diff --git a/networks/movement/movement-client/Cargo.toml b/networks/movement/movement-client/Cargo.toml index 206f9c54a..625ce06c7 100644 --- a/networks/movement/movement-client/Cargo.toml +++ b/networks/movement/movement-client/Cargo.toml @@ -47,6 +47,10 @@ path = "src/bin/e2e/transfer.rs" name = "movement-tests-e2e-key-rotation" path = "src/bin/e2e/key_rotation.rs" +[[bin]] +name = "movement-tests-sequence-number-ooo" +path = "src/bin/e2e/sequence_number_ooo.rs" + [dependencies] aptos-language-e2e-tests = { workspace = true } diff --git a/networks/movement/movement-client/src/bin/e2e/gas_dos.rs b/networks/movement/movement-client/src/bin/e2e/gas_dos.rs index 4cabd7d1e..6ca6920f3 100644 --- a/networks/movement/movement-client/src/bin/e2e/gas_dos.rs +++ b/networks/movement/movement-client/src/bin/e2e/gas_dos.rs @@ -171,7 +171,7 @@ pub async fn test_sending_failed_transaction() -> Result<(), anyhow::Error> { assert!(initial_balance > failed_balance); // TEST 2: Sending a transaction with a high sequence number - let too_high_sequence_number = alice.sequence_number() + 32 + 2; + let too_high_sequence_number = alice.sequence_number() + 1000 + 2; println!("Alice's sequence number: {}", alice.sequence_number()); println!("Too high sequence number: {}", too_high_sequence_number); let last_balance = failed_balance; @@ -180,7 +180,7 @@ pub async fn test_sending_failed_transaction() -> Result<(), anyhow::Error> { &alice, bob.address(), 100, - too_high_sequence_number, // too new tolerance is 32 + too_high_sequence_number, // too new tolerance is 1000 or more: ) .await?; diff --git a/networks/movement/movement-client/src/bin/e2e/sequence_number_ooo.rs b/networks/movement/movement-client/src/bin/e2e/sequence_number_ooo.rs new file mode 100644 index 000000000..05cfacfc4 --- /dev/null +++ b/networks/movement/movement-client/src/bin/e2e/sequence_number_ooo.rs @@ -0,0 +1,187 @@ +use anyhow::Context; +use bcs::to_bytes; +use movement_client::{ + coin_client::CoinClient, + move_types::{ + identifier::Identifier, + language_storage::{ModuleId, TypeTag}, + }, + rest_client::{Client, FaucetClient}, + transaction_builder::TransactionBuilder, + types::transaction::{EntryFunction, SignedTransaction, TransactionPayload}, + types::{account_address::AccountAddress, chain_id::ChainId, LocalAccount}, +}; +use once_cell::sync::Lazy; +use std::str::FromStr; +use std::time::SystemTime; +use std::time::UNIX_EPOCH; +use url::Url; + +static SUZUKA_CONFIG: Lazy = Lazy::new(|| { + let dot_movement = dot_movement::DotMovement::try_from_env().unwrap(); + let config = dot_movement.try_get_config_from_json::().unwrap(); + config +}); + +// :!:>section_1c +static NODE_URL: Lazy = Lazy::new(|| { + let node_connection_address = SUZUKA_CONFIG + .execution_config + .maptos_config + .client + .maptos_rest_connection_hostname + .clone(); + let node_connection_port = SUZUKA_CONFIG + .execution_config + .maptos_config + .client + .maptos_rest_connection_port + .clone(); + + let node_connection_url = + format!("http://{}:{}", node_connection_address, node_connection_port); + + Url::from_str(node_connection_url.as_str()).unwrap() +}); + +static FAUCET_URL: Lazy = Lazy::new(|| { + let faucet_listen_address = SUZUKA_CONFIG + .execution_config + .maptos_config + .client + .maptos_faucet_rest_connection_hostname + .clone(); + let faucet_listen_port = SUZUKA_CONFIG + .execution_config + .maptos_config + .client + .maptos_faucet_rest_connection_port + .clone(); + + let faucet_listen_url = format!("http://{}:{}", faucet_listen_address, faucet_listen_port); + + Url::from_str(faucet_listen_url.as_str()).unwrap() +}); +// <:!:section_1c + +pub async fn create_fake_signed_transaction( + chain_id: u8, + from_account: &LocalAccount, + to_account: AccountAddress, + amount: u64, + sequence_number: u64, +) -> Result { + let coin_type = "0x1::aptos_coin::AptosCoin"; + let timeout_secs = 600; // 10 minutes + let max_gas_amount = 5_000; + let gas_unit_price = 100; + + let expiration_time = + SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs() + timeout_secs; + + let transaction_builder = TransactionBuilder::new( + TransactionPayload::EntryFunction(EntryFunction::new( + ModuleId::new(AccountAddress::ONE, Identifier::new("coin").unwrap()), + Identifier::new("transfer")?, + vec![TypeTag::from_str(coin_type)?], + vec![to_bytes(&to_account)?, to_bytes(&amount)?], + )), + expiration_time, + ChainId::new(chain_id), + ); + + let raw_transaction = transaction_builder + .sender(from_account.address()) + .sequence_number(sequence_number) + .max_gas_amount(max_gas_amount) + .gas_unit_price(gas_unit_price) + .expiration_timestamp_secs(expiration_time) + .chain_id(ChainId::new(chain_id)) + .build(); + + let signed_transaction = from_account.sign_transaction(raw_transaction); + + Ok(signed_transaction) +} + +pub async fn test_sending_failed_transaction() -> Result<(), anyhow::Error> { + let rest_client = Client::new(NODE_URL.clone()); + let faucet_client = FaucetClient::new(FAUCET_URL.clone(), NODE_URL.clone()); + let coin_client = CoinClient::new(&rest_client); + + let alice = LocalAccount::generate(&mut rand::rngs::OsRng); + let bob = LocalAccount::generate(&mut rand::rngs::OsRng); + + println!("=== Addresses ==="); + println!("Alice: {}", alice.address().to_hex_literal()); + println!("Bob: {}", bob.address().to_hex_literal()); + + faucet_client + .fund(alice.address(), 100_000_000) + .await + .context("Failed to fund Alice's account")?; + + faucet_client + .create_account(bob.address()) + .await + .context("Failed to fund Bob's account")?; + + let chain_id = rest_client + .get_index() + .await + .context("Failed to get chain ID")? + .inner() + .chain_id; + println!("\n=== Initial Balance ==="); + let initial_balance = coin_client + .get_account_balance(&alice.address()) + .await + .context("Failed to get Alice's account balance")?; + println!("Alice: {:?}", initial_balance); + + // Send in ooo sequence numbers + // create transaction 1 + let transaction_1 = create_fake_signed_transaction( + chain_id, + &alice, + bob.address(), + 100, + alice.sequence_number(), + ) + .await?; + + // create transaction 2 + let transaction_2 = create_fake_signed_transaction( + chain_id, + &alice, + bob.address(), + 100, + alice.sequence_number() + 1, + ) + .await?; + + // submit 2 then 1 + rest_client.submit(&transaction_2).await?; + rest_client.submit(&transaction_1).await?; + + // wait for both the complete + rest_client.wait_for_signed_transaction(&transaction_1).await?; + rest_client.wait_for_signed_transaction(&transaction_2).await?; + + // validate the effect of the transactions, the balance should be less than the initial balance + let balance = coin_client + .get_account_balance(&alice.address()) + .await + .context("Failed to get Alice's account balance")?; + println!("\n=== After Tx#1 and Tx#2 ==="); + println!("Alice: {:?}", balance); + assert!(initial_balance > balance); + + Ok(()) +} + +#[tokio::main] +async fn main() -> Result<(), anyhow::Error> { + test_sending_failed_transaction().await?; + Ok(()) +} diff --git a/process-compose/movement-full-node/process-compose.test-sequence-number-ooo.yml b/process-compose/movement-full-node/process-compose.test-sequence-number-ooo.yml new file mode 100644 index 000000000..9e84e4c31 --- /dev/null +++ b/process-compose/movement-full-node/process-compose.test-sequence-number-ooo.yml @@ -0,0 +1,17 @@ +version: "3" + +environment: + +processes: + + # Test whether the full node is resistant to Gas DOS + test-sequence-number-ooo: + command: | + cargo run --bin movement-tests-sequence-number-ooo + depends_on: + movement-full-node: + condition: process_healthy + movement-faucet: + condition: process_healthy + availability: + exit_on_end: true \ No newline at end of file diff --git a/protocol-units/bridge/contracts/minter/build/Minter/BuildInfo.yaml b/protocol-units/bridge/contracts/minter/build/Minter/BuildInfo.yaml new file mode 100644 index 000000000..cf9dd3d57 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/BuildInfo.yaml @@ -0,0 +1,53 @@ +--- +compiled_package_info: + package_name: Minter + address_alias_instantiation: + Extensions: "0000000000000000000000000000000000000000000000000000000000000001" + aptos_framework: "0000000000000000000000000000000000000000000000000000000000000001" + aptos_fungible_asset: 000000000000000000000000000000000000000000000000000000000000000a + aptos_std: "0000000000000000000000000000000000000000000000000000000000000001" + aptos_token: "0000000000000000000000000000000000000000000000000000000000000003" + core_resources: 000000000000000000000000000000000000000000000000000000000a550c18 + std: "0000000000000000000000000000000000000000000000000000000000000001" + vm: "0000000000000000000000000000000000000000000000000000000000000000" + vm_reserved: "0000000000000000000000000000000000000000000000000000000000000000" + source_digest: A8817968ED43F9948E78519424C10EFF89A5BAFA9A2E3927121B387159584519 + build_flags: + dev_mode: false + test_mode: false + override_std: ~ + generate_docs: false + generate_abis: false + generate_move_model: true + full_model_generation: false + install_dir: ~ + force_recompilation: false + additional_named_addresses: {} + architecture: ~ + fetch_deps_only: false + skip_fetch_latest_git_deps: false + compiler_config: + bytecode_version: ~ + known_attributes: + - bytecode_instruction + - deprecated + - event + - expected_failure + - "fmt::skip" + - legacy_entry_fun + - "lint::allow_unsafe_randomness" + - native_interface + - randomness + - resource_group + - resource_group_member + - test + - test_only + - verify_only + - view + skip_attribute_checks: false + compiler_version: ~ + language_version: ~ +dependencies: + - AptosFramework + - AptosStdlib + - MoveStdlib diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/account.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/account.mv new file mode 100644 index 000000000..fb3ab7dfd Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/account.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aggregator.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aggregator.mv new file mode 100644 index 000000000..e6e96622e Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aggregator.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aggregator_factory.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aggregator_factory.mv new file mode 100644 index 000000000..dbceac2cb Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aggregator_factory.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aggregator_v2.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aggregator_v2.mv new file mode 100644 index 000000000..ffb7e84b6 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aggregator_v2.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aptos_account.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aptos_account.mv new file mode 100644 index 000000000..ff4124be9 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aptos_account.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aptos_coin.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aptos_coin.mv new file mode 100644 index 000000000..eecb14ac5 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aptos_coin.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aptos_governance.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aptos_governance.mv new file mode 100644 index 000000000..54f510ae0 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/aptos_governance.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/atomic_bridge.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/atomic_bridge.mv new file mode 100644 index 000000000..d36a676f7 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/atomic_bridge.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/atomic_bridge_configuration.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/atomic_bridge_configuration.mv new file mode 100644 index 000000000..5480be035 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/atomic_bridge_configuration.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/atomic_bridge_counterparty.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/atomic_bridge_counterparty.mv new file mode 100644 index 000000000..a2772e233 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/atomic_bridge_counterparty.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/atomic_bridge_initiator.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/atomic_bridge_initiator.mv new file mode 100644 index 000000000..e8fc048dc Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/atomic_bridge_initiator.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/atomic_bridge_store.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/atomic_bridge_store.mv new file mode 100644 index 000000000..7f777aaf9 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/atomic_bridge_store.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/block.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/block.mv new file mode 100644 index 000000000..8dc302e65 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/block.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/chain_id.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/chain_id.mv new file mode 100644 index 000000000..c1c9d214c Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/chain_id.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/chain_status.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/chain_status.mv new file mode 100644 index 000000000..83f53dba1 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/chain_status.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/code.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/code.mv new file mode 100644 index 000000000..f2fdf6659 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/code.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/coin.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/coin.mv new file mode 100644 index 000000000..6c44e357a Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/coin.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/config_buffer.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/config_buffer.mv new file mode 100644 index 000000000..2623d5a0e Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/config_buffer.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/consensus_config.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/consensus_config.mv new file mode 100644 index 000000000..967d2663b Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/consensus_config.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/create_signer.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/create_signer.mv new file mode 100644 index 000000000..0e486390d Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/create_signer.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/delegation_pool.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/delegation_pool.mv new file mode 100644 index 000000000..d67dccb18 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/delegation_pool.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/dispatchable_fungible_asset.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/dispatchable_fungible_asset.mv new file mode 100644 index 000000000..6a223bb53 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/dispatchable_fungible_asset.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/dkg.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/dkg.mv new file mode 100644 index 000000000..f4ddbbecb Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/dkg.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/ethereum.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/ethereum.mv new file mode 100644 index 000000000..52d8bb9b0 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/ethereum.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/event.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/event.mv new file mode 100644 index 000000000..ca9df5ed8 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/event.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/execution_config.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/execution_config.mv new file mode 100644 index 000000000..f338850c5 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/execution_config.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/function_info.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/function_info.mv new file mode 100644 index 000000000..2d6423db2 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/function_info.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/fungible_asset.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/fungible_asset.mv new file mode 100644 index 000000000..c00b5f37a Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/fungible_asset.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/gas_schedule.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/gas_schedule.mv new file mode 100644 index 000000000..57e5ab297 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/gas_schedule.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/genesis.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/genesis.mv new file mode 100644 index 000000000..1e916af43 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/genesis.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/governance_proposal.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/governance_proposal.mv new file mode 100644 index 000000000..f875f4891 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/governance_proposal.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/governed_gas_pool.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/governed_gas_pool.mv new file mode 100644 index 000000000..29c7f3d9a Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/governed_gas_pool.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/guid.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/guid.mv new file mode 100644 index 000000000..cb8277858 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/guid.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/jwk_consensus_config.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/jwk_consensus_config.mv new file mode 100644 index 000000000..d9ffa6bb5 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/jwk_consensus_config.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/jwks.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/jwks.mv new file mode 100644 index 000000000..d4771e4a9 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/jwks.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/keyless_account.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/keyless_account.mv new file mode 100644 index 000000000..460d109d3 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/keyless_account.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/managed_coin.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/managed_coin.mv new file mode 100644 index 000000000..b634a5d2d Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/managed_coin.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/multisig_account.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/multisig_account.mv new file mode 100644 index 000000000..554ed5c4d Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/multisig_account.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/native_bridge.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/native_bridge.mv new file mode 100644 index 000000000..454c6a3ac Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/native_bridge.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/object.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/object.mv new file mode 100644 index 000000000..4a69064eb Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/object.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/object_code_deployment.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/object_code_deployment.mv new file mode 100644 index 000000000..367e0a835 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/object_code_deployment.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/optional_aggregator.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/optional_aggregator.mv new file mode 100644 index 000000000..9d9447556 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/optional_aggregator.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/primary_fungible_store.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/primary_fungible_store.mv new file mode 100644 index 000000000..f602682b3 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/primary_fungible_store.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/randomness.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/randomness.mv new file mode 100644 index 000000000..ea1d4a4f3 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/randomness.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/randomness_api_v0_config.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/randomness_api_v0_config.mv new file mode 100644 index 000000000..1ff51ae75 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/randomness_api_v0_config.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/randomness_config.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/randomness_config.mv new file mode 100644 index 000000000..fa222a57b Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/randomness_config.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/randomness_config_seqnum.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/randomness_config_seqnum.mv new file mode 100644 index 000000000..a88da7d23 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/randomness_config_seqnum.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/reconfiguration.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/reconfiguration.mv new file mode 100644 index 000000000..46c96a411 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/reconfiguration.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/reconfiguration_state.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/reconfiguration_state.mv new file mode 100644 index 000000000..0817b53bb Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/reconfiguration_state.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/reconfiguration_with_dkg.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/reconfiguration_with_dkg.mv new file mode 100644 index 000000000..349bb150e Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/reconfiguration_with_dkg.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/resource_account.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/resource_account.mv new file mode 100644 index 000000000..349072440 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/resource_account.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/stake.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/stake.mv new file mode 100644 index 000000000..4433a7dd0 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/stake.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/staking_config.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/staking_config.mv new file mode 100644 index 000000000..9379a3bd9 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/staking_config.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/staking_contract.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/staking_contract.mv new file mode 100644 index 000000000..2e71ebaac Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/staking_contract.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/staking_proxy.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/staking_proxy.mv new file mode 100644 index 000000000..4b023ea6d Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/staking_proxy.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/state_storage.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/state_storage.mv new file mode 100644 index 000000000..1fd5adab2 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/state_storage.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/storage_gas.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/storage_gas.mv new file mode 100644 index 000000000..24961764f Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/storage_gas.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/system_addresses.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/system_addresses.mv new file mode 100644 index 000000000..cb6f65540 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/system_addresses.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/timestamp.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/timestamp.mv new file mode 100644 index 000000000..8f1d50a3c Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/timestamp.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/transaction_context.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/transaction_context.mv new file mode 100644 index 000000000..7802ca953 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/transaction_context.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/transaction_fee.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/transaction_fee.mv new file mode 100644 index 000000000..e7d7992bf Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/transaction_fee.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/transaction_validation.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/transaction_validation.mv new file mode 100644 index 000000000..851cb6159 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/transaction_validation.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/util.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/util.mv new file mode 100644 index 000000000..a39b8d91b Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/util.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/validator_consensus_info.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/validator_consensus_info.mv new file mode 100644 index 000000000..19231aa95 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/validator_consensus_info.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/version.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/version.mv new file mode 100644 index 000000000..3e0ca7de4 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/version.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/vesting.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/vesting.mv new file mode 100644 index 000000000..82ed76c34 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/vesting.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/voting.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/voting.mv new file mode 100644 index 000000000..abcda7971 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosFramework/voting.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/any.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/any.mv new file mode 100644 index 000000000..790ec873f Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/any.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/aptos_hash.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/aptos_hash.mv new file mode 100644 index 000000000..2947f36cf Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/aptos_hash.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/big_vector.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/big_vector.mv new file mode 100644 index 000000000..7288a6189 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/big_vector.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/bls12381.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/bls12381.mv new file mode 100644 index 000000000..82cfe5766 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/bls12381.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/bls12381_algebra.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/bls12381_algebra.mv new file mode 100644 index 000000000..bb7d580bb Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/bls12381_algebra.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/bn254_algebra.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/bn254_algebra.mv new file mode 100644 index 000000000..4c5e456d7 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/bn254_algebra.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/capability.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/capability.mv new file mode 100644 index 000000000..60e919e97 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/capability.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/comparator.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/comparator.mv new file mode 100644 index 000000000..151b4188e Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/comparator.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/copyable_any.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/copyable_any.mv new file mode 100644 index 000000000..433f1ae5e Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/copyable_any.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/crypto_algebra.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/crypto_algebra.mv new file mode 100644 index 000000000..477fbb609 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/crypto_algebra.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/debug.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/debug.mv new file mode 100644 index 000000000..54fd205df Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/debug.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/ed25519.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/ed25519.mv new file mode 100644 index 000000000..3686c4550 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/ed25519.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/fixed_point64.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/fixed_point64.mv new file mode 100644 index 000000000..cdf185b8f Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/fixed_point64.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/from_bcs.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/from_bcs.mv new file mode 100644 index 000000000..92d6d1e7c Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/from_bcs.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/math128.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/math128.mv new file mode 100644 index 000000000..7979abef7 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/math128.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/math64.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/math64.mv new file mode 100644 index 000000000..08b84e3cc Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/math64.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/math_fixed.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/math_fixed.mv new file mode 100644 index 000000000..bb74af93e Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/math_fixed.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/math_fixed64.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/math_fixed64.mv new file mode 100644 index 000000000..9cdb38324 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/math_fixed64.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/multi_ed25519.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/multi_ed25519.mv new file mode 100644 index 000000000..a76e717a9 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/multi_ed25519.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/pool_u64.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/pool_u64.mv new file mode 100644 index 000000000..8763de5c6 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/pool_u64.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/pool_u64_unbound.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/pool_u64_unbound.mv new file mode 100644 index 000000000..800876ae1 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/pool_u64_unbound.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/ristretto255.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/ristretto255.mv new file mode 100644 index 000000000..eceefd3d7 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/ristretto255.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/ristretto255_bulletproofs.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/ristretto255_bulletproofs.mv new file mode 100644 index 000000000..de94a752d Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/ristretto255_bulletproofs.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/ristretto255_elgamal.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/ristretto255_elgamal.mv new file mode 100644 index 000000000..8de1f547a Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/ristretto255_elgamal.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/ristretto255_pedersen.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/ristretto255_pedersen.mv new file mode 100644 index 000000000..6aa23a90e Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/ristretto255_pedersen.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/secp256k1.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/secp256k1.mv new file mode 100644 index 000000000..bf0d3b680 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/secp256k1.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/simple_map.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/simple_map.mv new file mode 100644 index 000000000..4f729b6e3 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/simple_map.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/smart_table.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/smart_table.mv new file mode 100644 index 000000000..105447250 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/smart_table.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/smart_vector.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/smart_vector.mv new file mode 100644 index 000000000..bc7a1f711 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/smart_vector.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/string_utils.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/string_utils.mv new file mode 100644 index 000000000..2af920974 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/string_utils.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/table.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/table.mv new file mode 100644 index 000000000..6a0d6749a Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/table.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/table_with_length.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/table_with_length.mv new file mode 100644 index 000000000..868c75252 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/table_with_length.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/type_info.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/type_info.mv new file mode 100644 index 000000000..5178daf0e Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/AptosStdlib/type_info.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/acl.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/acl.mv new file mode 100644 index 000000000..2e88d6816 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/acl.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/bcs.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/bcs.mv new file mode 100644 index 000000000..3c0aa2c6c Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/bcs.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/bit_vector.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/bit_vector.mv new file mode 100644 index 000000000..9b40a5cc4 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/bit_vector.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/error.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/error.mv new file mode 100644 index 000000000..8a8c47a3d Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/error.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/features.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/features.mv new file mode 100644 index 000000000..c7d82c577 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/features.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/fixed_point32.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/fixed_point32.mv new file mode 100644 index 000000000..40e1638d3 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/fixed_point32.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/hash.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/hash.mv new file mode 100644 index 000000000..4ce035be4 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/hash.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/option.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/option.mv new file mode 100644 index 000000000..5430b7f1d Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/option.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/signer.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/signer.mv new file mode 100644 index 000000000..4e4ddb18d Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/signer.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/string.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/string.mv new file mode 100644 index 000000000..cef687067 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/string.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/vector.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/vector.mv new file mode 100644 index 000000000..278f014d3 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_modules/dependencies/MoveStdlib/vector.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/bytecode_scripts/main.mv b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_scripts/main.mv new file mode 100644 index 000000000..74c26e3e2 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/bytecode_scripts/main.mv differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/account.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/account.mvsm new file mode 100644 index 000000000..90d2cecb7 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/account.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aggregator.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aggregator.mvsm new file mode 100644 index 000000000..3ce03842d Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aggregator.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aggregator_factory.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aggregator_factory.mvsm new file mode 100644 index 000000000..3754ea941 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aggregator_factory.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aggregator_v2.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aggregator_v2.mvsm new file mode 100644 index 000000000..bab702f60 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aggregator_v2.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aptos_account.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aptos_account.mvsm new file mode 100644 index 000000000..08ad2fec6 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aptos_account.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aptos_coin.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aptos_coin.mvsm new file mode 100644 index 000000000..775f13fa2 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aptos_coin.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aptos_governance.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aptos_governance.mvsm new file mode 100644 index 000000000..f556c8423 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/aptos_governance.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/atomic_bridge.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/atomic_bridge.mvsm new file mode 100644 index 000000000..8e9c4e34b Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/atomic_bridge.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/atomic_bridge_configuration.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/atomic_bridge_configuration.mvsm new file mode 100644 index 000000000..b71944edb Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/atomic_bridge_configuration.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/atomic_bridge_counterparty.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/atomic_bridge_counterparty.mvsm new file mode 100644 index 000000000..e001f02a2 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/atomic_bridge_counterparty.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/atomic_bridge_initiator.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/atomic_bridge_initiator.mvsm new file mode 100644 index 000000000..8d43ad797 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/atomic_bridge_initiator.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/atomic_bridge_store.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/atomic_bridge_store.mvsm new file mode 100644 index 000000000..040b5698c Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/atomic_bridge_store.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/block.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/block.mvsm new file mode 100644 index 000000000..28cc2a928 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/block.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/chain_id.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/chain_id.mvsm new file mode 100644 index 000000000..0de8e7f50 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/chain_id.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/chain_status.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/chain_status.mvsm new file mode 100644 index 000000000..a595891e7 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/chain_status.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/code.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/code.mvsm new file mode 100644 index 000000000..a08bfc33e Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/code.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/coin.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/coin.mvsm new file mode 100644 index 000000000..6b6780478 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/coin.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/config_buffer.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/config_buffer.mvsm new file mode 100644 index 000000000..e10c72e06 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/config_buffer.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/consensus_config.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/consensus_config.mvsm new file mode 100644 index 000000000..76c2a5f14 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/consensus_config.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/create_signer.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/create_signer.mvsm new file mode 100644 index 000000000..7a9916141 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/create_signer.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/delegation_pool.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/delegation_pool.mvsm new file mode 100644 index 000000000..8797ce38f Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/delegation_pool.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/dispatchable_fungible_asset.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/dispatchable_fungible_asset.mvsm new file mode 100644 index 000000000..26b63052e Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/dispatchable_fungible_asset.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/dkg.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/dkg.mvsm new file mode 100644 index 000000000..a0154c808 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/dkg.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/ethereum.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/ethereum.mvsm new file mode 100644 index 000000000..2f3260a6c Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/ethereum.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/event.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/event.mvsm new file mode 100644 index 000000000..caf7d6a97 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/event.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/execution_config.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/execution_config.mvsm new file mode 100644 index 000000000..3a405e2d0 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/execution_config.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/function_info.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/function_info.mvsm new file mode 100644 index 000000000..e3841bcbc Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/function_info.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/fungible_asset.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/fungible_asset.mvsm new file mode 100644 index 000000000..07b5b10d6 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/fungible_asset.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/gas_schedule.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/gas_schedule.mvsm new file mode 100644 index 000000000..e0b96c0e0 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/gas_schedule.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/genesis.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/genesis.mvsm new file mode 100644 index 000000000..bd8983052 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/genesis.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/governance_proposal.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/governance_proposal.mvsm new file mode 100644 index 000000000..feb6c8283 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/governance_proposal.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/governed_gas_pool.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/governed_gas_pool.mvsm new file mode 100644 index 000000000..9abd73886 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/governed_gas_pool.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/guid.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/guid.mvsm new file mode 100644 index 000000000..18d867919 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/guid.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/jwk_consensus_config.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/jwk_consensus_config.mvsm new file mode 100644 index 000000000..8105e2714 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/jwk_consensus_config.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/jwks.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/jwks.mvsm new file mode 100644 index 000000000..a6896910c Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/jwks.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/keyless_account.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/keyless_account.mvsm new file mode 100644 index 000000000..4a73ad3c1 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/keyless_account.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/managed_coin.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/managed_coin.mvsm new file mode 100644 index 000000000..07a16981a Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/managed_coin.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/multisig_account.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/multisig_account.mvsm new file mode 100644 index 000000000..2b89adb6c Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/multisig_account.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/native_bridge.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/native_bridge.mvsm new file mode 100644 index 000000000..38b3abd7e Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/native_bridge.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/object.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/object.mvsm new file mode 100644 index 000000000..a86d6e4b0 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/object.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/object_code_deployment.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/object_code_deployment.mvsm new file mode 100644 index 000000000..be8523251 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/object_code_deployment.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/optional_aggregator.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/optional_aggregator.mvsm new file mode 100644 index 000000000..d9a21c060 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/optional_aggregator.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/primary_fungible_store.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/primary_fungible_store.mvsm new file mode 100644 index 000000000..4f421d7ed Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/primary_fungible_store.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/randomness.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/randomness.mvsm new file mode 100644 index 000000000..ad8d4df4c Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/randomness.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/randomness_api_v0_config.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/randomness_api_v0_config.mvsm new file mode 100644 index 000000000..8a25389f8 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/randomness_api_v0_config.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/randomness_config.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/randomness_config.mvsm new file mode 100644 index 000000000..aab0472a0 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/randomness_config.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/randomness_config_seqnum.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/randomness_config_seqnum.mvsm new file mode 100644 index 000000000..98e50463d Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/randomness_config_seqnum.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/reconfiguration.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/reconfiguration.mvsm new file mode 100644 index 000000000..e6af9125a Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/reconfiguration.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/reconfiguration_state.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/reconfiguration_state.mvsm new file mode 100644 index 000000000..3578f4c20 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/reconfiguration_state.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/reconfiguration_with_dkg.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/reconfiguration_with_dkg.mvsm new file mode 100644 index 000000000..7919d776c Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/reconfiguration_with_dkg.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/resource_account.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/resource_account.mvsm new file mode 100644 index 000000000..1c59ca7a0 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/resource_account.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/stake.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/stake.mvsm new file mode 100644 index 000000000..2fc815e45 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/stake.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/staking_config.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/staking_config.mvsm new file mode 100644 index 000000000..cf31d1d4a Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/staking_config.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/staking_contract.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/staking_contract.mvsm new file mode 100644 index 000000000..49e677ff8 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/staking_contract.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/staking_proxy.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/staking_proxy.mvsm new file mode 100644 index 000000000..d5c234b1c Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/staking_proxy.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/state_storage.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/state_storage.mvsm new file mode 100644 index 000000000..bbc8aa7e2 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/state_storage.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/storage_gas.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/storage_gas.mvsm new file mode 100644 index 000000000..32ce3f165 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/storage_gas.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/system_addresses.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/system_addresses.mvsm new file mode 100644 index 000000000..4acd7ac99 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/system_addresses.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/timestamp.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/timestamp.mvsm new file mode 100644 index 000000000..d10025e9a Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/timestamp.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/transaction_context.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/transaction_context.mvsm new file mode 100644 index 000000000..0fd7b55e7 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/transaction_context.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/transaction_fee.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/transaction_fee.mvsm new file mode 100644 index 000000000..7e65eba54 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/transaction_fee.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/transaction_validation.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/transaction_validation.mvsm new file mode 100644 index 000000000..3029b8126 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/transaction_validation.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/util.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/util.mvsm new file mode 100644 index 000000000..92a16e7c3 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/util.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/validator_consensus_info.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/validator_consensus_info.mvsm new file mode 100644 index 000000000..feb1e5a18 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/validator_consensus_info.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/version.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/version.mvsm new file mode 100644 index 000000000..22bd6f449 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/version.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/vesting.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/vesting.mvsm new file mode 100644 index 000000000..64b655000 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/vesting.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/voting.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/voting.mvsm new file mode 100644 index 000000000..7dc7c5062 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosFramework/voting.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/any.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/any.mvsm new file mode 100644 index 000000000..d2293fad0 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/any.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/aptos_hash.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/aptos_hash.mvsm new file mode 100644 index 000000000..cab6ffa19 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/aptos_hash.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/big_vector.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/big_vector.mvsm new file mode 100644 index 000000000..e4503c8a4 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/big_vector.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/bls12381.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/bls12381.mvsm new file mode 100644 index 000000000..f0df819f6 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/bls12381.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/bls12381_algebra.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/bls12381_algebra.mvsm new file mode 100644 index 000000000..52e021183 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/bls12381_algebra.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/bn254_algebra.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/bn254_algebra.mvsm new file mode 100644 index 000000000..363b4e60b Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/bn254_algebra.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/capability.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/capability.mvsm new file mode 100644 index 000000000..b0ed6884b Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/capability.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/comparator.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/comparator.mvsm new file mode 100644 index 000000000..61811dee3 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/comparator.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/copyable_any.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/copyable_any.mvsm new file mode 100644 index 000000000..73ca14bf2 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/copyable_any.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/crypto_algebra.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/crypto_algebra.mvsm new file mode 100644 index 000000000..e5ec26658 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/crypto_algebra.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/debug.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/debug.mvsm new file mode 100644 index 000000000..b13356a5b Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/debug.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/ed25519.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/ed25519.mvsm new file mode 100644 index 000000000..497097453 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/ed25519.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/fixed_point64.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/fixed_point64.mvsm new file mode 100644 index 000000000..9a16cecf4 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/fixed_point64.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/from_bcs.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/from_bcs.mvsm new file mode 100644 index 000000000..ce080a6e5 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/from_bcs.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/math128.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/math128.mvsm new file mode 100644 index 000000000..ee5f59f5b Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/math128.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/math64.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/math64.mvsm new file mode 100644 index 000000000..c71a06230 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/math64.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/math_fixed.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/math_fixed.mvsm new file mode 100644 index 000000000..720e38b1e Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/math_fixed.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/math_fixed64.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/math_fixed64.mvsm new file mode 100644 index 000000000..0ee2e6afe Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/math_fixed64.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/multi_ed25519.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/multi_ed25519.mvsm new file mode 100644 index 000000000..b80755a0e Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/multi_ed25519.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/pool_u64.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/pool_u64.mvsm new file mode 100644 index 000000000..d9f3a16f1 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/pool_u64.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/pool_u64_unbound.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/pool_u64_unbound.mvsm new file mode 100644 index 000000000..3a59af396 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/pool_u64_unbound.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/ristretto255.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/ristretto255.mvsm new file mode 100644 index 000000000..9357430fd Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/ristretto255.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/ristretto255_bulletproofs.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/ristretto255_bulletproofs.mvsm new file mode 100644 index 000000000..b94a7fbd5 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/ristretto255_bulletproofs.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/ristretto255_elgamal.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/ristretto255_elgamal.mvsm new file mode 100644 index 000000000..963ebc650 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/ristretto255_elgamal.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/ristretto255_pedersen.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/ristretto255_pedersen.mvsm new file mode 100644 index 000000000..956c3094b Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/ristretto255_pedersen.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/secp256k1.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/secp256k1.mvsm new file mode 100644 index 000000000..16356ce8c Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/secp256k1.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/simple_map.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/simple_map.mvsm new file mode 100644 index 000000000..027901cda Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/simple_map.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/smart_table.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/smart_table.mvsm new file mode 100644 index 000000000..7510d6e55 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/smart_table.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/smart_vector.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/smart_vector.mvsm new file mode 100644 index 000000000..a2d8c5df6 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/smart_vector.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/string_utils.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/string_utils.mvsm new file mode 100644 index 000000000..6d1b387f3 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/string_utils.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/table.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/table.mvsm new file mode 100644 index 000000000..8bd26fdcd Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/table.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/table_with_length.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/table_with_length.mvsm new file mode 100644 index 000000000..6a8d3f6da Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/table_with_length.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/type_info.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/type_info.mvsm new file mode 100644 index 000000000..60808db5b Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/AptosStdlib/type_info.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/acl.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/acl.mvsm new file mode 100644 index 000000000..01b721a86 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/acl.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/bcs.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/bcs.mvsm new file mode 100644 index 000000000..3b9a902f6 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/bcs.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/bit_vector.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/bit_vector.mvsm new file mode 100644 index 000000000..9a792ea26 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/bit_vector.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/error.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/error.mvsm new file mode 100644 index 000000000..308789b9c Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/error.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/features.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/features.mvsm new file mode 100644 index 000000000..ec0c06d2b Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/features.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/fixed_point32.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/fixed_point32.mvsm new file mode 100644 index 000000000..239b9a103 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/fixed_point32.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/hash.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/hash.mvsm new file mode 100644 index 000000000..9ce46ed07 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/hash.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/option.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/option.mvsm new file mode 100644 index 000000000..78b6ca4ee Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/option.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/signer.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/signer.mvsm new file mode 100644 index 000000000..0fe30a029 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/signer.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/string.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/string.mvsm new file mode 100644 index 000000000..158107745 Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/string.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/vector.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/vector.mvsm new file mode 100644 index 000000000..b4c458d0f Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/dependencies/MoveStdlib/vector.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/source_maps/main.mvsm b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/main.mvsm new file mode 100644 index 000000000..96c2e768b Binary files /dev/null and b/protocol-units/bridge/contracts/minter/build/Minter/source_maps/main.mvsm differ diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/account.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/account.move new file mode 100644 index 000000000..6dcd2800a --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/account.move @@ -0,0 +1,1534 @@ +module aptos_framework::account { + use std::bcs; + use std::error; + use std::hash; + use std::option::{Self, Option}; + use std::signer; + use std::vector; + use aptos_framework::chain_id; + use aptos_framework::create_signer::create_signer; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::guid; + use aptos_framework::system_addresses; + use aptos_std::ed25519; + use aptos_std::from_bcs; + use aptos_std::multi_ed25519; + use aptos_std::table::{Self, Table}; + use aptos_std::type_info::{Self, TypeInfo}; + + friend aptos_framework::aptos_account; + friend aptos_framework::coin; + friend aptos_framework::genesis; + friend aptos_framework::multisig_account; + friend aptos_framework::resource_account; + friend aptos_framework::transaction_validation; + friend aptos_framework::governed_gas_pool; + + #[event] + struct KeyRotation has drop, store { + account: address, + old_authentication_key: vector, + new_authentication_key: vector, + } + + /// Resource representing an account. + struct Account has key, store { + authentication_key: vector, + sequence_number: u64, + guid_creation_num: u64, + coin_register_events: EventHandle, + key_rotation_events: EventHandle, + rotation_capability_offer: CapabilityOffer, + signer_capability_offer: CapabilityOffer, + } + + struct KeyRotationEvent has drop, store { + old_authentication_key: vector, + new_authentication_key: vector, + } + + struct CoinRegisterEvent has drop, store { + type_info: TypeInfo, + } + + struct CapabilityOffer has store { for: Option
} + + struct RotationCapability has drop, store { account: address } + + struct SignerCapability has drop, store { account: address } + + /// It is easy to fetch the authentication key of an address by simply reading it from the `Account` struct at that address. + /// The table in this struct makes it possible to do a reverse lookup: it maps an authentication key, to the address of the account which has that authentication key set. + /// + /// This mapping is needed when recovering wallets for accounts whose authentication key has been rotated. + /// + /// For example, imagine a freshly-created wallet with address `a` and thus also with authentication key `a`, derived from a PK `pk_a` with corresponding SK `sk_a`. + /// It is easy to recover such a wallet given just the secret key `sk_a`, since the PK can be derived from the SK, the authentication key can then be derived from the PK, and the address equals the authentication key (since there was no key rotation). + /// + /// However, if such a wallet rotates its authentication key to `b` derived from a different PK `pk_b` with SK `sk_b`, how would account recovery work? + /// The recovered address would no longer be 'a'; it would be `b`, which is incorrect. + /// This struct solves this problem by mapping the new authentication key `b` to the original address `a` and thus helping the wallet software during recovery find the correct address. + struct OriginatingAddress has key { + address_map: Table, + } + + /// This structs stores the challenge message that should be signed during key rotation. First, this struct is + /// signed by the account owner's current public key, which proves possession of a capability to rotate the key. + /// Second, this struct is signed by the new public key that the account owner wants to rotate to, which proves + /// knowledge of this new public key's associated secret key. These two signatures cannot be replayed in another + /// context because they include the TXN's unique sequence number. + struct RotationProofChallenge has copy, drop { + sequence_number: u64, + // the sequence number of the account whose key is being rotated + originator: address, + // the address of the account whose key is being rotated + current_auth_key: address, + // the current authentication key of the account whose key is being rotated + new_public_key: vector, + // the new public key that the account owner wants to rotate to + } + + /// Deprecated struct - newest version is `RotationCapabilityOfferProofChallengeV2` + struct RotationCapabilityOfferProofChallenge has drop { + sequence_number: u64, + recipient_address: address, + } + + /// Deprecated struct - newest version is `SignerCapabilityOfferProofChallengeV2` + struct SignerCapabilityOfferProofChallenge has drop { + sequence_number: u64, + recipient_address: address, + } + + /// This struct stores the challenge message that should be signed by the source account, when the source account + /// is delegating its rotation capability to the `recipient_address`. + /// This V2 struct adds the `chain_id` and `source_address` to the challenge message, which prevents replaying the challenge message. + struct RotationCapabilityOfferProofChallengeV2 has drop { + chain_id: u8, + sequence_number: u64, + source_address: address, + recipient_address: address, + } + + struct SignerCapabilityOfferProofChallengeV2 has copy, drop { + sequence_number: u64, + source_address: address, + recipient_address: address, + } + + const MAX_U64: u128 = 18446744073709551615; + const ZERO_AUTH_KEY: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; + + /// Scheme identifier for Ed25519 signatures used to derive authentication keys for Ed25519 public keys. + const ED25519_SCHEME: u8 = 0; + /// Scheme identifier for MultiEd25519 signatures used to derive authentication keys for MultiEd25519 public keys. + const MULTI_ED25519_SCHEME: u8 = 1; + /// Scheme identifier used when hashing an account's address together with a seed to derive the address (not the + /// authentication key) of a resource account. This is an abuse of the notion of a scheme identifier which, for now, + /// serves to domain separate hashes used to derive resource account addresses from hashes used to derive + /// authentication keys. Without such separation, an adversary could create (and get a signer for) a resource account + /// whose address matches an existing address of a MultiEd25519 wallet. + const DERIVE_RESOURCE_ACCOUNT_SCHEME: u8 = 255; + + /// Account already exists + const EACCOUNT_ALREADY_EXISTS: u64 = 1; + /// Account does not exist + const EACCOUNT_DOES_NOT_EXIST: u64 = 2; + /// Sequence number exceeds the maximum value for a u64 + const ESEQUENCE_NUMBER_TOO_BIG: u64 = 3; + /// The provided authentication key has an invalid length + const EMALFORMED_AUTHENTICATION_KEY: u64 = 4; + /// Cannot create account because address is reserved + const ECANNOT_RESERVED_ADDRESS: u64 = 5; + /// Transaction exceeded its allocated max gas + const EOUT_OF_GAS: u64 = 6; + /// Specified current public key is not correct + const EWRONG_CURRENT_PUBLIC_KEY: u64 = 7; + /// Specified proof of knowledge required to prove ownership of a public key is invalid + const EINVALID_PROOF_OF_KNOWLEDGE: u64 = 8; + /// The caller does not have a digital-signature-based capability to call this function + const ENO_CAPABILITY: u64 = 9; + /// The caller does not have a valid rotation capability offer from the other account + const EINVALID_ACCEPT_ROTATION_CAPABILITY: u64 = 10; + /// Address to create is not a valid reserved address for Aptos framework + const ENO_VALID_FRAMEWORK_RESERVED_ADDRESS: u64 = 11; + /// Specified scheme required to proceed with the smart contract operation - can only be ED25519_SCHEME(0) OR MULTI_ED25519_SCHEME(1) + const EINVALID_SCHEME: u64 = 12; + /// Abort the transaction if the expected originating address is different from the originating address on-chain + const EINVALID_ORIGINATING_ADDRESS: u64 = 13; + /// The signer capability offer doesn't exist at the given address + const ENO_SUCH_SIGNER_CAPABILITY: u64 = 14; + /// An attempt to create a resource account on a claimed account + const ERESOURCE_ACCCOUNT_EXISTS: u64 = 15; + /// An attempt to create a resource account on an account that has a committed transaction + const EACCOUNT_ALREADY_USED: u64 = 16; + /// Offerer address doesn't exist + const EOFFERER_ADDRESS_DOES_NOT_EXIST: u64 = 17; + /// The specified rotation capablity offer does not exist at the specified offerer address + const ENO_SUCH_ROTATION_CAPABILITY_OFFER: u64 = 18; + // The signer capability is not offered to any address + const ENO_SIGNER_CAPABILITY_OFFERED: u64 = 19; + // This account has exceeded the allocated GUIDs it can create. It should be impossible to reach this number for real applications. + const EEXCEEDED_MAX_GUID_CREATION_NUM: u64 = 20; + + /// Explicitly separate the GUID space between Object and Account to prevent accidental overlap. + const MAX_GUID_CREATION_NUM: u64 = 0x4000000000000; + + #[test_only] + /// Create signer for testing, independently of an Aptos-style `Account`. + public fun create_signer_for_test(addr: address): signer { create_signer(addr) } + + /// Only called during genesis to initialize system resources for this module. + public(friend) fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, OriginatingAddress { + address_map: table::new(), + }); + } + + public fun create_account_if_does_not_exist(account_address: address) { + if (!exists(account_address)) { + create_account(account_address); + } + } + + /// Publishes a new `Account` resource under `new_address`. A signer representing `new_address` + /// is returned. This way, the caller of this function can publish additional resources under + /// `new_address`. + public(friend) fun create_account(new_address: address): signer { + // there cannot be an Account resource under new_addr already. + assert!(!exists(new_address), error::already_exists(EACCOUNT_ALREADY_EXISTS)); + + // NOTE: @core_resources gets created via a `create_account` call, so we do not include it below. + assert!( + new_address != @vm_reserved && new_address != @aptos_framework && new_address != @aptos_token, + error::invalid_argument(ECANNOT_RESERVED_ADDRESS) + ); + + create_account_unchecked(new_address) + } + + fun create_account_unchecked(new_address: address): signer { + let new_account = create_signer(new_address); + let authentication_key = bcs::to_bytes(&new_address); + assert!( + vector::length(&authentication_key) == 32, + error::invalid_argument(EMALFORMED_AUTHENTICATION_KEY) + ); + + let guid_creation_num = 0; + + let guid_for_coin = guid::create(new_address, &mut guid_creation_num); + let coin_register_events = event::new_event_handle(guid_for_coin); + + let guid_for_rotation = guid::create(new_address, &mut guid_creation_num); + let key_rotation_events = event::new_event_handle(guid_for_rotation); + + move_to( + &new_account, + Account { + authentication_key, + sequence_number: 0, + guid_creation_num, + coin_register_events, + key_rotation_events, + rotation_capability_offer: CapabilityOffer { for: option::none() }, + signer_capability_offer: CapabilityOffer { for: option::none() }, + } + ); + + new_account + } + + #[view] + public fun exists_at(addr: address): bool { + exists(addr) + } + + #[view] + public fun get_guid_next_creation_num(addr: address): u64 acquires Account { + borrow_global(addr).guid_creation_num + } + + #[view] + public fun get_sequence_number(addr: address): u64 acquires Account { + borrow_global(addr).sequence_number + } + + public(friend) fun increment_sequence_number(addr: address) acquires Account { + let sequence_number = &mut borrow_global_mut(addr).sequence_number; + + assert!( + (*sequence_number as u128) < MAX_U64, + error::out_of_range(ESEQUENCE_NUMBER_TOO_BIG) + ); + + *sequence_number = *sequence_number + 1; + } + + #[view] + public fun get_authentication_key(addr: address): vector acquires Account { + borrow_global(addr).authentication_key + } + + /// This function is used to rotate a resource account's authentication key to `new_auth_key`. This is done in + /// many contexts: + /// 1. During normal key rotation via `rotate_authentication_key` or `rotate_authentication_key_call` + /// 2. During resource account initialization so that no private key can control the resource account + /// 3. During multisig_v2 account creation + public(friend) fun rotate_authentication_key_internal(account: &signer, new_auth_key: vector) acquires Account { + let addr = signer::address_of(account); + assert!(exists_at(addr), error::not_found(EACCOUNT_DOES_NOT_EXIST)); + assert!( + vector::length(&new_auth_key) == 32, + error::invalid_argument(EMALFORMED_AUTHENTICATION_KEY) + ); + let account_resource = borrow_global_mut(addr); + account_resource.authentication_key = new_auth_key; + } + + /// Private entry function for key rotation that allows the signer to update their authentication key. + /// Note that this does not update the `OriginatingAddress` table because the `new_auth_key` is not "verified": it + /// does not come with a proof-of-knowledge of the underlying SK. Nonetheless, we need this functionality due to + /// the introduction of non-standard key algorithms, such as passkeys, which cannot produce proofs-of-knowledge in + /// the format expected in `rotate_authentication_key`. + entry fun rotate_authentication_key_call(account: &signer, new_auth_key: vector) acquires Account { + rotate_authentication_key_internal(account, new_auth_key); + } + + /// Generic authentication key rotation function that allows the user to rotate their authentication key from any scheme to any scheme. + /// To authorize the rotation, we need two signatures: + /// - the first signature `cap_rotate_key` refers to the signature by the account owner's current key on a valid `RotationProofChallenge`, + /// demonstrating that the user intends to and has the capability to rotate the authentication key of this account; + /// - the second signature `cap_update_table` refers to the signature by the new key (that the account owner wants to rotate to) on a + /// valid `RotationProofChallenge`, demonstrating that the user owns the new private key, and has the authority to update the + /// `OriginatingAddress` map with the new address mapping ``. + /// To verify these two signatures, we need their corresponding public key and public key scheme: we use `from_scheme` and `from_public_key_bytes` + /// to verify `cap_rotate_key`, and `to_scheme` and `to_public_key_bytes` to verify `cap_update_table`. + /// A scheme of 0 refers to an Ed25519 key and a scheme of 1 refers to Multi-Ed25519 keys. + /// `originating address` refers to an account's original/first address. + /// + /// Here is an example attack if we don't ask for the second signature `cap_update_table`: + /// Alice has rotated her account `addr_a` to `new_addr_a`. As a result, the following entry is created, to help Alice when recovering her wallet: + /// `OriginatingAddress[new_addr_a]` -> `addr_a` + /// Alice has had bad day: her laptop blew up and she needs to reset her account on a new one. + /// (Fortunately, she still has her secret key `new_sk_a` associated with her new address `new_addr_a`, so she can do this.) + /// + /// But Bob likes to mess with Alice. + /// Bob creates an account `addr_b` and maliciously rotates it to Alice's new address `new_addr_a`. Since we are no longer checking a PoK, + /// Bob can easily do this. + /// + /// Now, the table will be updated to make Alice's new address point to Bob's address: `OriginatingAddress[new_addr_a]` -> `addr_b`. + /// When Alice recovers her account, her wallet will display the attacker's address (Bob's) `addr_b` as her address. + /// Now Alice will give `addr_b` to everyone to pay her, but the money will go to Bob. + /// + /// Because we ask for a valid `cap_update_table`, this kind of attack is not possible. Bob would not have the secret key of Alice's address + /// to rotate his address to Alice's address in the first place. + public entry fun rotate_authentication_key( + account: &signer, + from_scheme: u8, + from_public_key_bytes: vector, + to_scheme: u8, + to_public_key_bytes: vector, + cap_rotate_key: vector, + cap_update_table: vector, + ) acquires Account, OriginatingAddress { + let addr = signer::address_of(account); + assert!(exists_at(addr), error::not_found(EACCOUNT_DOES_NOT_EXIST)); + let account_resource = borrow_global_mut(addr); + + // Verify the given `from_public_key_bytes` matches this account's current authentication key. + if (from_scheme == ED25519_SCHEME) { + let from_pk = ed25519::new_unvalidated_public_key_from_bytes(from_public_key_bytes); + let from_auth_key = ed25519::unvalidated_public_key_to_authentication_key(&from_pk); + assert!( + account_resource.authentication_key == from_auth_key, + error::unauthenticated(EWRONG_CURRENT_PUBLIC_KEY) + ); + } else if (from_scheme == MULTI_ED25519_SCHEME) { + let from_pk = multi_ed25519::new_unvalidated_public_key_from_bytes(from_public_key_bytes); + let from_auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&from_pk); + assert!( + account_resource.authentication_key == from_auth_key, + error::unauthenticated(EWRONG_CURRENT_PUBLIC_KEY) + ); + } else { + abort error::invalid_argument(EINVALID_SCHEME) + }; + + // Construct a valid `RotationProofChallenge` that `cap_rotate_key` and `cap_update_table` will validate against. + let curr_auth_key_as_address = from_bcs::to_address(account_resource.authentication_key); + let challenge = RotationProofChallenge { + sequence_number: account_resource.sequence_number, + originator: addr, + current_auth_key: curr_auth_key_as_address, + new_public_key: to_public_key_bytes, + }; + + // Assert the challenges signed by the current and new keys are valid + assert_valid_rotation_proof_signature_and_get_auth_key( + from_scheme, + from_public_key_bytes, + cap_rotate_key, + &challenge + ); + let new_auth_key = assert_valid_rotation_proof_signature_and_get_auth_key( + to_scheme, + to_public_key_bytes, + cap_update_table, + &challenge + ); + + // Update the `OriginatingAddress` table. + update_auth_key_and_originating_address_table(addr, account_resource, new_auth_key); + } + + public entry fun rotate_authentication_key_with_rotation_capability( + delegate_signer: &signer, + rotation_cap_offerer_address: address, + new_scheme: u8, + new_public_key_bytes: vector, + cap_update_table: vector + ) acquires Account, OriginatingAddress { + assert!(exists_at(rotation_cap_offerer_address), error::not_found(EOFFERER_ADDRESS_DOES_NOT_EXIST)); + + // Check that there exists a rotation capability offer at the offerer's account resource for the delegate. + let delegate_address = signer::address_of(delegate_signer); + let offerer_account_resource = borrow_global(rotation_cap_offerer_address); + assert!( + option::contains(&offerer_account_resource.rotation_capability_offer.for, &delegate_address), + error::not_found(ENO_SUCH_ROTATION_CAPABILITY_OFFER) + ); + + let curr_auth_key = from_bcs::to_address(offerer_account_resource.authentication_key); + let challenge = RotationProofChallenge { + sequence_number: get_sequence_number(delegate_address), + originator: rotation_cap_offerer_address, + current_auth_key: curr_auth_key, + new_public_key: new_public_key_bytes, + }; + + // Verifies that the `RotationProofChallenge` from above is signed under the new public key that we are rotating to. l + let new_auth_key = assert_valid_rotation_proof_signature_and_get_auth_key( + new_scheme, + new_public_key_bytes, + cap_update_table, + &challenge + ); + + // Update the `OriginatingAddress` table, so we can find the originating address using the new address. + let offerer_account_resource = borrow_global_mut(rotation_cap_offerer_address); + update_auth_key_and_originating_address_table( + rotation_cap_offerer_address, + offerer_account_resource, + new_auth_key + ); + } + + /// Offers rotation capability on behalf of `account` to the account at address `recipient_address`. + /// An account can delegate its rotation capability to only one other address at one time. If the account + /// has an existing rotation capability offer, calling this function will update the rotation capability offer with + /// the new `recipient_address`. + /// Here, `rotation_capability_sig_bytes` signature indicates that this key rotation is authorized by the account owner, + /// and prevents the classic "time-of-check time-of-use" attack. + /// For example, users usually rely on what the wallet displays to them as the transaction's outcome. Consider a contract that with 50% probability + /// (based on the current timestamp in Move), rotates somebody's key. The wallet might be unlucky and get an outcome where nothing is rotated, + /// incorrectly telling the user nothing bad will happen. But when the transaction actually gets executed, the attacker gets lucky and + /// the execution path triggers the account key rotation. + /// We prevent such attacks by asking for this extra signature authorizing the key rotation. + /// + /// @param rotation_capability_sig_bytes is the signature by the account owner's key on `RotationCapabilityOfferProofChallengeV2`. + /// @param account_scheme is the scheme of the account (ed25519 or multi_ed25519). + /// @param account_public_key_bytes is the public key of the account owner. + /// @param recipient_address is the address of the recipient of the rotation capability - note that if there's an existing rotation capability + /// offer, calling this function will replace the previous `recipient_address` upon successful verification. + public entry fun offer_rotation_capability( + account: &signer, + rotation_capability_sig_bytes: vector, + account_scheme: u8, + account_public_key_bytes: vector, + recipient_address: address, + ) acquires Account { + let addr = signer::address_of(account); + assert!(exists_at(recipient_address), error::not_found(EACCOUNT_DOES_NOT_EXIST)); + + // proof that this account intends to delegate its rotation capability to another account + let account_resource = borrow_global_mut(addr); + let proof_challenge = RotationCapabilityOfferProofChallengeV2 { + chain_id: chain_id::get(), + sequence_number: account_resource.sequence_number, + source_address: addr, + recipient_address, + }; + + // verify the signature on `RotationCapabilityOfferProofChallengeV2` by the account owner + if (account_scheme == ED25519_SCHEME) { + let pubkey = ed25519::new_unvalidated_public_key_from_bytes(account_public_key_bytes); + let expected_auth_key = ed25519::unvalidated_public_key_to_authentication_key(&pubkey); + assert!( + account_resource.authentication_key == expected_auth_key, + error::invalid_argument(EWRONG_CURRENT_PUBLIC_KEY) + ); + + let rotation_capability_sig = ed25519::new_signature_from_bytes(rotation_capability_sig_bytes); + assert!( + ed25519::signature_verify_strict_t(&rotation_capability_sig, &pubkey, proof_challenge), + error::invalid_argument(EINVALID_PROOF_OF_KNOWLEDGE) + ); + } else if (account_scheme == MULTI_ED25519_SCHEME) { + let pubkey = multi_ed25519::new_unvalidated_public_key_from_bytes(account_public_key_bytes); + let expected_auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&pubkey); + assert!( + account_resource.authentication_key == expected_auth_key, + error::invalid_argument(EWRONG_CURRENT_PUBLIC_KEY) + ); + + let rotation_capability_sig = multi_ed25519::new_signature_from_bytes(rotation_capability_sig_bytes); + assert!( + multi_ed25519::signature_verify_strict_t(&rotation_capability_sig, &pubkey, proof_challenge), + error::invalid_argument(EINVALID_PROOF_OF_KNOWLEDGE) + ); + } else { + abort error::invalid_argument(EINVALID_SCHEME) + }; + + // update the existing rotation capability offer or put in a new rotation capability offer for the current account + option::swap_or_fill(&mut account_resource.rotation_capability_offer.for, recipient_address); + } + + #[view] + /// Returns true if the account at `account_addr` has a rotation capability offer. + public fun is_rotation_capability_offered(account_addr: address): bool acquires Account { + let account_resource = borrow_global(account_addr); + option::is_some(&account_resource.rotation_capability_offer.for) + } + + #[view] + /// Returns the address of the account that has a rotation capability offer from the account at `account_addr`. + public fun get_rotation_capability_offer_for(account_addr: address): address acquires Account { + let account_resource = borrow_global(account_addr); + assert!( + option::is_some(&account_resource.rotation_capability_offer.for), + error::not_found(ENO_SIGNER_CAPABILITY_OFFERED), + ); + *option::borrow(&account_resource.rotation_capability_offer.for) + } + + /// Revoke the rotation capability offer given to `to_be_revoked_recipient_address` from `account` + public entry fun revoke_rotation_capability(account: &signer, to_be_revoked_address: address) acquires Account { + assert!(exists_at(to_be_revoked_address), error::not_found(EACCOUNT_DOES_NOT_EXIST)); + let addr = signer::address_of(account); + let account_resource = borrow_global_mut(addr); + assert!( + option::contains(&account_resource.rotation_capability_offer.for, &to_be_revoked_address), + error::not_found(ENO_SUCH_ROTATION_CAPABILITY_OFFER) + ); + revoke_any_rotation_capability(account); + } + + /// Revoke any rotation capability offer in the specified account. + public entry fun revoke_any_rotation_capability(account: &signer) acquires Account { + let account_resource = borrow_global_mut(signer::address_of(account)); + option::extract(&mut account_resource.rotation_capability_offer.for); + } + + /// Offers signer capability on behalf of `account` to the account at address `recipient_address`. + /// An account can delegate its signer capability to only one other address at one time. + /// `signer_capability_key_bytes` is the `SignerCapabilityOfferProofChallengeV2` signed by the account owner's key + /// `account_scheme` is the scheme of the account (ed25519 or multi_ed25519). + /// `account_public_key_bytes` is the public key of the account owner. + /// `recipient_address` is the address of the recipient of the signer capability - note that if there's an existing + /// `recipient_address` in the account owner's `SignerCapabilityOffer`, this will replace the + /// previous `recipient_address` upon successful verification (the previous recipient will no longer have access + /// to the account owner's signer capability). + public entry fun offer_signer_capability( + account: &signer, + signer_capability_sig_bytes: vector, + account_scheme: u8, + account_public_key_bytes: vector, + recipient_address: address + ) acquires Account { + let source_address = signer::address_of(account); + assert!(exists_at(recipient_address), error::not_found(EACCOUNT_DOES_NOT_EXIST)); + + // Proof that this account intends to delegate its signer capability to another account. + let proof_challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: get_sequence_number(source_address), + source_address, + recipient_address, + }; + verify_signed_message( + source_address, account_scheme, account_public_key_bytes, signer_capability_sig_bytes, proof_challenge); + + // Update the existing signer capability offer or put in a new signer capability offer for the recipient. + let account_resource = borrow_global_mut(source_address); + option::swap_or_fill(&mut account_resource.signer_capability_offer.for, recipient_address); + } + + #[view] + /// Returns true if the account at `account_addr` has a signer capability offer. + public fun is_signer_capability_offered(account_addr: address): bool acquires Account { + let account_resource = borrow_global(account_addr); + option::is_some(&account_resource.signer_capability_offer.for) + } + + #[view] + /// Returns the address of the account that has a signer capability offer from the account at `account_addr`. + public fun get_signer_capability_offer_for(account_addr: address): address acquires Account { + let account_resource = borrow_global(account_addr); + assert!( + option::is_some(&account_resource.signer_capability_offer.for), + error::not_found(ENO_SIGNER_CAPABILITY_OFFERED), + ); + *option::borrow(&account_resource.signer_capability_offer.for) + } + + /// Revoke the account owner's signer capability offer for `to_be_revoked_address` (i.e., the address that + /// has a signer capability offer from `account` but will be revoked in this function). + public entry fun revoke_signer_capability(account: &signer, to_be_revoked_address: address) acquires Account { + assert!(exists_at(to_be_revoked_address), error::not_found(EACCOUNT_DOES_NOT_EXIST)); + let addr = signer::address_of(account); + let account_resource = borrow_global_mut(addr); + assert!( + option::contains(&account_resource.signer_capability_offer.for, &to_be_revoked_address), + error::not_found(ENO_SUCH_SIGNER_CAPABILITY) + ); + revoke_any_signer_capability(account); + } + + /// Revoke any signer capability offer in the specified account. + public entry fun revoke_any_signer_capability(account: &signer) acquires Account { + let account_resource = borrow_global_mut(signer::address_of(account)); + option::extract(&mut account_resource.signer_capability_offer.for); + } + + /// Return an authorized signer of the offerer, if there's an existing signer capability offer for `account` + /// at the offerer's address. + public fun create_authorized_signer(account: &signer, offerer_address: address): signer acquires Account { + assert!(exists_at(offerer_address), error::not_found(EOFFERER_ADDRESS_DOES_NOT_EXIST)); + + // Check if there's an existing signer capability offer from the offerer. + let account_resource = borrow_global(offerer_address); + let addr = signer::address_of(account); + assert!( + option::contains(&account_resource.signer_capability_offer.for, &addr), + error::not_found(ENO_SUCH_SIGNER_CAPABILITY) + ); + + create_signer(offerer_address) + } + + /////////////////////////////////////////////////////////////////////////// + /// Helper functions for authentication key rotation. + /////////////////////////////////////////////////////////////////////////// + fun assert_valid_rotation_proof_signature_and_get_auth_key( + scheme: u8, + public_key_bytes: vector, + signature: vector, + challenge: &RotationProofChallenge + ): vector { + if (scheme == ED25519_SCHEME) { + let pk = ed25519::new_unvalidated_public_key_from_bytes(public_key_bytes); + let sig = ed25519::new_signature_from_bytes(signature); + assert!( + ed25519::signature_verify_strict_t(&sig, &pk, *challenge), + std::error::invalid_argument(EINVALID_PROOF_OF_KNOWLEDGE) + ); + ed25519::unvalidated_public_key_to_authentication_key(&pk) + } else if (scheme == MULTI_ED25519_SCHEME) { + let pk = multi_ed25519::new_unvalidated_public_key_from_bytes(public_key_bytes); + let sig = multi_ed25519::new_signature_from_bytes(signature); + assert!( + multi_ed25519::signature_verify_strict_t(&sig, &pk, *challenge), + std::error::invalid_argument(EINVALID_PROOF_OF_KNOWLEDGE) + ); + multi_ed25519::unvalidated_public_key_to_authentication_key(&pk) + } else { + abort error::invalid_argument(EINVALID_SCHEME) + } + } + + /// Update the `OriginatingAddress` table, so that we can find the originating address using the latest address + /// in the event of key recovery. + fun update_auth_key_and_originating_address_table( + originating_addr: address, + account_resource: &mut Account, + new_auth_key_vector: vector, + ) acquires OriginatingAddress { + let address_map = &mut borrow_global_mut(@aptos_framework).address_map; + let curr_auth_key = from_bcs::to_address(account_resource.authentication_key); + + // Checks `OriginatingAddress[curr_auth_key]` is either unmapped, or mapped to `originating_address`. + // If it's mapped to the originating address, removes that mapping. + // Otherwise, abort if it's mapped to a different address. + if (table::contains(address_map, curr_auth_key)) { + // If account_a with address_a is rotating its keypair from keypair_a to keypair_b, we expect + // the address of the account to stay the same, while its keypair updates to keypair_b. + // Here, by asserting that we're calling from the account with the originating address, we enforce + // the standard of keeping the same address and updating the keypair at the contract level. + // Without this assertion, the dapps could also update the account's address to address_b (the address that + // is programmatically related to keypaier_b) and update the keypair to keypair_b. This causes problems + // for interoperability because different dapps can implement this in different ways. + // If the account with address b calls this function with two valid signatures, it will abort at this step, + // because address b is not the account's originating address. + assert!( + originating_addr == table::remove(address_map, curr_auth_key), + error::not_found(EINVALID_ORIGINATING_ADDRESS) + ); + }; + + // Set `OriginatingAddress[new_auth_key] = originating_address`. + let new_auth_key = from_bcs::to_address(new_auth_key_vector); + table::add(address_map, new_auth_key, originating_addr); + + if (std::features::module_event_migration_enabled()) { + event::emit(KeyRotation { + account: originating_addr, + old_authentication_key: account_resource.authentication_key, + new_authentication_key: new_auth_key_vector, + }); + }; + event::emit_event( + &mut account_resource.key_rotation_events, + KeyRotationEvent { + old_authentication_key: account_resource.authentication_key, + new_authentication_key: new_auth_key_vector, + } + ); + + // Update the account resource's authentication key. + account_resource.authentication_key = new_auth_key_vector; + } + + /////////////////////////////////////////////////////////////////////////// + /// Basic account creation methods. + /////////////////////////////////////////////////////////////////////////// + + /// This is a helper function to compute resource addresses. Computation of the address + /// involves the use of a cryptographic hash operation and should be use thoughtfully. + public fun create_resource_address(source: &address, seed: vector): address { + let bytes = bcs::to_bytes(source); + vector::append(&mut bytes, seed); + vector::push_back(&mut bytes, DERIVE_RESOURCE_ACCOUNT_SCHEME); + from_bcs::to_address(hash::sha3_256(bytes)) + } + + /// A resource account is used to manage resources independent of an account managed by a user. + /// In Aptos a resource account is created based upon the sha3 256 of the source's address and additional seed data. + /// A resource account can only be created once, this is designated by setting the + /// `Account::signer_capability_offer::for` to the address of the resource account. While an entity may call + /// `create_account` to attempt to claim an account ahead of the creation of a resource account, if found Aptos will + /// transition ownership of the account over to the resource account. This is done by validating that the account has + /// yet to execute any transactions and that the `Account::signer_capability_offer::for` is none. The probability of a + /// collision where someone has legitimately produced a private key that maps to a resource account address is less + /// than `(1/2)^(256)`. + public fun create_resource_account(source: &signer, seed: vector): (signer, SignerCapability) acquires Account { + let resource_addr = create_resource_address(&signer::address_of(source), seed); + let resource = if (exists_at(resource_addr)) { + let account = borrow_global(resource_addr); + assert!( + option::is_none(&account.signer_capability_offer.for), + error::already_exists(ERESOURCE_ACCCOUNT_EXISTS), + ); + assert!( + account.sequence_number == 0, + error::invalid_state(EACCOUNT_ALREADY_USED), + ); + create_signer(resource_addr) + } else { + create_account_unchecked(resource_addr) + }; + + // By default, only the SignerCapability should have control over the resource account and not the auth key. + // If the source account wants direct control via auth key, they would need to explicitly rotate the auth key + // of the resource account using the SignerCapability. + rotate_authentication_key_internal(&resource, ZERO_AUTH_KEY); + + let account = borrow_global_mut(resource_addr); + account.signer_capability_offer.for = option::some(resource_addr); + let signer_cap = SignerCapability { account: resource_addr }; + (resource, signer_cap) + } + + /// create the account for system reserved addresses + public(friend) fun create_framework_reserved_account(addr: address): (signer, SignerCapability) { + assert!( + addr == @0x1 || + addr == @0x2 || + addr == @0x3 || + addr == @0x4 || + addr == @0x5 || + addr == @0x6 || + addr == @0x7 || + addr == @0x8 || + addr == @0x9 || + addr == @0xa, + error::permission_denied(ENO_VALID_FRAMEWORK_RESERVED_ADDRESS), + ); + let signer = create_account_unchecked(addr); + let signer_cap = SignerCapability { account: addr }; + (signer, signer_cap) + } + + /////////////////////////////////////////////////////////////////////////// + /// GUID management methods. + /////////////////////////////////////////////////////////////////////////// + + public fun create_guid(account_signer: &signer): guid::GUID acquires Account { + let addr = signer::address_of(account_signer); + let account = borrow_global_mut(addr); + let guid = guid::create(addr, &mut account.guid_creation_num); + assert!( + account.guid_creation_num < MAX_GUID_CREATION_NUM, + error::out_of_range(EEXCEEDED_MAX_GUID_CREATION_NUM), + ); + guid + } + + /////////////////////////////////////////////////////////////////////////// + /// GUID management methods. + /////////////////////////////////////////////////////////////////////////// + + public fun new_event_handle(account: &signer): EventHandle acquires Account { + event::new_event_handle(create_guid(account)) + } + + /////////////////////////////////////////////////////////////////////////// + /// Coin management methods. + /////////////////////////////////////////////////////////////////////////// + + public(friend) fun register_coin(account_addr: address) acquires Account { + let account = borrow_global_mut(account_addr); + event::emit_event( + &mut account.coin_register_events, + CoinRegisterEvent { + type_info: type_info::type_of(), + }, + ); + } + + /////////////////////////////////////////////////////////////////////////// + // Test-only create signerCapabilityOfferProofChallengeV2 and return it + /////////////////////////////////////////////////////////////////////////// + + #[test_only] + public fun get_signer_capability_offer_proof_challenge_v2( + source_address: address, + recipient_address: address, + ): SignerCapabilityOfferProofChallengeV2 acquires Account { + SignerCapabilityOfferProofChallengeV2 { + sequence_number: borrow_global_mut(source_address).sequence_number, + source_address, + recipient_address, + } + } + + /////////////////////////////////////////////////////////////////////////// + /// Capability based functions for efficient use. + /////////////////////////////////////////////////////////////////////////// + + public fun create_signer_with_capability(capability: &SignerCapability): signer { + let addr = &capability.account; + create_signer(*addr) + } + + public fun get_signer_capability_address(capability: &SignerCapability): address { + capability.account + } + + public fun verify_signed_message( + account: address, + account_scheme: u8, + account_public_key: vector, + signed_message_bytes: vector, + message: T, + ) acquires Account { + let account_resource = borrow_global_mut(account); + // Verify that the `SignerCapabilityOfferProofChallengeV2` has the right information and is signed by the account owner's key + if (account_scheme == ED25519_SCHEME) { + let pubkey = ed25519::new_unvalidated_public_key_from_bytes(account_public_key); + let expected_auth_key = ed25519::unvalidated_public_key_to_authentication_key(&pubkey); + assert!( + account_resource.authentication_key == expected_auth_key, + error::invalid_argument(EWRONG_CURRENT_PUBLIC_KEY), + ); + + let signer_capability_sig = ed25519::new_signature_from_bytes(signed_message_bytes); + assert!( + ed25519::signature_verify_strict_t(&signer_capability_sig, &pubkey, message), + error::invalid_argument(EINVALID_PROOF_OF_KNOWLEDGE), + ); + } else if (account_scheme == MULTI_ED25519_SCHEME) { + let pubkey = multi_ed25519::new_unvalidated_public_key_from_bytes(account_public_key); + let expected_auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&pubkey); + assert!( + account_resource.authentication_key == expected_auth_key, + error::invalid_argument(EWRONG_CURRENT_PUBLIC_KEY), + ); + + let signer_capability_sig = multi_ed25519::new_signature_from_bytes(signed_message_bytes); + assert!( + multi_ed25519::signature_verify_strict_t(&signer_capability_sig, &pubkey, message), + error::invalid_argument(EINVALID_PROOF_OF_KNOWLEDGE), + ); + } else { + abort error::invalid_argument(EINVALID_SCHEME) + }; + } + + #[test_only] + public fun create_account_for_test(new_address: address): signer { + // Make this easier by just allowing the account to be created again in a test + if (!exists_at(new_address)) { + create_account_unchecked(new_address) + } else { + create_signer_for_test(new_address) + } + } + + #[test] + /// Assert correct signer creation. + fun test_create_signer_for_test() { + assert!(signer::address_of(&create_signer_for_test(@aptos_framework)) == @0x1, 0); + assert!(signer::address_of(&create_signer_for_test(@0x123)) == @0x123, 0); + } + + #[test(user = @0x1)] + public entry fun test_create_resource_account(user: signer) acquires Account { + let (resource_account, resource_account_cap) = create_resource_account(&user, x"01"); + let resource_addr = signer::address_of(&resource_account); + assert!(resource_addr != signer::address_of(&user), 0); + assert!(resource_addr == get_signer_capability_address(&resource_account_cap), 1); + } + + #[test] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_cannot_control_resource_account_via_auth_key() acquires Account { + let alice_pk = x"4141414141414141414141414141414141414141414141414141414141414145"; + let alice = create_account_from_ed25519_public_key(alice_pk); + let alice_auth = get_authentication_key(signer::address_of(&alice)); // must look like a valid public key + + let (eve_sk, eve_pk) = ed25519::generate_keys(); + let eve_pk_bytes = ed25519::validated_public_key_to_bytes(&eve_pk); + let eve = create_account_from_ed25519_public_key(eve_pk_bytes); + let recipient_address = signer::address_of(&eve); + + let seed = eve_pk_bytes; // multisig public key + vector::push_back(&mut seed, 1); // multisig threshold + vector::push_back(&mut seed, 1); // signature scheme id + let (resource, _) = create_resource_account(&alice, seed); + + let resource_addr = signer::address_of(&resource); + let proof_challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: borrow_global_mut(resource_addr).sequence_number, + source_address: resource_addr, + recipient_address, + }; + + let eve_sig = ed25519::sign_struct(&eve_sk, copy proof_challenge); + + // Construct a malicious 1-out-of-2 multisig PK over Alice's authentication key and Eve's Ed25519 PK. + let account_public_key_bytes = alice_auth; + vector::append(&mut account_public_key_bytes, eve_pk_bytes); + vector::push_back(&mut account_public_key_bytes, 1); // Multisig verification threshold. + let fake_pk = multi_ed25519::new_unvalidated_public_key_from_bytes(account_public_key_bytes); + + // Construct a multisig for `proof_challenge` as if it is signed by the signers behind `fake_pk`, + // Eve being the only participant. + let signer_capability_sig_bytes = x""; + vector::append(&mut signer_capability_sig_bytes, ed25519::signature_to_bytes(&eve_sig)); + vector::append(&mut signer_capability_sig_bytes, x"40000000"); // Signers bitmap. + let fake_sig = multi_ed25519::new_signature_from_bytes(signer_capability_sig_bytes); + + assert!( + multi_ed25519::signature_verify_strict_t(&fake_sig, &fake_pk, proof_challenge), + error::invalid_state(EINVALID_PROOF_OF_KNOWLEDGE) + ); + offer_signer_capability( + &resource, + signer_capability_sig_bytes, + MULTI_ED25519_SCHEME, + account_public_key_bytes, + recipient_address + ); + } + + #[test_only] + struct DummyResource has key {} + + #[test(user = @0x1)] + public entry fun test_module_capability(user: signer) acquires Account, DummyResource { + let (resource_account, signer_cap) = create_resource_account(&user, x"01"); + assert!(signer::address_of(&resource_account) != signer::address_of(&user), 0); + + let resource_account_from_cap = create_signer_with_capability(&signer_cap); + assert!(&resource_account == &resource_account_from_cap, 1); + + move_to(&resource_account_from_cap, DummyResource {}); + borrow_global(signer::address_of(&resource_account)); + } + + #[test(user = @0x1)] + public entry fun test_resource_account_and_create_account(user: signer) acquires Account { + let resource_addr = create_resource_address(&@0x1, x"01"); + create_account_unchecked(resource_addr); + + create_resource_account(&user, x"01"); + } + + #[test(user = @0x1)] + #[expected_failure(abort_code = 0x8000f, location = Self)] + public entry fun test_duplice_create_resource_account(user: signer) acquires Account { + create_resource_account(&user, x"01"); + create_resource_account(&user, x"01"); + } + + /////////////////////////////////////////////////////////////////////////// + // Test-only sequence number mocking for extant Account resource + /////////////////////////////////////////////////////////////////////////// + + #[test_only] + /// Increment sequence number of account at address `addr` + public fun increment_sequence_number_for_test( + addr: address, + ) acquires Account { + let acct = borrow_global_mut(addr); + acct.sequence_number = acct.sequence_number + 1; + } + + #[test_only] + /// Update address `addr` to have `s` as its sequence number + public fun set_sequence_number( + addr: address, + s: u64 + ) acquires Account { + borrow_global_mut(addr).sequence_number = s; + } + + #[test_only] + public fun create_test_signer_cap(account: address): SignerCapability { + SignerCapability { account } + } + + #[test_only] + public fun set_signer_capability_offer(offerer: address, receiver: address) acquires Account { + let account_resource = borrow_global_mut(offerer); + option::swap_or_fill(&mut account_resource.signer_capability_offer.for, receiver); + } + + #[test_only] + public fun set_rotation_capability_offer(offerer: address, receiver: address) acquires Account { + let account_resource = borrow_global_mut(offerer); + option::swap_or_fill(&mut account_resource.rotation_capability_offer.for, receiver); + } + + #[test] + /// Verify test-only sequence number mocking + public entry fun mock_sequence_numbers() + acquires Account { + let addr: address = @0x1234; // Define test address + create_account(addr); // Initialize account resource + // Assert sequence number intializes to 0 + assert!(borrow_global(addr).sequence_number == 0, 0); + increment_sequence_number_for_test(addr); // Increment sequence number + // Assert correct mock value post-increment + assert!(borrow_global(addr).sequence_number == 1, 1); + set_sequence_number(addr, 10); // Set mock sequence number + // Assert correct mock value post-modification + assert!(borrow_global(addr).sequence_number == 10, 2); + } + + /////////////////////////////////////////////////////////////////////////// + // Test account helpers + /////////////////////////////////////////////////////////////////////////// + + #[test(alice = @0xa11ce)] + #[expected_failure(abort_code = 65537, location = aptos_framework::ed25519)] + public entry fun test_empty_public_key(alice: signer) acquires Account, OriginatingAddress { + create_account(signer::address_of(&alice)); + let pk = vector::empty(); + let sig = x"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + rotate_authentication_key(&alice, ED25519_SCHEME, pk, ED25519_SCHEME, pk, sig, sig); + } + + #[test(alice = @0xa11ce)] + #[expected_failure(abort_code = 262151, location = Self)] + public entry fun test_empty_signature(alice: signer) acquires Account, OriginatingAddress { + create_account(signer::address_of(&alice)); + let test_signature = vector::empty(); + let pk = x"0000000000000000000000000000000000000000000000000000000000000000"; + rotate_authentication_key(&alice, ED25519_SCHEME, pk, ED25519_SCHEME, pk, test_signature, test_signature); + } + + #[test_only] + public fun create_account_from_ed25519_public_key(pk_bytes: vector): signer { + let pk = ed25519::new_unvalidated_public_key_from_bytes(pk_bytes); + let curr_auth_key = ed25519::unvalidated_public_key_to_authentication_key(&pk); + let alice_address = from_bcs::to_address(curr_auth_key); + let alice = create_account_unchecked(alice_address); + alice + } + + // + // Tests for offering & revoking signer capabilities + // + + #[test(bob = @0x345)] + #[expected_failure(abort_code = 65544, location = Self)] + public entry fun test_invalid_offer_signer_capability(bob: signer) acquires Account { + let (_alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: borrow_global(alice_addr).sequence_number, + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let sig = ed25519::sign_struct(&_alice_sk, challenge); + + // Maul the signature and make sure the call would fail + let invalid_signature = ed25519::signature_to_bytes(&sig); + let first_sig_byte = vector::borrow_mut(&mut invalid_signature, 0); + *first_sig_byte = *first_sig_byte ^ 1; + + offer_signer_capability(&alice, invalid_signature, 0, alice_pk_bytes, bob_addr); + } + + #[test(bob = @0x345)] + public entry fun test_valid_check_signer_capability_and_create_authorized_signer(bob: signer) acquires Account { + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: borrow_global(alice_addr).sequence_number, + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_signer_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_signer_capability( + &alice, + ed25519::signature_to_bytes(&alice_signer_capability_offer_sig), + 0, + alice_pk_bytes, + bob_addr + ); + + assert!(option::contains(&borrow_global(alice_addr).signer_capability_offer.for, &bob_addr), 0); + + let signer = create_authorized_signer(&bob, alice_addr); + assert!(signer::address_of(&signer) == signer::address_of(&alice), 0); + } + + #[test(bob = @0x345)] + public entry fun test_get_signer_cap_and_is_signer_cap(bob: signer) acquires Account { + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: borrow_global(alice_addr).sequence_number, + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_signer_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_signer_capability( + &alice, + ed25519::signature_to_bytes(&alice_signer_capability_offer_sig), + 0, + alice_pk_bytes, + bob_addr + ); + + assert!(is_signer_capability_offered(alice_addr), 0); + assert!(get_signer_capability_offer_for(alice_addr) == bob_addr, 0); + } + + + #[test(bob = @0x345, charlie = @0x567)] + #[expected_failure(abort_code = 393230, location = Self)] + public entry fun test_invalid_check_signer_capability_and_create_authorized_signer( + bob: signer, + charlie: signer + ) acquires Account { + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: borrow_global(alice_addr).sequence_number, + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_signer_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_signer_capability( + &alice, + ed25519::signature_to_bytes(&alice_signer_capability_offer_sig), + 0, + alice_pk_bytes, + bob_addr + ); + + let alice_account_resource = borrow_global_mut(alice_addr); + assert!(option::contains(&alice_account_resource.signer_capability_offer.for, &bob_addr), 0); + + create_authorized_signer(&charlie, alice_addr); + } + + #[test(bob = @0x345)] + public entry fun test_valid_revoke_signer_capability(bob: signer) acquires Account { + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: borrow_global(alice_addr).sequence_number, + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_signer_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_signer_capability( + &alice, + ed25519::signature_to_bytes(&alice_signer_capability_offer_sig), + 0, + alice_pk_bytes, + bob_addr + ); + revoke_signer_capability(&alice, bob_addr); + } + + #[test(bob = @0x345, charlie = @0x567)] + #[expected_failure(abort_code = 393230, location = Self)] + public entry fun test_invalid_revoke_signer_capability(bob: signer, charlie: signer) acquires Account { + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + let alice_account_resource = borrow_global(alice_addr); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let charlie_addr = signer::address_of(&charlie); + create_account(charlie_addr); + + let challenge = SignerCapabilityOfferProofChallengeV2 { + sequence_number: alice_account_resource.sequence_number, + source_address: alice_addr, + recipient_address: bob_addr, + }; + let alice_signer_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + offer_signer_capability( + &alice, + ed25519::signature_to_bytes(&alice_signer_capability_offer_sig), + 0, + alice_pk_bytes, + bob_addr + ); + revoke_signer_capability(&alice, charlie_addr); + } + + // + // Tests for offering rotation capabilities + // + #[test(bob = @0x345, framework = @aptos_framework)] + public entry fun test_valid_offer_rotation_capability(bob: signer, framework: signer) acquires Account { + chain_id::initialize_for_test(&framework, 4); + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = RotationCapabilityOfferProofChallengeV2 { + chain_id: chain_id::get(), + sequence_number: get_sequence_number(alice_addr), + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_rotation_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_rotation_capability( + &alice, + ed25519::signature_to_bytes(&alice_rotation_capability_offer_sig), + 0, + alice_pk_bytes, + bob_addr + ); + + let alice_resource = borrow_global_mut(signer::address_of(&alice)); + assert!(option::contains(&alice_resource.rotation_capability_offer.for, &bob_addr), 0); + } + + #[test(bob = @0x345, framework = @aptos_framework)] + #[expected_failure(abort_code = 65544, location = Self)] + public entry fun test_invalid_offer_rotation_capability(bob: signer, framework: signer) acquires Account { + chain_id::initialize_for_test(&framework, 4); + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = RotationCapabilityOfferProofChallengeV2 { + chain_id: chain_id::get(), + // Intentionally make the signature invalid. + sequence_number: 2, + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_rotation_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_rotation_capability( + &alice, + ed25519::signature_to_bytes(&alice_rotation_capability_offer_sig), + 0, + alice_pk_bytes, + signer::address_of(&bob) + ); + } + + #[test(bob = @0x345, framework = @aptos_framework)] + public entry fun test_valid_revoke_rotation_capability(bob: signer, framework: signer) acquires Account { + chain_id::initialize_for_test(&framework, 4); + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + + let challenge = RotationCapabilityOfferProofChallengeV2 { + chain_id: chain_id::get(), + sequence_number: get_sequence_number(alice_addr), + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_rotation_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_rotation_capability( + &alice, + ed25519::signature_to_bytes(&alice_rotation_capability_offer_sig), + 0, + alice_pk_bytes, + signer::address_of(&bob) + ); + revoke_rotation_capability(&alice, signer::address_of(&bob)); + } + + #[test(bob = @0x345, charlie = @0x567, framework = @aptos_framework)] + #[expected_failure(abort_code = 393234, location = Self)] + public entry fun test_invalid_revoke_rotation_capability( + bob: signer, + charlie: signer, + framework: signer + ) acquires Account { + chain_id::initialize_for_test(&framework, 4); + let (alice_sk, alice_pk) = ed25519::generate_keys(); + let alice_pk_bytes = ed25519::validated_public_key_to_bytes(&alice_pk); + let alice = create_account_from_ed25519_public_key(alice_pk_bytes); + let alice_addr = signer::address_of(&alice); + + let bob_addr = signer::address_of(&bob); + create_account(bob_addr); + create_account(signer::address_of(&charlie)); + + let challenge = RotationCapabilityOfferProofChallengeV2 { + chain_id: chain_id::get(), + sequence_number: get_sequence_number(alice_addr), + source_address: alice_addr, + recipient_address: bob_addr, + }; + + let alice_rotation_capability_offer_sig = ed25519::sign_struct(&alice_sk, challenge); + + offer_rotation_capability( + &alice, + ed25519::signature_to_bytes(&alice_rotation_capability_offer_sig), + 0, + alice_pk_bytes, + signer::address_of(&bob) + ); + revoke_rotation_capability(&alice, signer::address_of(&charlie)); + } + + // + // Tests for key rotation + // + + #[test(account = @aptos_framework)] + public entry fun test_valid_rotate_authentication_key_multi_ed25519_to_multi_ed25519( + account: signer + ) acquires Account, OriginatingAddress { + initialize(&account); + let (curr_sk, curr_pk) = multi_ed25519::generate_keys(2, 3); + let curr_pk_unvalidated = multi_ed25519::public_key_to_unvalidated(&curr_pk); + let curr_auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&curr_pk_unvalidated); + let alice_addr = from_bcs::to_address(curr_auth_key); + let alice = create_account_unchecked(alice_addr); + + let (new_sk, new_pk) = multi_ed25519::generate_keys(4, 5); + let new_pk_unvalidated = multi_ed25519::public_key_to_unvalidated(&new_pk); + let new_auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&new_pk_unvalidated); + let new_address = from_bcs::to_address(new_auth_key); + + let challenge = RotationProofChallenge { + sequence_number: borrow_global(alice_addr).sequence_number, + originator: alice_addr, + current_auth_key: alice_addr, + new_public_key: multi_ed25519::unvalidated_public_key_to_bytes(&new_pk_unvalidated), + }; + + let from_sig = multi_ed25519::sign_struct(&curr_sk, challenge); + let to_sig = multi_ed25519::sign_struct(&new_sk, challenge); + + rotate_authentication_key( + &alice, + MULTI_ED25519_SCHEME, + multi_ed25519::unvalidated_public_key_to_bytes(&curr_pk_unvalidated), + MULTI_ED25519_SCHEME, + multi_ed25519::unvalidated_public_key_to_bytes(&new_pk_unvalidated), + multi_ed25519::signature_to_bytes(&from_sig), + multi_ed25519::signature_to_bytes(&to_sig), + ); + let address_map = &mut borrow_global_mut(@aptos_framework).address_map; + let expected_originating_address = table::borrow(address_map, new_address); + assert!(*expected_originating_address == alice_addr, 0); + assert!(borrow_global(alice_addr).authentication_key == new_auth_key, 0); + } + + #[test(account = @aptos_framework)] + public entry fun test_valid_rotate_authentication_key_multi_ed25519_to_ed25519( + account: signer + ) acquires Account, OriginatingAddress { + initialize(&account); + + let (curr_sk, curr_pk) = multi_ed25519::generate_keys(2, 3); + let curr_pk_unvalidated = multi_ed25519::public_key_to_unvalidated(&curr_pk); + let curr_auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&curr_pk_unvalidated); + let alice_addr = from_bcs::to_address(curr_auth_key); + let alice = create_account_unchecked(alice_addr); + + let account_resource = borrow_global_mut(alice_addr); + + let (new_sk, new_pk) = ed25519::generate_keys(); + let new_pk_unvalidated = ed25519::public_key_to_unvalidated(&new_pk); + let new_auth_key = ed25519::unvalidated_public_key_to_authentication_key(&new_pk_unvalidated); + let new_addr = from_bcs::to_address(new_auth_key); + + let challenge = RotationProofChallenge { + sequence_number: account_resource.sequence_number, + originator: alice_addr, + current_auth_key: alice_addr, + new_public_key: ed25519::unvalidated_public_key_to_bytes(&new_pk_unvalidated), + }; + + let from_sig = multi_ed25519::sign_struct(&curr_sk, challenge); + let to_sig = ed25519::sign_struct(&new_sk, challenge); + + rotate_authentication_key( + &alice, + MULTI_ED25519_SCHEME, + multi_ed25519::unvalidated_public_key_to_bytes(&curr_pk_unvalidated), + ED25519_SCHEME, + ed25519::unvalidated_public_key_to_bytes(&new_pk_unvalidated), + multi_ed25519::signature_to_bytes(&from_sig), + ed25519::signature_to_bytes(&to_sig), + ); + + let address_map = &mut borrow_global_mut(@aptos_framework).address_map; + let expected_originating_address = table::borrow(address_map, new_addr); + assert!(*expected_originating_address == alice_addr, 0); + assert!(borrow_global(alice_addr).authentication_key == new_auth_key, 0); + } + + + #[test(account = @aptos_framework)] + public entry fun test_simple_rotation(account: &signer) acquires Account { + initialize(account); + + let alice_addr = @0x1234; + let alice = create_account_unchecked(alice_addr); + + let (_new_sk, new_pk) = ed25519::generate_keys(); + let new_pk_unvalidated = ed25519::public_key_to_unvalidated(&new_pk); + let new_auth_key = ed25519::unvalidated_public_key_to_authentication_key(&new_pk_unvalidated); + let _new_addr = from_bcs::to_address(new_auth_key); + + rotate_authentication_key_call(&alice, new_auth_key); + assert!(borrow_global(alice_addr).authentication_key == new_auth_key, 0); + } + + + #[test(account = @aptos_framework)] + #[expected_failure(abort_code = 0x20014, location = Self)] + public entry fun test_max_guid(account: &signer) acquires Account { + let addr = signer::address_of(account); + create_account_unchecked(addr); + let account_state = borrow_global_mut(addr); + account_state.guid_creation_num = MAX_GUID_CREATION_NUM - 1; + create_guid(account); + } + + #[test_only] + struct FakeCoin {} + + #[test_only] + struct SadFakeCoin {} + + #[test(account = @0x1234)] + fun test_events(account: &signer) acquires Account { + let addr = signer::address_of(account); + create_account_unchecked(addr); + register_coin(addr); + + let eventhandle = &borrow_global(addr).coin_register_events; + let event = CoinRegisterEvent { type_info: type_info::type_of() }; + + let events = event::emitted_events_by_handle(eventhandle); + assert!(vector::length(&events) == 1, 0); + assert!(vector::borrow(&events, 0) == &event, 1); + assert!(event::was_event_emitted_by_handle(eventhandle, &event), 2); + + let event = CoinRegisterEvent { type_info: type_info::type_of() }; + assert!(!event::was_event_emitted_by_handle(eventhandle, &event), 3); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aggregator.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aggregator.move new file mode 100644 index 000000000..9a0baaff1 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aggregator.move @@ -0,0 +1,48 @@ +/// This module provides an interface for aggregators. Aggregators are similar to +/// unsigned integers and support addition and subtraction (aborting on underflow +/// or on overflowing a custom upper limit). The difference from integers is that +/// aggregators allow to perform both additions and subtractions in parallel across +/// multiple transactions, enabling parallel execution. For example, if the first +/// transaction is doing `add(X, 1)` for aggregator resource `X`, and the second +/// is doing `sub(X,3)`, they can be executed in parallel avoiding a read-modify-write +/// dependency. +/// However, reading the aggregator value (i.e. calling `read(X)`) is an expensive +/// operation and should be avoided as much as possible because it reduces the +/// parallelism. Moreover, **aggregators can only be created by Aptos Framework (0x1) +/// at the moment.** +module aptos_framework::aggregator { + + /// The value of aggregator overflows. Raised by native code. + const EAGGREGATOR_OVERFLOW: u64 = 1; + + /// The value of aggregator underflows (goes below zero). Raised by native code. + const EAGGREGATOR_UNDERFLOW: u64 = 2; + + /// Aggregator feature is not supported. Raised by native code. + const ENOT_SUPPORTED: u64 = 3; + + /// Represents an integer which supports parallel additions and subtractions + /// across multiple transactions. See the module description for more details. + struct Aggregator has store { + handle: address, + key: address, + limit: u128, + } + + /// Returns `limit` exceeding which aggregator overflows. + public fun limit(aggregator: &Aggregator): u128 { + aggregator.limit + } + + /// Adds `value` to aggregator. Aborts on overflowing the limit. + public native fun add(aggregator: &mut Aggregator, value: u128); + + /// Subtracts `value` from aggregator. Aborts on going below zero. + public native fun sub(aggregator: &mut Aggregator, value: u128); + + /// Returns a value stored in this aggregator. + public native fun read(aggregator: &Aggregator): u128; + + /// Destroys an aggregator and removes it from its `AggregatorFactory`. + public native fun destroy(aggregator: Aggregator); +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aggregator_factory.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aggregator_factory.move new file mode 100644 index 000000000..7ec4dad80 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aggregator_factory.move @@ -0,0 +1,66 @@ +/// This module provides foundations to create aggregators. Currently only +/// Aptos Framework (0x1) can create them, so this module helps to wrap +/// the constructor of `Aggregator` struct so that only a system account +/// can initialize one. In the future, this might change and aggregators +/// can be enabled for the public. +module aptos_framework::aggregator_factory { + use std::error; + + use aptos_framework::system_addresses; + use aptos_framework::aggregator::Aggregator; + use aptos_std::table::{Self, Table}; + + friend aptos_framework::genesis; + friend aptos_framework::optional_aggregator; + + /// Aggregator factory is not published yet. + const EAGGREGATOR_FACTORY_NOT_FOUND: u64 = 1; + + /// Creates new aggregators. Used to control the numbers of aggregators in the + /// system and who can create them. At the moment, only Aptos Framework (0x1) + /// account can. + struct AggregatorFactory has key { + phantom_table: Table, + } + + /// Creates a new factory for aggregators. Can only be called during genesis. + public(friend) fun initialize_aggregator_factory(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + let aggregator_factory = AggregatorFactory { + phantom_table: table::new() + }; + move_to(aptos_framework, aggregator_factory); + } + + /// Creates a new aggregator instance which overflows on exceeding a `limit`. + public(friend) fun create_aggregator_internal(limit: u128): Aggregator acquires AggregatorFactory { + assert!( + exists(@aptos_framework), + error::not_found(EAGGREGATOR_FACTORY_NOT_FOUND) + ); + + let aggregator_factory = borrow_global_mut(@aptos_framework); + new_aggregator(aggregator_factory, limit) + } + + /// This is currently a function closed for public. This can be updated in the future by on-chain governance + /// to allow any signer to call. + public fun create_aggregator(account: &signer, limit: u128): Aggregator acquires AggregatorFactory { + // Only Aptos Framework (0x1) account can call this for now. + system_addresses::assert_aptos_framework(account); + create_aggregator_internal(limit) + } + + /// Returns a new aggregator. + native fun new_aggregator(aggregator_factory: &mut AggregatorFactory, limit: u128): Aggregator; + + #[test_only] + public fun initialize_aggregator_factory_for_test(aptos_framework: &signer) { + initialize_aggregator_factory(aptos_framework); + } + + #[test_only] + public fun aggregator_factory_exists_for_testing(): bool { + exists(@aptos_framework) + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aggregator_v2.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aggregator_v2.move new file mode 100644 index 000000000..7e26548bc --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aggregator_v2.move @@ -0,0 +1,280 @@ +/// This module provides an interface for aggregators (version 2). Aggregators are +/// similar to unsigned integers and support addition and subtraction (aborting on +/// underflow or on overflowing a custom upper limit). The difference from integers +/// is that aggregators allow to perform both additions and subtractions in parallel +/// across multiple transactions, enabling parallel execution. For example, if the +/// first transaction is doing `try_add(X, 1)` for aggregator `X`, and the second is +/// doing `try_sub(X,3)`, they can be executed in parallel avoiding a read-modify-write +/// dependency. +/// However, reading the aggregator value (i.e. calling `read(X)`) is a resource-intensive +/// operation that also reduced parallelism, and should be avoided as much as possible. +/// If you need to capture the value, without revealing it, use snapshot function instead, +/// which has no parallelism impact. +/// +/// From parallelism considerations, there are three different levels of effects: +/// * enable full parallelism (cannot create conflicts): +/// max_value, create_*, snapshot, derive_string_concat +/// * enable speculative parallelism (generally parallel via branch prediction) +/// try_add, add, try_sub, sub, is_at_least +/// * create read/write conflicts, as if you were using a regular field +/// read, read_snapshot, read_derived_string +module aptos_framework::aggregator_v2 { + use std::error; + use std::features; + use std::string::String; + + /// The value of aggregator overflows. Raised by uncoditional add() call + const EAGGREGATOR_OVERFLOW: u64 = 1; + + /// The value of aggregator underflows (goes below zero). Raised by uncoditional sub() call + const EAGGREGATOR_UNDERFLOW: u64 = 2; + + /// The generic type supplied to the aggregator snapshot is not supported. + const EUNSUPPORTED_AGGREGATOR_SNAPSHOT_TYPE: u64 = 5; + + /// The aggregator api v2 feature flag is not enabled. + const EAGGREGATOR_API_V2_NOT_ENABLED: u64 = 6; + + /// The generic type supplied to the aggregator is not supported. + const EUNSUPPORTED_AGGREGATOR_TYPE: u64 = 7; + + /// Arguments passed to concat exceed max limit of 256 bytes (for prefix and suffix together). + const ECONCAT_STRING_LENGTH_TOO_LARGE: u64 = 8; + + /// The native aggregator function, that is in the move file, is not yet supported. + /// and any calls will raise this error. + const EAGGREGATOR_FUNCTION_NOT_YET_SUPPORTED: u64 = 9; + + /// Represents an integer which supports parallel additions and subtractions + /// across multiple transactions. See the module description for more details. + /// + /// Currently supported types for IntElement are u64 and u128. + struct Aggregator has store, drop { + value: IntElement, + max_value: IntElement, + } + + /// Represents a constant value, that was derived from an aggregator at given instant in time. + /// Unlike read() and storing the value directly, this enables parallel execution of transactions, + /// while storing snapshot of aggregator state elsewhere. + struct AggregatorSnapshot has store, drop { + value: IntElement, + } + + struct DerivedStringSnapshot has store, drop { + value: String, + padding: vector, + } + + /// Returns `max_value` exceeding which aggregator overflows. + public fun max_value(aggregator: &Aggregator): IntElement { + aggregator.max_value + } + + /// Creates new aggregator, with given 'max_value'. + /// + /// Currently supported types for IntElement are u64 and u128. + /// EAGGREGATOR_ELEMENT_TYPE_NOT_SUPPORTED raised if called with a different type. + public native fun create_aggregator(max_value: IntElement): Aggregator; + + public fun create_aggregator_with_value(start_value: IntElement, max_value: IntElement): Aggregator { + let aggregator = create_aggregator(max_value); + add(&mut aggregator, start_value); + aggregator + } + + /// Creates new aggregator, without any 'max_value' on top of the implicit bound restriction + /// due to the width of the type (i.e. MAX_U64 for u64, MAX_U128 for u128). + /// + /// Currently supported types for IntElement are u64 and u128. + /// EAGGREGATOR_ELEMENT_TYPE_NOT_SUPPORTED raised if called with a different type. + public native fun create_unbounded_aggregator(): Aggregator; + + public fun create_unbounded_aggregator_with_value(start_value: IntElement): Aggregator { + let aggregator = create_unbounded_aggregator(); + add(&mut aggregator, start_value); + aggregator + } + + /// Adds `value` to aggregator. + /// If addition would exceed the max_value, `false` is returned, and aggregator value is left unchanged. + /// + /// Parallelism info: This operation enables speculative parallelism. + public native fun try_add(aggregator: &mut Aggregator, value: IntElement): bool; + + /// Adds `value` to aggregator, unconditionally. + /// If addition would exceed the max_value, EAGGREGATOR_OVERFLOW exception will be thrown. + /// + /// Parallelism info: This operation enables speculative parallelism. + public fun add(aggregator: &mut Aggregator, value: IntElement) { + assert!(try_add(aggregator, value), error::out_of_range(EAGGREGATOR_OVERFLOW)); + } + + /// Subtracts `value` from aggregator. + /// If subtraction would result in a negative value, `false` is returned, and aggregator value is left unchanged. + /// + /// Parallelism info: This operation enables speculative parallelism. + public native fun try_sub(aggregator: &mut Aggregator, value: IntElement): bool; + + // Subtracts `value` to aggregator, unconditionally. + // If subtraction would result in a negative value, EAGGREGATOR_UNDERFLOW exception will be thrown. + /// + /// Parallelism info: This operation enables speculative parallelism. + public fun sub(aggregator: &mut Aggregator, value: IntElement) { + assert!(try_sub(aggregator, value), error::out_of_range(EAGGREGATOR_UNDERFLOW)); + } + + native fun is_at_least_impl(aggregator: &Aggregator, min_amount: IntElement): bool; + + /// Returns true if aggregator value is larger than or equal to the given `min_amount`, false otherwise. + /// + /// This operation is more efficient and much more parallelization friendly than calling `read(agg) > min_amount`. + /// Until traits are deployed, `is_at_most`/`is_equal` utility methods can be derived from this one (assuming +1 doesn't overflow): + /// - for `is_at_most(agg, max_amount)`, you can do `!is_at_least(max_amount + 1)` + /// - for `is_equal(agg, value)`, you can do `is_at_least(value) && !is_at_least(value + 1)` + /// + /// Parallelism info: This operation enables speculative parallelism. + public fun is_at_least(aggregator: &Aggregator, min_amount: IntElement): bool { + assert!(features::aggregator_v2_is_at_least_api_enabled(), EAGGREGATOR_API_V2_NOT_ENABLED); + is_at_least_impl(aggregator, min_amount) + } + + // TODO waiting for integer traits + // public fun is_at_most(aggregator: &Aggregator, max_amount: IntElement): bool { + // !is_at_least(max_amount + 1) + // } + + // TODO waiting for integer traits + // public fun is_equal(aggregator: &Aggregator, value: IntElement): bool { + // is_at_least(value) && !is_at_least(value + 1) + // } + + /// Returns a value stored in this aggregator. + /// Note: This operation is resource-intensive, and reduces parallelism. + /// If you need to capture the value, without revealing it, use snapshot function instead, + /// which has no parallelism impact. + /// If called in a transaction that also modifies the aggregator, or has other read/write conflicts, + /// it will sequentialize that transaction. (i.e. up to concurrency_level times slower) + /// If called in a separate transaction (i.e. after transaction that modifies aggregator), it might be + /// up to two times slower. + /// + /// Parallelism info: This operation *prevents* speculative parallelism. + public native fun read(aggregator: &Aggregator): IntElement; + + /// Returns a wrapper of a current value of an aggregator + /// Unlike read(), it is fast and avoids sequential dependencies. + /// + /// Parallelism info: This operation enables parallelism. + public native fun snapshot(aggregator: &Aggregator): AggregatorSnapshot; + + /// Creates a snapshot of a given value. + /// Useful for when object is sometimes created via snapshot() or string_concat(), and sometimes directly. + public native fun create_snapshot(value: IntElement): AggregatorSnapshot; + + /// Returns a value stored in this snapshot. + /// Note: This operation is resource-intensive, and reduces parallelism. + /// (Especially if called in a transaction that also modifies the aggregator, + /// or has other read/write conflicts) + /// + /// Parallelism info: This operation *prevents* speculative parallelism. + public native fun read_snapshot(snapshot: &AggregatorSnapshot): IntElement; + + /// Returns a value stored in this DerivedStringSnapshot. + /// Note: This operation is resource-intensive, and reduces parallelism. + /// (Especially if called in a transaction that also modifies the aggregator, + /// or has other read/write conflicts) + /// + /// Parallelism info: This operation *prevents* speculative parallelism. + public native fun read_derived_string(snapshot: &DerivedStringSnapshot): String; + + /// Creates a DerivedStringSnapshot of a given value. + /// Useful for when object is sometimes created via string_concat(), and sometimes directly. + public native fun create_derived_string(value: String): DerivedStringSnapshot; + + /// Concatenates `before`, `snapshot` and `after` into a single string. + /// snapshot passed needs to have integer type - currently supported types are u64 and u128. + /// Raises EUNSUPPORTED_AGGREGATOR_SNAPSHOT_TYPE if called with another type. + /// If length of prefix and suffix together exceed 256 bytes, ECONCAT_STRING_LENGTH_TOO_LARGE is raised. + /// + /// Parallelism info: This operation enables parallelism. + public native fun derive_string_concat(before: String, snapshot: &AggregatorSnapshot, after: String): DerivedStringSnapshot; + + // ===== DEPRECATE/NOT YET IMPLEMENTED ==== + + #[deprecated] + /// NOT YET IMPLEMENTED, always raises EAGGREGATOR_FUNCTION_NOT_YET_SUPPORTED. + public native fun copy_snapshot(snapshot: &AggregatorSnapshot): AggregatorSnapshot; + + #[deprecated] + /// DEPRECATED, use derive_string_concat() instead. always raises EAGGREGATOR_FUNCTION_NOT_YET_SUPPORTED. + public native fun string_concat(before: String, snapshot: &AggregatorSnapshot, after: String): AggregatorSnapshot; + + // ======================================== + + #[test] + fun test_aggregator() { + let agg = create_aggregator(10); + assert!(try_add(&mut agg, 5), 1); + assert!(try_add(&mut agg, 5), 2); + assert!(read(&agg) == 10, 3); + assert!(!try_add(&mut agg, 5), 4); + assert!(read(&agg) == 10, 5); + assert!(try_sub(&mut agg, 5), 6); + assert!(read(&agg) == 5, 7); + + let snap = snapshot(&agg); + assert!(try_add(&mut agg, 2), 8); + assert!(read(&agg) == 7, 9); + assert!(read_snapshot(&snap) == 5, 10); + } + + #[test] + fun test_correct_read() { + let snapshot = create_snapshot(42); + assert!(read_snapshot(&snapshot) == 42, 0); + + let derived = create_derived_string(std::string::utf8(b"42")); + assert!(read_derived_string(&derived) == std::string::utf8(b"42"), 0); + } + + #[test] + #[expected_failure(abort_code = 0x030009, location = Self)] + fun test_copy_not_yet_supported() { + let snapshot = create_snapshot(42); + copy_snapshot(&snapshot); + } + + #[test] + fun test_string_concat1() { + let snapshot = create_snapshot(42); + let derived = derive_string_concat(std::string::utf8(b"before"), &snapshot, std::string::utf8(b"after")); + assert!(read_derived_string(&derived) == std::string::utf8(b"before42after"), 0); + } + + #[test] + #[expected_failure(abort_code = 0x030007, location = Self)] + fun test_aggregator_invalid_type1() { + create_unbounded_aggregator(); + } + + #[test] + fun test_aggregator_valid_type() { + create_unbounded_aggregator(); + create_unbounded_aggregator(); + create_aggregator(5); + create_aggregator(5); + } + + #[test] + #[expected_failure(abort_code = 0x030005, location = Self)] + fun test_snpashot_invalid_type1() { + use std::option; + create_snapshot(option::some(42)); + } + + #[test] + #[expected_failure(abort_code = 0x030005, location = Self)] + fun test_snpashot_invalid_type2() { + create_snapshot(vector[42]); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aptos_account.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aptos_account.move new file mode 100644 index 000000000..8d7c367cb --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aptos_account.move @@ -0,0 +1,444 @@ +module aptos_framework::aptos_account { + use aptos_framework::account::{Self, new_event_handle}; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::coin::{Self, Coin}; + use aptos_framework::create_signer::create_signer; + use aptos_framework::event::{EventHandle, emit_event, emit}; + use aptos_framework::fungible_asset::{Self, Metadata, BurnRef}; + use aptos_framework::primary_fungible_store; + use aptos_framework::object; + + use std::error; + use std::features; + use std::signer; + use std::vector; + + friend aptos_framework::genesis; + friend aptos_framework::resource_account; + friend aptos_framework::transaction_fee; + friend aptos_framework::transaction_validation; + friend aptos_framework::governed_gas_pool; + + /// Account does not exist. + const EACCOUNT_NOT_FOUND: u64 = 1; + /// Account is not registered to receive APT. + const EACCOUNT_NOT_REGISTERED_FOR_APT: u64 = 2; + /// Account opted out of receiving coins that they did not register to receive. + const EACCOUNT_DOES_NOT_ACCEPT_DIRECT_COIN_TRANSFERS: u64 = 3; + /// Account opted out of directly receiving NFT tokens. + const EACCOUNT_DOES_NOT_ACCEPT_DIRECT_TOKEN_TRANSFERS: u64 = 4; + /// The lengths of the recipients and amounts lists don't match. + const EMISMATCHING_RECIPIENTS_AND_AMOUNTS_LENGTH: u64 = 5; + + /// Configuration for whether an account can receive direct transfers of coins that they have not registered. + /// + /// By default, this is enabled. Users can opt-out by disabling at any time. + struct DirectTransferConfig has key { + allow_arbitrary_coin_transfers: bool, + update_coin_transfer_events: EventHandle, + } + + /// Event emitted when an account's direct coins transfer config is updated. + struct DirectCoinTransferConfigUpdatedEvent has drop, store { + new_allow_direct_transfers: bool, + } + + #[event] + struct DirectCoinTransferConfigUpdated has drop, store { + account: address, + new_allow_direct_transfers: bool, + } + + /////////////////////////////////////////////////////////////////////////// + /// Basic account creation methods. + /////////////////////////////////////////////////////////////////////////// + + public entry fun create_account(auth_key: address) { + let account_signer = account::create_account(auth_key); + register_apt(&account_signer); + } + + /// Batch version of APT transfer. + public entry fun batch_transfer(source: &signer, recipients: vector
, amounts: vector) { + let recipients_len = vector::length(&recipients); + assert!( + recipients_len == vector::length(&amounts), + error::invalid_argument(EMISMATCHING_RECIPIENTS_AND_AMOUNTS_LENGTH), + ); + + vector::enumerate_ref(&recipients, |i, to| { + let amount = *vector::borrow(&amounts, i); + transfer(source, *to, amount); + }); + } + + /// Convenient function to transfer APT to a recipient account that might not exist. + /// This would create the recipient account first, which also registers it to receive APT, before transferring. + public entry fun transfer(source: &signer, to: address, amount: u64) { + if (!account::exists_at(to)) { + create_account(to) + }; + + if (features::operations_default_to_fa_apt_store_enabled()) { + fungible_transfer_only(source, to, amount) + } else { + // Resource accounts can be created without registering them to receive APT. + // This conveniently does the registration if necessary. + if (!coin::is_account_registered(to)) { + coin::register(&create_signer(to)); + }; + coin::transfer(source, to, amount) + } + } + + /// Batch version of transfer_coins. + public entry fun batch_transfer_coins( + from: &signer, recipients: vector
, amounts: vector) acquires DirectTransferConfig { + let recipients_len = vector::length(&recipients); + assert!( + recipients_len == vector::length(&amounts), + error::invalid_argument(EMISMATCHING_RECIPIENTS_AND_AMOUNTS_LENGTH), + ); + + vector::enumerate_ref(&recipients, |i, to| { + let amount = *vector::borrow(&amounts, i); + transfer_coins(from, *to, amount); + }); + } + + /// Convenient function to transfer a custom CoinType to a recipient account that might not exist. + /// This would create the recipient account first and register it to receive the CoinType, before transferring. + public entry fun transfer_coins(from: &signer, to: address, amount: u64) acquires DirectTransferConfig { + deposit_coins(to, coin::withdraw(from, amount)); + } + + /// Convenient function to deposit a custom CoinType into a recipient account that might not exist. + /// This would create the recipient account first and register it to receive the CoinType, before transferring. + public fun deposit_coins(to: address, coins: Coin) acquires DirectTransferConfig { + if (!account::exists_at(to)) { + create_account(to); + spec { + assert coin::spec_is_account_registered(to); + assume aptos_std::type_info::type_of() == aptos_std::type_info::type_of() ==> + coin::spec_is_account_registered(to); + }; + }; + if (!coin::is_account_registered(to)) { + assert!( + can_receive_direct_coin_transfers(to), + error::permission_denied(EACCOUNT_DOES_NOT_ACCEPT_DIRECT_COIN_TRANSFERS), + ); + coin::register(&create_signer(to)); + }; + coin::deposit(to, coins) + } + + public fun assert_account_exists(addr: address) { + assert!(account::exists_at(addr), error::not_found(EACCOUNT_NOT_FOUND)); + } + + public fun assert_account_is_registered_for_apt(addr: address) { + assert_account_exists(addr); + assert!(coin::is_account_registered(addr), error::not_found(EACCOUNT_NOT_REGISTERED_FOR_APT)); + } + + /// Set whether `account` can receive direct transfers of coins that they have not explicitly registered to receive. + public entry fun set_allow_direct_coin_transfers(account: &signer, allow: bool) acquires DirectTransferConfig { + let addr = signer::address_of(account); + if (exists(addr)) { + let direct_transfer_config = borrow_global_mut(addr); + // Short-circuit to avoid emitting an event if direct transfer config is not changing. + if (direct_transfer_config.allow_arbitrary_coin_transfers == allow) { + return + }; + + direct_transfer_config.allow_arbitrary_coin_transfers = allow; + + if (std::features::module_event_migration_enabled()) { + emit(DirectCoinTransferConfigUpdated { account: addr, new_allow_direct_transfers: allow }); + }; + emit_event( + &mut direct_transfer_config.update_coin_transfer_events, + DirectCoinTransferConfigUpdatedEvent { new_allow_direct_transfers: allow }); + } else { + let direct_transfer_config = DirectTransferConfig { + allow_arbitrary_coin_transfers: allow, + update_coin_transfer_events: new_event_handle(account), + }; + if (std::features::module_event_migration_enabled()) { + emit(DirectCoinTransferConfigUpdated { account: addr, new_allow_direct_transfers: allow }); + }; + emit_event( + &mut direct_transfer_config.update_coin_transfer_events, + DirectCoinTransferConfigUpdatedEvent { new_allow_direct_transfers: allow }); + move_to(account, direct_transfer_config); + }; + } + + #[view] + /// Return true if `account` can receive direct transfers of coins that they have not explicitly registered to + /// receive. + /// + /// By default, this returns true if an account has not explicitly set whether the can receive direct transfers. + public fun can_receive_direct_coin_transfers(account: address): bool acquires DirectTransferConfig { + !exists(account) || + borrow_global(account).allow_arbitrary_coin_transfers + } + + public(friend) fun register_apt(account_signer: &signer) { + if (features::new_accounts_default_to_fa_apt_store_enabled()) { + ensure_primary_fungible_store_exists(signer::address_of(account_signer)); + } else { + coin::register(account_signer); + } + } + + /// APT Primary Fungible Store specific specialized functions, + /// Utilized internally once migration of APT to FungibleAsset is complete. + + /// Convenient function to transfer APT to a recipient account that might not exist. + /// This would create the recipient APT PFS first, which also registers it to receive APT, before transferring. + /// TODO: once migration is complete, rename to just "transfer_only" and make it an entry function (for cheapest way + /// to transfer APT) - if we want to allow APT PFS without account itself + fun fungible_transfer_only( + source: &signer, to: address, amount: u64 + ) { + let sender_store = ensure_primary_fungible_store_exists(signer::address_of(source)); + let recipient_store = ensure_primary_fungible_store_exists(to); + + // use internal APIs, as they skip: + // - owner, frozen and dispatchable checks + // as APT cannot be frozen or have dispatch, and PFS cannot be transfered + // (PFS could potentially be burned. regular transfer would permanently unburn the store. + // Ignoring the check here has the equivalent of unburning, transfers, and then burning again) + fungible_asset::deposit_internal(recipient_store, fungible_asset::withdraw_internal(sender_store, amount)); + } + + /// Is balance from APT Primary FungibleStore at least the given amount + public(friend) fun is_fungible_balance_at_least(account: address, amount: u64): bool { + let store_addr = primary_fungible_store_address(account); + fungible_asset::is_address_balance_at_least(store_addr, amount) + } + + /// Burn from APT Primary FungibleStore + public(friend) fun burn_from_fungible_store( + ref: &BurnRef, + account: address, + amount: u64, + ) { + // Skip burning if amount is zero. This shouldn't error out as it's called as part of transaction fee burning. + if (amount != 0) { + let store_addr = primary_fungible_store_address(account); + fungible_asset::address_burn_from(ref, store_addr, amount); + }; + } + + /// Ensure that APT Primary FungibleStore exists (and create if it doesn't) + inline fun ensure_primary_fungible_store_exists(owner: address): address { + let store_addr = primary_fungible_store_address(owner); + if (fungible_asset::store_exists(store_addr)) { + store_addr + } else { + object::object_address(&primary_fungible_store::create_primary_store(owner, object::address_to_object(@aptos_fungible_asset))) + } + } + + /// Address of APT Primary Fungible Store + inline fun primary_fungible_store_address(account: address): address { + object::create_user_derived_object_address(account, @aptos_fungible_asset) + } + + // tests + + #[test_only] + use aptos_std::from_bcs; + #[test_only] + use std::string::utf8; + #[test_only] + use aptos_framework::account::create_account_for_test; + + #[test_only] + struct FakeCoin {} + + #[test(alice = @0xa11ce, core = @0x1)] + public fun test_transfer(alice: &signer, core: &signer) { + let bob = from_bcs::to_address(x"0000000000000000000000000000000000000000000000000000000000000b0b"); + let carol = from_bcs::to_address(x"00000000000000000000000000000000000000000000000000000000000ca501"); + + let (burn_cap, mint_cap) = aptos_framework::aptos_coin::initialize_for_test(core); + create_account(signer::address_of(alice)); + coin::deposit(signer::address_of(alice), coin::mint(10000, &mint_cap)); + transfer(alice, bob, 500); + assert!(coin::balance(bob) == 500, 0); + transfer(alice, carol, 500); + assert!(coin::balance(carol) == 500, 1); + transfer(alice, carol, 1500); + assert!(coin::balance(carol) == 2000, 2); + + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + } + + #[test(alice = @0xa11ce, core = @0x1)] + public fun test_transfer_to_resource_account(alice: &signer, core: &signer) { + let (resource_account, _) = account::create_resource_account(alice, vector[]); + let resource_acc_addr = signer::address_of(&resource_account); + let (burn_cap, mint_cap) = aptos_framework::aptos_coin::initialize_for_test(core); + assert!(!coin::is_account_registered(resource_acc_addr), 0); + + create_account(signer::address_of(alice)); + coin::deposit(signer::address_of(alice), coin::mint(10000, &mint_cap)); + transfer(alice, resource_acc_addr, 500); + assert!(coin::balance(resource_acc_addr) == 500, 1); + + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + } + + #[test(from = @0x123, core = @0x1, recipient_1 = @0x124, recipient_2 = @0x125)] + public fun test_batch_transfer(from: &signer, core: &signer, recipient_1: &signer, recipient_2: &signer) { + let (burn_cap, mint_cap) = aptos_framework::aptos_coin::initialize_for_test(core); + create_account(signer::address_of(from)); + let recipient_1_addr = signer::address_of(recipient_1); + let recipient_2_addr = signer::address_of(recipient_2); + create_account(recipient_1_addr); + create_account(recipient_2_addr); + coin::deposit(signer::address_of(from), coin::mint(10000, &mint_cap)); + batch_transfer( + from, + vector[recipient_1_addr, recipient_2_addr], + vector[100, 500], + ); + assert!(coin::balance(recipient_1_addr) == 100, 0); + assert!(coin::balance(recipient_2_addr) == 500, 1); + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + } + + #[test(from = @0x1, to = @0x12)] + public fun test_direct_coin_transfers(from: &signer, to: &signer) acquires DirectTransferConfig { + let (burn_cap, freeze_cap, mint_cap) = coin::initialize( + from, + utf8(b"FC"), + utf8(b"FC"), + 10, + true, + ); + create_account_for_test(signer::address_of(from)); + create_account_for_test(signer::address_of(to)); + deposit_coins(signer::address_of(from), coin::mint(1000, &mint_cap)); + // Recipient account did not explicit register for the coin. + let to_addr = signer::address_of(to); + transfer_coins(from, to_addr, 500); + assert!(coin::balance(to_addr) == 500, 0); + + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + coin::destroy_freeze_cap(freeze_cap); + } + + #[test(from = @0x1, recipient_1 = @0x124, recipient_2 = @0x125)] + public fun test_batch_transfer_coins( + from: &signer, recipient_1: &signer, recipient_2: &signer) acquires DirectTransferConfig { + let (burn_cap, freeze_cap, mint_cap) = coin::initialize( + from, + utf8(b"FC"), + utf8(b"FC"), + 10, + true, + ); + create_account_for_test(signer::address_of(from)); + let recipient_1_addr = signer::address_of(recipient_1); + let recipient_2_addr = signer::address_of(recipient_2); + create_account_for_test(recipient_1_addr); + create_account_for_test(recipient_2_addr); + deposit_coins(signer::address_of(from), coin::mint(1000, &mint_cap)); + batch_transfer_coins( + from, + vector[recipient_1_addr, recipient_2_addr], + vector[100, 500], + ); + assert!(coin::balance(recipient_1_addr) == 100, 0); + assert!(coin::balance(recipient_2_addr) == 500, 1); + + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + coin::destroy_freeze_cap(freeze_cap); + } + + #[test(user = @0x123)] + public fun test_set_allow_direct_coin_transfers(user: &signer) acquires DirectTransferConfig { + let addr = signer::address_of(user); + create_account_for_test(addr); + set_allow_direct_coin_transfers(user, true); + assert!(can_receive_direct_coin_transfers(addr), 0); + set_allow_direct_coin_transfers(user, false); + assert!(!can_receive_direct_coin_transfers(addr), 1); + set_allow_direct_coin_transfers(user, true); + assert!(can_receive_direct_coin_transfers(addr), 2); + } + + #[test(from = @0x1, to = @0x12)] + public fun test_direct_coin_transfers_with_explicit_direct_coin_transfer_config( + from: &signer, to: &signer) acquires DirectTransferConfig { + let (burn_cap, freeze_cap, mint_cap) = coin::initialize( + from, + utf8(b"FC"), + utf8(b"FC"), + 10, + true, + ); + create_account_for_test(signer::address_of(from)); + create_account_for_test(signer::address_of(to)); + set_allow_direct_coin_transfers(from, true); + deposit_coins(signer::address_of(from), coin::mint(1000, &mint_cap)); + // Recipient account did not explicit register for the coin. + let to_addr = signer::address_of(to); + transfer_coins(from, to_addr, 500); + assert!(coin::balance(to_addr) == 500, 0); + + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + coin::destroy_freeze_cap(freeze_cap); + } + + #[test(from = @0x1, to = @0x12)] + #[expected_failure(abort_code = 0x50003, location = Self)] + public fun test_direct_coin_transfers_fail_if_recipient_opted_out( + from: &signer, to: &signer) acquires DirectTransferConfig { + let (burn_cap, freeze_cap, mint_cap) = coin::initialize( + from, + utf8(b"FC"), + utf8(b"FC"), + 10, + true, + ); + create_account_for_test(signer::address_of(from)); + create_account_for_test(signer::address_of(to)); + set_allow_direct_coin_transfers(from, false); + deposit_coins(signer::address_of(from), coin::mint(1000, &mint_cap)); + // This should fail as the to account has explicitly opted out of receiving arbitrary coins. + transfer_coins(from, signer::address_of(to), 500); + + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + coin::destroy_freeze_cap(freeze_cap); + } + + #[test(user = @0xcafe)] + fun test_primary_fungible_store_address( + user: &signer, + ) { + use aptos_framework::fungible_asset::Metadata; + use aptos_framework::aptos_coin; + + aptos_coin::ensure_initialized_with_apt_fa_metadata_for_test(); + + let apt_metadata = object::address_to_object(@aptos_fungible_asset); + let user_addr = signer::address_of(user); + assert!(primary_fungible_store_address(user_addr) == primary_fungible_store::primary_store_address(user_addr, apt_metadata), 1); + + ensure_primary_fungible_store_exists(user_addr); + assert!(primary_fungible_store::primary_store_exists(user_addr, apt_metadata), 2); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aptos_coin.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aptos_coin.move new file mode 100644 index 000000000..6fdd9bc8e --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aptos_coin.move @@ -0,0 +1,204 @@ +/// This module defines a minimal and generic Coin and Balance. +/// modified from https://github.com/move-language/move/tree/main/language/documentation/tutorial +module aptos_framework::aptos_coin { + use std::error; + use std::signer; + use std::string; + use std::vector; + use std::option::{Self, Option}; + + use aptos_framework::coin::{Self, BurnCapability, MintCapability}; + use aptos_framework::system_addresses; + + friend aptos_framework::genesis; + + /// Account does not have mint capability + const ENO_CAPABILITIES: u64 = 1; + /// Mint capability has already been delegated to this specified address + const EALREADY_DELEGATED: u64 = 2; + /// Cannot find delegation of mint capability to this account + const EDELEGATION_NOT_FOUND: u64 = 3; + + struct AptosCoin has key {} + + struct MintCapStore has key { + mint_cap: MintCapability, + } + + /// Delegation token created by delegator and can be claimed by the delegatee as MintCapability. + struct DelegatedMintCapability has store { + to: address + } + + /// The container stores the current pending delegations. + struct Delegations has key { + inner: vector, + } + + /// Can only called during genesis to initialize the Aptos coin. + public(friend) fun initialize(aptos_framework: &signer): (BurnCapability, MintCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + + let (burn_cap, freeze_cap, mint_cap) = coin::initialize_with_parallelizable_supply( + aptos_framework, + string::utf8(b"Move Coin"), + string::utf8(b"MOVE"), + 8, // decimals + true, // monitor_supply + ); + + // Aptos framework needs mint cap to mint coins to initial validators. This will be revoked once the validators + // have been initialized. + move_to(aptos_framework, MintCapStore { mint_cap }); + + coin::destroy_freeze_cap(freeze_cap); + (burn_cap, mint_cap) + } + + public fun has_mint_capability(account: &signer): bool { + exists(signer::address_of(account)) + } + + /// Only called during genesis to destroy the aptos framework account's mint capability once all initial validators + /// and accounts have been initialized during genesis. + public(friend) fun destroy_mint_cap(aptos_framework: &signer) acquires MintCapStore { + system_addresses::assert_aptos_framework(aptos_framework); + let MintCapStore { mint_cap } = move_from(@aptos_framework); + coin::destroy_mint_cap(mint_cap); + } + + /// Can only be called during genesis for tests to grant mint capability to aptos framework and core resources + /// accounts. + /// Expects account and APT store to be registered before calling. + public(friend) fun configure_accounts_for_test( + aptos_framework: &signer, + core_resources: &signer, + mint_cap: MintCapability, + ) { + system_addresses::assert_aptos_framework(aptos_framework); + + // Mint the core resource account AptosCoin for gas so it can execute system transactions. + let coins = coin::mint( + 18446744073709551615, + &mint_cap, + ); + coin::deposit(signer::address_of(core_resources), coins); + + move_to(core_resources, MintCapStore { mint_cap }); + move_to(core_resources, Delegations { inner: vector::empty() }); + } + + /// Only callable in tests and testnets where the core resources account exists. + /// Create new coins and deposit them into dst_addr's account. + public entry fun mint( + account: &signer, + dst_addr: address, + amount: u64, + ) acquires MintCapStore { + let account_addr = signer::address_of(account); + + assert!( + exists(account_addr), + error::not_found(ENO_CAPABILITIES), + ); + + let mint_cap = &borrow_global(account_addr).mint_cap; + let coins_minted = coin::mint(amount, mint_cap); + coin::deposit(dst_addr, coins_minted); + } + + /// Only callable in tests and testnets where the core resources account exists. + /// Create delegated token for the address so the account could claim MintCapability later. + public entry fun delegate_mint_capability(account: signer, to: address) acquires Delegations { + system_addresses::assert_core_resource(&account); + let delegations = &mut borrow_global_mut(@core_resources).inner; + vector::for_each_ref(delegations, |element| { + let element: &DelegatedMintCapability = element; + assert!(element.to != to, error::invalid_argument(EALREADY_DELEGATED)); + }); + vector::push_back(delegations, DelegatedMintCapability { to }); + } + + /// Only callable in tests and testnets where the core resources account exists. + /// Claim the delegated mint capability and destroy the delegated token. + public entry fun claim_mint_capability(account: &signer) acquires Delegations, MintCapStore { + let maybe_index = find_delegation(signer::address_of(account)); + assert!(option::is_some(&maybe_index), EDELEGATION_NOT_FOUND); + let idx = *option::borrow(&maybe_index); + let delegations = &mut borrow_global_mut(@core_resources).inner; + let DelegatedMintCapability { to: _ } = vector::swap_remove(delegations, idx); + + // Make a copy of mint cap and give it to the specified account. + let mint_cap = borrow_global(@core_resources).mint_cap; + move_to(account, MintCapStore { mint_cap }); + } + + fun find_delegation(addr: address): Option acquires Delegations { + let delegations = &borrow_global(@core_resources).inner; + let i = 0; + let len = vector::length(delegations); + let index = option::none(); + while (i < len) { + let element = vector::borrow(delegations, i); + if (element.to == addr) { + index = option::some(i); + break + }; + i = i + 1; + }; + index + } + + #[test_only] + use aptos_framework::account; + #[test_only] + use aptos_framework::aggregator_factory; + #[test_only] + use aptos_framework::fungible_asset::FungibleAsset; + + #[test_only] + public fun mint_apt_fa_for_test(amount: u64): FungibleAsset acquires MintCapStore { + ensure_initialized_with_apt_fa_metadata_for_test(); + coin::coin_to_fungible_asset( + coin::mint( + amount, + &borrow_global(@aptos_framework).mint_cap + ) + ) + } + + #[test_only] + public fun ensure_initialized_with_apt_fa_metadata_for_test() { + let aptos_framework = account::create_signer_for_test(@aptos_framework); + if (!exists(@aptos_framework)) { + if (!aggregator_factory::aggregator_factory_exists_for_testing()) { + aggregator_factory::initialize_aggregator_factory_for_test(&aptos_framework); + }; + let (burn_cap, mint_cap) = initialize(&aptos_framework); + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + }; + coin::create_coin_conversion_map(&aptos_framework); + coin::create_pairing(&aptos_framework); + } + + #[test_only] + public fun initialize_for_test(aptos_framework: &signer): (BurnCapability, MintCapability) { + aggregator_factory::initialize_aggregator_factory_for_test(aptos_framework); + let (burn_cap, mint_cap) = initialize(aptos_framework); + coin::create_coin_conversion_map(aptos_framework); + coin::create_pairing(aptos_framework); + (burn_cap, mint_cap) + } + + // This is particularly useful if the aggregator_factory is already initialized via another call path. + #[test_only] + public fun initialize_for_test_without_aggregator_factory( + aptos_framework: &signer + ): (BurnCapability, MintCapability) { + let (burn_cap, mint_cap) = initialize(aptos_framework); + coin::create_coin_conversion_map(aptos_framework); + coin::create_pairing(aptos_framework); + (burn_cap, mint_cap) + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aptos_governance.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aptos_governance.move new file mode 100644 index 000000000..19c8d45c9 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/aptos_governance.move @@ -0,0 +1,1387 @@ +/// +/// AptosGovernance represents the on-chain governance of the Aptos network. Voting power is calculated based on the +/// current epoch's voting power of the proposer or voter's backing stake pool. In addition, for it to count, +/// the stake pool's lockup needs to be at least as long as the proposal's duration. +/// +/// It provides the following flow: +/// 1. Proposers can create a proposal by calling AptosGovernance::create_proposal. The proposer's backing stake pool +/// needs to have the minimum proposer stake required. Off-chain components can subscribe to CreateProposalEvent to +/// track proposal creation and proposal ids. +/// 2. Voters can vote on a proposal. Their voting power is derived from the backing stake pool. A stake pool can vote +/// on a proposal multiple times as long as the total voting power of these votes doesn't exceed its total voting power. +module aptos_framework::aptos_governance { + use std::error; + use std::option; + use std::signer; + use std::string::{Self, String, utf8}; + use std::vector; + use std::features; + + use aptos_std::math64::min; + use aptos_std::simple_map::{Self, SimpleMap}; + use aptos_std::smart_table::{Self, SmartTable}; + use aptos_std::table::{Self, Table}; + + use aptos_framework::account::{Self, SignerCapability, create_signer_with_capability}; + use aptos_framework::coin; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::governance_proposal::{Self, GovernanceProposal}; + use aptos_framework::stake; + use aptos_framework::staking_config; + use aptos_framework::system_addresses; + use aptos_framework::aptos_coin::{Self, AptosCoin}; + use aptos_framework::consensus_config; + use aptos_framework::randomness_config; + use aptos_framework::reconfiguration_with_dkg; + use aptos_framework::timestamp; + use aptos_framework::voting; + + /// The specified stake pool does not have sufficient stake to create a proposal + const EINSUFFICIENT_PROPOSER_STAKE: u64 = 1; + /// This account is not the designated voter of the specified stake pool + const ENOT_DELEGATED_VOTER: u64 = 2; + /// The specified stake pool does not have long enough remaining lockup to create a proposal or vote + const EINSUFFICIENT_STAKE_LOCKUP: u64 = 3; + /// The specified stake pool has already been used to vote on the same proposal + const EALREADY_VOTED: u64 = 4; + /// The specified stake pool must be part of the validator set + const ENO_VOTING_POWER: u64 = 5; + /// Proposal is not ready to be resolved. Waiting on time or votes + const EPROPOSAL_NOT_RESOLVABLE_YET: u64 = 6; + /// The proposal has not been resolved yet + const EPROPOSAL_NOT_RESOLVED_YET: u64 = 8; + /// Metadata location cannot be longer than 256 chars + const EMETADATA_LOCATION_TOO_LONG: u64 = 9; + /// Metadata hash cannot be longer than 256 chars + const EMETADATA_HASH_TOO_LONG: u64 = 10; + /// Account is not authorized to call this function. + const EUNAUTHORIZED: u64 = 11; + /// The stake pool is using voting power more than it has. + const EVOTING_POWER_OVERFLOW: u64 = 12; + /// Partial voting feature hasn't been properly initialized. + const EPARTIAL_VOTING_NOT_INITIALIZED: u64 = 13; + /// The proposal in the argument is not a partial voting proposal. + const ENOT_PARTIAL_VOTING_PROPOSAL: u64 = 14; + + /// This matches the same enum const in voting. We have to duplicate it as Move doesn't have support for enums yet. + const PROPOSAL_STATE_SUCCEEDED: u64 = 1; + + const MAX_U64: u64 = 18446744073709551615; + + /// Proposal metadata attribute keys. + const METADATA_LOCATION_KEY: vector = b"metadata_location"; + const METADATA_HASH_KEY: vector = b"metadata_hash"; + + /// Store the SignerCapabilities of accounts under the on-chain governance's control. + struct GovernanceResponsbility has key { + signer_caps: SimpleMap, + } + + /// Configurations of the AptosGovernance, set during Genesis and can be updated by the same process offered + /// by this AptosGovernance module. + struct GovernanceConfig has key { + min_voting_threshold: u128, + required_proposer_stake: u64, + voting_duration_secs: u64, + } + + struct RecordKey has copy, drop, store { + stake_pool: address, + proposal_id: u64, + } + + /// Records to track the proposals each stake pool has been used to vote on. + struct VotingRecords has key { + votes: Table + } + + /// Records to track the voting power usage of each stake pool on each proposal. + struct VotingRecordsV2 has key { + votes: SmartTable + } + + /// Used to track which execution script hashes have been approved by governance. + /// This is required to bypass cases where the execution scripts exceed the size limit imposed by mempool. + struct ApprovedExecutionHashes has key { + hashes: SimpleMap>, + } + + /// Events generated by interactions with the AptosGovernance module. + struct GovernanceEvents has key { + create_proposal_events: EventHandle, + update_config_events: EventHandle, + vote_events: EventHandle, + } + + /// Event emitted when a proposal is created. + struct CreateProposalEvent has drop, store { + proposer: address, + stake_pool: address, + proposal_id: u64, + execution_hash: vector, + proposal_metadata: SimpleMap>, + } + + /// Event emitted when there's a vote on a proposa; + struct VoteEvent has drop, store { + proposal_id: u64, + voter: address, + stake_pool: address, + num_votes: u64, + should_pass: bool, + } + + /// Event emitted when the governance configs are updated. + struct UpdateConfigEvent has drop, store { + min_voting_threshold: u128, + required_proposer_stake: u64, + voting_duration_secs: u64, + } + + #[event] + /// Event emitted when a proposal is created. + struct CreateProposal has drop, store { + proposer: address, + stake_pool: address, + proposal_id: u64, + execution_hash: vector, + proposal_metadata: SimpleMap>, + } + + #[event] + /// Event emitted when there's a vote on a proposa; + struct Vote has drop, store { + proposal_id: u64, + voter: address, + stake_pool: address, + num_votes: u64, + should_pass: bool, + } + + #[event] + /// Event emitted when the governance configs are updated. + struct UpdateConfig has drop, store { + min_voting_threshold: u128, + required_proposer_stake: u64, + voting_duration_secs: u64, + } + + /// Can be called during genesis or by the governance itself. + /// Stores the signer capability for a given address. + public fun store_signer_cap( + aptos_framework: &signer, + signer_address: address, + signer_cap: SignerCapability, + ) acquires GovernanceResponsbility { + system_addresses::assert_aptos_framework(aptos_framework); + system_addresses::assert_framework_reserved(signer_address); + + if (!exists(@aptos_framework)) { + move_to( + aptos_framework, + GovernanceResponsbility { signer_caps: simple_map::create() } + ); + }; + + let signer_caps = &mut borrow_global_mut(@aptos_framework).signer_caps; + simple_map::add(signer_caps, signer_address, signer_cap); + } + + /// Initializes the state for Aptos Governance. Can only be called during Genesis with a signer + /// for the aptos_framework (0x1) account. + /// This function is private because it's called directly from the vm. + fun initialize( + aptos_framework: &signer, + min_voting_threshold: u128, + required_proposer_stake: u64, + voting_duration_secs: u64, + ) { + system_addresses::assert_aptos_framework(aptos_framework); + + voting::register(aptos_framework); + move_to(aptos_framework, GovernanceConfig { + voting_duration_secs, + min_voting_threshold, + required_proposer_stake, + }); + move_to(aptos_framework, GovernanceEvents { + create_proposal_events: account::new_event_handle(aptos_framework), + update_config_events: account::new_event_handle(aptos_framework), + vote_events: account::new_event_handle(aptos_framework), + }); + move_to(aptos_framework, VotingRecords { + votes: table::new(), + }); + move_to(aptos_framework, ApprovedExecutionHashes { + hashes: simple_map::create>(), + }) + } + + /// Update the governance configurations. This can only be called as part of resolving a proposal in this same + /// AptosGovernance. + public fun update_governance_config( + aptos_framework: &signer, + min_voting_threshold: u128, + required_proposer_stake: u64, + voting_duration_secs: u64, + ) acquires GovernanceConfig, GovernanceEvents { + system_addresses::assert_aptos_framework(aptos_framework); + + let governance_config = borrow_global_mut(@aptos_framework); + governance_config.voting_duration_secs = voting_duration_secs; + governance_config.min_voting_threshold = min_voting_threshold; + governance_config.required_proposer_stake = required_proposer_stake; + + if (std::features::module_event_migration_enabled()) { + event::emit( + UpdateConfig { + min_voting_threshold, + required_proposer_stake, + voting_duration_secs + }, + ) + }; + let events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut events.update_config_events, + UpdateConfigEvent { + min_voting_threshold, + required_proposer_stake, + voting_duration_secs + }, + ); + } + + /// Initializes the state for Aptos Governance partial voting. Can only be called through Aptos governance + /// proposals with a signer for the aptos_framework (0x1) account. + public fun initialize_partial_voting( + aptos_framework: &signer, + ) { + system_addresses::assert_aptos_framework(aptos_framework); + + move_to(aptos_framework, VotingRecordsV2 { + votes: smart_table::new(), + }); + } + + #[view] + public fun get_voting_duration_secs(): u64 acquires GovernanceConfig { + borrow_global(@aptos_framework).voting_duration_secs + } + + #[view] + public fun get_min_voting_threshold(): u128 acquires GovernanceConfig { + borrow_global(@aptos_framework).min_voting_threshold + } + + #[view] + public fun get_required_proposer_stake(): u64 acquires GovernanceConfig { + borrow_global(@aptos_framework).required_proposer_stake + } + + #[view] + /// Return true if a stake pool has already voted on a proposal before partial governance voting is enabled. + public fun has_entirely_voted(stake_pool: address, proposal_id: u64): bool acquires VotingRecords { + let record_key = RecordKey { + stake_pool, + proposal_id, + }; + // If a stake pool has already voted on a proposal before partial governance voting is enabled, + // there is a record in VotingRecords. + let voting_records = borrow_global(@aptos_framework); + table::contains(&voting_records.votes, record_key) + } + + #[view] + /// Return remaining voting power of a stake pool on a proposal. + /// Note: a stake pool's voting power on a proposal could increase over time(e.g. rewards/new stake). + public fun get_remaining_voting_power( + stake_pool: address, + proposal_id: u64 + ): u64 acquires VotingRecords, VotingRecordsV2 { + assert_voting_initialization(); + + let proposal_expiration = voting::get_proposal_expiration_secs( + @aptos_framework, + proposal_id + ); + let lockup_until = stake::get_lockup_secs(stake_pool); + // The voter's stake needs to be locked up at least as long as the proposal's expiration. + // Also no one can vote on a expired proposal. + if (proposal_expiration > lockup_until || timestamp::now_seconds() > proposal_expiration) { + return 0 + }; + + // If a stake pool has already voted on a proposal before partial governance voting is enabled, the stake pool + // cannot vote on the proposal even after partial governance voting is enabled. + if (has_entirely_voted(stake_pool, proposal_id)) { + return 0 + }; + let record_key = RecordKey { + stake_pool, + proposal_id, + }; + let used_voting_power = 0u64; + if (features::partial_governance_voting_enabled()) { + let voting_records_v2 = borrow_global(@aptos_framework); + used_voting_power = *smart_table::borrow_with_default(&voting_records_v2.votes, record_key, &0); + }; + get_voting_power(stake_pool) - used_voting_power + } + + /// Create a single-step proposal with the backing `stake_pool`. + /// @param execution_hash Required. This is the hash of the resolution script. When the proposal is resolved, + /// only the exact script with matching hash can be successfully executed. + public entry fun create_proposal( + proposer: &signer, + stake_pool: address, + execution_hash: vector, + metadata_location: vector, + metadata_hash: vector, + ) acquires GovernanceConfig, GovernanceEvents { + create_proposal_v2(proposer, stake_pool, execution_hash, metadata_location, metadata_hash, false); + } + + /// Create a single-step or multi-step proposal with the backing `stake_pool`. + /// @param execution_hash Required. This is the hash of the resolution script. When the proposal is resolved, + /// only the exact script with matching hash can be successfully executed. + public entry fun create_proposal_v2( + proposer: &signer, + stake_pool: address, + execution_hash: vector, + metadata_location: vector, + metadata_hash: vector, + is_multi_step_proposal: bool, + ) acquires GovernanceConfig, GovernanceEvents { + create_proposal_v2_impl( + proposer, + stake_pool, + execution_hash, + metadata_location, + metadata_hash, + is_multi_step_proposal + ); + } + + /// Create a single-step or multi-step proposal with the backing `stake_pool`. + /// @param execution_hash Required. This is the hash of the resolution script. When the proposal is resolved, + /// only the exact script with matching hash can be successfully executed. + /// Return proposal_id when a proposal is successfully created. + public fun create_proposal_v2_impl( + proposer: &signer, + stake_pool: address, + execution_hash: vector, + metadata_location: vector, + metadata_hash: vector, + is_multi_step_proposal: bool, + ): u64 acquires GovernanceConfig, GovernanceEvents { + let proposer_address = signer::address_of(proposer); + assert!( + stake::get_delegated_voter(stake_pool) == proposer_address, + error::invalid_argument(ENOT_DELEGATED_VOTER) + ); + + // The proposer's stake needs to be at least the required bond amount. + let governance_config = borrow_global(@aptos_framework); + let stake_balance = get_voting_power(stake_pool); + assert!( + stake_balance >= governance_config.required_proposer_stake, + error::invalid_argument(EINSUFFICIENT_PROPOSER_STAKE), + ); + + // The proposer's stake needs to be locked up at least as long as the proposal's voting period. + let current_time = timestamp::now_seconds(); + let proposal_expiration = current_time + governance_config.voting_duration_secs; + assert!( + stake::get_lockup_secs(stake_pool) >= proposal_expiration, + error::invalid_argument(EINSUFFICIENT_STAKE_LOCKUP), + ); + + // Create and validate proposal metadata. + let proposal_metadata = create_proposal_metadata(metadata_location, metadata_hash); + + // We want to allow early resolution of proposals if more than 50% of the total supply of the network coins + // has voted. This doesn't take into subsequent inflation/deflation (rewards are issued every epoch and gas fees + // are burnt after every transaction), but inflation/delation is very unlikely to have a major impact on total + // supply during the voting period. + let total_voting_token_supply = coin::supply(); + let early_resolution_vote_threshold = option::none(); + if (option::is_some(&total_voting_token_supply)) { + let total_supply = *option::borrow(&total_voting_token_supply); + // 50% + 1 to avoid rounding errors. + early_resolution_vote_threshold = option::some(total_supply / 2 + 1); + }; + + let proposal_id = voting::create_proposal_v2( + proposer_address, + @aptos_framework, + governance_proposal::create_proposal(), + execution_hash, + governance_config.min_voting_threshold, + proposal_expiration, + early_resolution_vote_threshold, + proposal_metadata, + is_multi_step_proposal, + ); + + if (std::features::module_event_migration_enabled()) { + event::emit( + CreateProposal { + proposal_id, + proposer: proposer_address, + stake_pool, + execution_hash, + proposal_metadata, + }, + ); + }; + let events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut events.create_proposal_events, + CreateProposalEvent { + proposal_id, + proposer: proposer_address, + stake_pool, + execution_hash, + proposal_metadata, + }, + ); + proposal_id + } + + /// Vote on proposal with proposal_id and all voting power from multiple stake_pools. + public entry fun batch_vote( + voter: &signer, + stake_pools: vector
, + proposal_id: u64, + should_pass: bool, + ) acquires ApprovedExecutionHashes, VotingRecords, VotingRecordsV2, GovernanceEvents { + vector::for_each(stake_pools, |stake_pool| { + vote_internal(voter, stake_pool, proposal_id, MAX_U64, should_pass); + }); + } + + /// Batch vote on proposal with proposal_id and specified voting power from multiple stake_pools. + public entry fun batch_partial_vote( + voter: &signer, + stake_pools: vector
, + proposal_id: u64, + voting_power: u64, + should_pass: bool, + ) acquires ApprovedExecutionHashes, VotingRecords, VotingRecordsV2, GovernanceEvents { + vector::for_each(stake_pools, |stake_pool| { + vote_internal(voter, stake_pool, proposal_id, voting_power, should_pass); + }); + } + + /// Vote on proposal with `proposal_id` and all voting power from `stake_pool`. + public entry fun vote( + voter: &signer, + stake_pool: address, + proposal_id: u64, + should_pass: bool, + ) acquires ApprovedExecutionHashes, VotingRecords, VotingRecordsV2, GovernanceEvents { + vote_internal(voter, stake_pool, proposal_id, MAX_U64, should_pass); + } + + /// Vote on proposal with `proposal_id` and specified voting power from `stake_pool`. + public entry fun partial_vote( + voter: &signer, + stake_pool: address, + proposal_id: u64, + voting_power: u64, + should_pass: bool, + ) acquires ApprovedExecutionHashes, VotingRecords, VotingRecordsV2, GovernanceEvents { + vote_internal(voter, stake_pool, proposal_id, voting_power, should_pass); + } + + /// Vote on proposal with `proposal_id` and specified voting_power from `stake_pool`. + /// If voting_power is more than all the left voting power of `stake_pool`, use all the left voting power. + /// If a stake pool has already voted on a proposal before partial governance voting is enabled, the stake pool + /// cannot vote on the proposal even after partial governance voting is enabled. + fun vote_internal( + voter: &signer, + stake_pool: address, + proposal_id: u64, + voting_power: u64, + should_pass: bool, + ) acquires ApprovedExecutionHashes, VotingRecords, VotingRecordsV2, GovernanceEvents { + let voter_address = signer::address_of(voter); + assert!(stake::get_delegated_voter(stake_pool) == voter_address, error::invalid_argument(ENOT_DELEGATED_VOTER)); + + // The voter's stake needs to be locked up at least as long as the proposal's expiration. + let proposal_expiration = voting::get_proposal_expiration_secs( + @aptos_framework, + proposal_id + ); + assert!( + stake::get_lockup_secs(stake_pool) >= proposal_expiration, + error::invalid_argument(EINSUFFICIENT_STAKE_LOCKUP), + ); + + // If a stake pool has already voted on a proposal before partial governance voting is enabled, + // `get_remaining_voting_power` returns 0. + let staking_pool_voting_power = get_remaining_voting_power(stake_pool, proposal_id); + voting_power = min(voting_power, staking_pool_voting_power); + + // Short-circuit if the voter has no voting power. + assert!(voting_power > 0, error::invalid_argument(ENO_VOTING_POWER)); + + voting::vote( + &governance_proposal::create_empty_proposal(), + @aptos_framework, + proposal_id, + voting_power, + should_pass, + ); + + let record_key = RecordKey { + stake_pool, + proposal_id, + }; + if (features::partial_governance_voting_enabled()) { + let voting_records_v2 = borrow_global_mut(@aptos_framework); + let used_voting_power = smart_table::borrow_mut_with_default(&mut voting_records_v2.votes, record_key, 0); + // This calculation should never overflow because the used voting cannot exceed the total voting power of this stake pool. + *used_voting_power = *used_voting_power + voting_power; + } else { + let voting_records = borrow_global_mut(@aptos_framework); + assert!( + !table::contains(&voting_records.votes, record_key), + error::invalid_argument(EALREADY_VOTED)); + table::add(&mut voting_records.votes, record_key, true); + }; + + if (std::features::module_event_migration_enabled()) { + event::emit( + Vote { + proposal_id, + voter: voter_address, + stake_pool, + num_votes: voting_power, + should_pass, + }, + ); + }; + let events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut events.vote_events, + VoteEvent { + proposal_id, + voter: voter_address, + stake_pool, + num_votes: voting_power, + should_pass, + }, + ); + + let proposal_state = voting::get_proposal_state(@aptos_framework, proposal_id); + if (proposal_state == PROPOSAL_STATE_SUCCEEDED) { + add_approved_script_hash(proposal_id); + } + } + + public entry fun add_approved_script_hash_script(proposal_id: u64) acquires ApprovedExecutionHashes { + add_approved_script_hash(proposal_id) + } + + /// Add the execution script hash of a successful governance proposal to the approved list. + /// This is needed to bypass the mempool transaction size limit for approved governance proposal transactions that + /// are too large (e.g. module upgrades). + public fun add_approved_script_hash(proposal_id: u64) acquires ApprovedExecutionHashes { + let approved_hashes = borrow_global_mut(@aptos_framework); + + // Ensure the proposal can be resolved. + let proposal_state = voting::get_proposal_state(@aptos_framework, proposal_id); + assert!(proposal_state == PROPOSAL_STATE_SUCCEEDED, error::invalid_argument(EPROPOSAL_NOT_RESOLVABLE_YET)); + + let execution_hash = voting::get_execution_hash(@aptos_framework, proposal_id); + + // If this is a multi-step proposal, the proposal id will already exist in the ApprovedExecutionHashes map. + // We will update execution hash in ApprovedExecutionHashes to be the next_execution_hash. + if (simple_map::contains_key(&approved_hashes.hashes, &proposal_id)) { + let current_execution_hash = simple_map::borrow_mut(&mut approved_hashes.hashes, &proposal_id); + *current_execution_hash = execution_hash; + } else { + simple_map::add(&mut approved_hashes.hashes, proposal_id, execution_hash); + } + } + + /// Resolve a successful single-step proposal. This would fail if the proposal is not successful (not enough votes or more no + /// than yes). + public fun resolve( + proposal_id: u64, + signer_address: address + ): signer acquires ApprovedExecutionHashes, GovernanceResponsbility { + voting::resolve(@aptos_framework, proposal_id); + remove_approved_hash(proposal_id); + get_signer(signer_address) + } + + /// Resolve a successful multi-step proposal. This would fail if the proposal is not successful. + public fun resolve_multi_step_proposal( + proposal_id: u64, + signer_address: address, + next_execution_hash: vector + ): signer acquires GovernanceResponsbility, ApprovedExecutionHashes { + voting::resolve_proposal_v2(@aptos_framework, proposal_id, next_execution_hash); + // If the current step is the last step of this multi-step proposal, + // we will remove the execution hash from the ApprovedExecutionHashes map. + if (vector::length(&next_execution_hash) == 0) { + remove_approved_hash(proposal_id); + } else { + // If the current step is not the last step of this proposal, + // we replace the current execution hash with the next execution hash + // in the ApprovedExecutionHashes map. + add_approved_script_hash(proposal_id) + }; + get_signer(signer_address) + } + + /// Remove an approved proposal's execution script hash. + public fun remove_approved_hash(proposal_id: u64) acquires ApprovedExecutionHashes { + assert!( + voting::is_resolved(@aptos_framework, proposal_id), + error::invalid_argument(EPROPOSAL_NOT_RESOLVED_YET), + ); + + let approved_hashes = &mut borrow_global_mut(@aptos_framework).hashes; + if (simple_map::contains_key(approved_hashes, &proposal_id)) { + simple_map::remove(approved_hashes, &proposal_id); + }; + } + + /// Manually reconfigure. Called at the end of a governance txn that alters on-chain configs. + /// + /// WARNING: this function always ensures a reconfiguration starts, but when the reconfiguration finishes depends. + /// - If feature `RECONFIGURE_WITH_DKG` is disabled, it finishes immediately. + /// - At the end of the calling transaction, we will be in a new epoch. + /// - If feature `RECONFIGURE_WITH_DKG` is enabled, it starts DKG, and the new epoch will start in a block prologue after DKG finishes. + /// + /// This behavior affects when an update of an on-chain config (e.g. `ConsensusConfig`, `Features`) takes effect, + /// since such updates are applied whenever we enter an new epoch. + public entry fun reconfigure(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + if (consensus_config::validator_txn_enabled() && randomness_config::enabled()) { + reconfiguration_with_dkg::try_start(); + } else { + reconfiguration_with_dkg::finish(aptos_framework); + } + } + + /// Change epoch immediately. + /// If `RECONFIGURE_WITH_DKG` is enabled and we are in the middle of a DKG, + /// stop waiting for DKG and enter the new epoch without randomness. + /// + /// WARNING: currently only used by tests. In most cases you should use `reconfigure()` instead. + /// TODO: migrate these tests to be aware of async reconfiguration. + public entry fun force_end_epoch(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + reconfiguration_with_dkg::finish(aptos_framework); + } + + /// `force_end_epoch()` equivalent but only called in testnet, + /// where the core resources account exists and has been granted power to mint Aptos coins. + public entry fun force_end_epoch_test_only(aptos_framework: &signer) acquires GovernanceResponsbility { + let core_signer = get_signer_testnet_only(aptos_framework, @0x1); + system_addresses::assert_aptos_framework(&core_signer); + reconfiguration_with_dkg::finish(&core_signer); + } + + /// Update feature flags and also trigger reconfiguration. + public fun toggle_features(aptos_framework: &signer, enable: vector, disable: vector) { + system_addresses::assert_aptos_framework(aptos_framework); + features::change_feature_flags_for_next_epoch(aptos_framework, enable, disable); + reconfigure(aptos_framework); + } + + /// Only called in testnet where the core resources account exists and has been granted power to mint Aptos coins. + public fun get_signer_testnet_only( + core_resources: &signer, signer_address: address): signer acquires GovernanceResponsbility { + system_addresses::assert_core_resource(core_resources); + // Core resources account only has mint capability in tests/testnets. + assert!(aptos_coin::has_mint_capability(core_resources), error::unauthenticated(EUNAUTHORIZED)); + get_signer(signer_address) + } + + #[view] + /// Return the voting power a stake pool has with respect to governance proposals. + public fun get_voting_power(pool_address: address): u64 { + let allow_validator_set_change = staking_config::get_allow_validator_set_change(&staking_config::get()); + if (allow_validator_set_change) { + let (active, _, pending_active, pending_inactive) = stake::get_stake(pool_address); + // We calculate the voting power as total non-inactive stakes of the pool. Even if the validator is not in the + // active validator set, as long as they have a lockup (separately checked in create_proposal and voting), their + // stake would still count in their voting power for governance proposals. + active + pending_active + pending_inactive + } else { + stake::get_current_epoch_voting_power(pool_address) + } + } + + /// Return a signer for making changes to 0x1 as part of on-chain governance proposal process. + fun get_signer(signer_address: address): signer acquires GovernanceResponsbility { + let governance_responsibility = borrow_global(@aptos_framework); + let signer_cap = simple_map::borrow(&governance_responsibility.signer_caps, &signer_address); + create_signer_with_capability(signer_cap) + } + + fun create_proposal_metadata( + metadata_location: vector, + metadata_hash: vector + ): SimpleMap> { + assert!(string::length(&utf8(metadata_location)) <= 256, error::invalid_argument(EMETADATA_LOCATION_TOO_LONG)); + assert!(string::length(&utf8(metadata_hash)) <= 256, error::invalid_argument(EMETADATA_HASH_TOO_LONG)); + + let metadata = simple_map::create>(); + simple_map::add(&mut metadata, utf8(METADATA_LOCATION_KEY), metadata_location); + simple_map::add(&mut metadata, utf8(METADATA_HASH_KEY), metadata_hash); + metadata + } + + fun assert_voting_initialization() { + if (features::partial_governance_voting_enabled()) { + assert!(exists(@aptos_framework), error::invalid_state(EPARTIAL_VOTING_NOT_INITIALIZED)); + }; + } + + #[test_only] + public entry fun create_proposal_for_test( + proposer: &signer, + multi_step: bool, + ) acquires GovernanceConfig, GovernanceEvents { + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + if (multi_step) { + create_proposal_v2( + proposer, + signer::address_of(proposer), + execution_hash, + b"", + b"", + true, + ); + } else { + create_proposal( + proposer, + signer::address_of(proposer), + execution_hash, + b"", + b"", + ); + }; + } + + #[test_only] + public fun resolve_proposal_for_test( + proposal_id: u64, + signer_address: address, + multi_step: bool, + finish_multi_step_execution: bool + ): signer acquires ApprovedExecutionHashes, GovernanceResponsbility { + if (multi_step) { + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + + if (finish_multi_step_execution) { + resolve_multi_step_proposal(proposal_id, signer_address, vector::empty()) + } else { + resolve_multi_step_proposal(proposal_id, signer_address, execution_hash) + } + } else { + resolve(proposal_id, signer_address) + } + } + + #[test_only] + /// Force reconfigure. To be called at the end of a proposal that alters on-chain configs. + public fun toggle_features_for_test(enable: vector, disable: vector) { + toggle_features(&account::create_signer_for_test(@0x1), enable, disable); + } + + #[test_only] + public entry fun test_voting_generic( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + multi_step: bool, + use_generic_resolve_function: bool, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + setup_voting(&aptos_framework, &proposer, &yes_voter, &no_voter); + + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + + create_proposal_for_test(&proposer, multi_step); + + vote(&yes_voter, signer::address_of(&yes_voter), 0, true); + vote(&no_voter, signer::address_of(&no_voter), 0, false); + + test_resolving_proposal_generic(aptos_framework, use_generic_resolve_function, execution_hash); + } + + #[test_only] + public entry fun test_resolving_proposal_generic( + aptos_framework: signer, + use_generic_resolve_function: bool, + execution_hash: vector, + ) acquires ApprovedExecutionHashes, GovernanceResponsbility { + // Once expiration time has passed, the proposal should be considered resolve now as there are more yes votes + // than no. + timestamp::update_global_time_for_test(100001000000); + let proposal_state = voting::get_proposal_state(signer::address_of(&aptos_framework), 0); + assert!(proposal_state == PROPOSAL_STATE_SUCCEEDED, proposal_state); + + // Add approved script hash. + add_approved_script_hash(0); + let approved_hashes = borrow_global(@aptos_framework).hashes; + assert!(*simple_map::borrow(&approved_hashes, &0) == execution_hash, 0); + + // Resolve the proposal. + let account = resolve_proposal_for_test(0, @aptos_framework, use_generic_resolve_function, true); + assert!(signer::address_of(&account) == @aptos_framework, 1); + assert!(voting::is_resolved(@aptos_framework, 0), 2); + let approved_hashes = borrow_global(@aptos_framework).hashes; + assert!(!simple_map::contains_key(&approved_hashes, &0), 3); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, yes_voter = @0x234, no_voter = @345)] + public entry fun test_voting( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + test_voting_generic(aptos_framework, proposer, yes_voter, no_voter, false, false); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, yes_voter = @0x234, no_voter = @345)] + public entry fun test_voting_multi_step( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + test_voting_generic(aptos_framework, proposer, yes_voter, no_voter, true, true); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, yes_voter = @0x234, no_voter = @345)] + #[expected_failure(abort_code = 0x5000a, location = aptos_framework::voting)] + public entry fun test_voting_multi_step_cannot_use_single_step_resolve( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + test_voting_generic(aptos_framework, proposer, yes_voter, no_voter, true, false); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, yes_voter = @0x234, no_voter = @345)] + public entry fun test_voting_single_step_can_use_generic_resolve_function( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + test_voting_generic(aptos_framework, proposer, yes_voter, no_voter, false, true); + } + + #[test_only] + public entry fun test_can_remove_approved_hash_if_executed_directly_via_voting_generic( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + multi_step: bool, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + setup_voting(&aptos_framework, &proposer, &yes_voter, &no_voter); + + create_proposal_for_test(&proposer, multi_step); + vote(&yes_voter, signer::address_of(&yes_voter), 0, true); + vote(&no_voter, signer::address_of(&no_voter), 0, false); + + // Add approved script hash. + timestamp::update_global_time_for_test(100001000000); + add_approved_script_hash(0); + + // Resolve the proposal. + if (multi_step) { + let execution_hash = vector::empty(); + let next_execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + voting::resolve_proposal_v2(@aptos_framework, 0, next_execution_hash); + assert!(voting::is_resolved(@aptos_framework, 0), 0); + if (vector::length(&next_execution_hash) == 0) { + remove_approved_hash(0); + } else { + add_approved_script_hash(0) + }; + } else { + voting::resolve(@aptos_framework, 0); + assert!(voting::is_resolved(@aptos_framework, 0), 0); + remove_approved_hash(0); + }; + let approved_hashes = borrow_global(@aptos_framework).hashes; + assert!(!simple_map::contains_key(&approved_hashes, &0), 1); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, yes_voter = @0x234, no_voter = @345)] + public entry fun test_can_remove_approved_hash_if_executed_directly_via_voting( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + test_can_remove_approved_hash_if_executed_directly_via_voting_generic( + aptos_framework, + proposer, + yes_voter, + no_voter, + false + ); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, yes_voter = @0x234, no_voter = @345)] + public entry fun test_can_remove_approved_hash_if_executed_directly_via_voting_multi_step( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + test_can_remove_approved_hash_if_executed_directly_via_voting_generic( + aptos_framework, + proposer, + yes_voter, + no_voter, + true + ); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + #[expected_failure(abort_code = 0x10004, location = aptos_framework::voting)] + public entry fun test_cannot_double_vote( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + setup_voting(&aptos_framework, &proposer, &voter_1, &voter_2); + + create_proposal( + &proposer, + signer::address_of(&proposer), + b"", + b"", + b"", + ); + + // Double voting should throw an error. + vote(&voter_1, signer::address_of(&voter_1), 0, true); + vote(&voter_1, signer::address_of(&voter_1), 0, true); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + #[expected_failure(abort_code = 0x10004, location = aptos_framework::voting)] + public entry fun test_cannot_double_vote_with_different_voter_addresses( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + setup_voting(&aptos_framework, &proposer, &voter_1, &voter_2); + + create_proposal( + &proposer, + signer::address_of(&proposer), + b"", + b"", + b"", + ); + + // Double voting should throw an error for 2 different voters if they still use the same stake pool. + vote(&voter_1, signer::address_of(&voter_1), 0, true); + stake::set_delegated_voter(&voter_1, signer::address_of(&voter_2)); + vote(&voter_2, signer::address_of(&voter_1), 0, true); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + public entry fun test_stake_pool_can_vote_on_partial_voting_proposal_many_times( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + setup_partial_voting(&aptos_framework, &proposer, &voter_1, &voter_2); + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let proposer_addr = signer::address_of(&proposer); + let voter_1_addr = signer::address_of(&voter_1); + let voter_2_addr = signer::address_of(&voter_2); + + create_proposal_for_test(&proposer, true); + + partial_vote(&voter_1, voter_1_addr, 0, 5, true); + partial_vote(&voter_1, voter_1_addr, 0, 3, true); + partial_vote(&voter_1, voter_1_addr, 0, 2, true); + + assert!(get_remaining_voting_power(proposer_addr, 0) == 100, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 10, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 10, 2); + + test_resolving_proposal_generic(aptos_framework, true, execution_hash); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + #[expected_failure(abort_code = 0x3, location = Self)] + public entry fun test_stake_pool_can_vote_with_partial_voting_power( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + setup_partial_voting(&aptos_framework, &proposer, &voter_1, &voter_2); + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let proposer_addr = signer::address_of(&proposer); + let voter_1_addr = signer::address_of(&voter_1); + let voter_2_addr = signer::address_of(&voter_2); + + create_proposal_for_test(&proposer, true); + + partial_vote(&voter_1, voter_1_addr, 0, 9, true); + + assert!(get_remaining_voting_power(proposer_addr, 0) == 100, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 11, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 10, 2); + + // No enough Yes. The proposal cannot be resolved. + test_resolving_proposal_generic(aptos_framework, true, execution_hash); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + public entry fun test_batch_vote( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + features::change_feature_flags_for_testing(&aptos_framework, vector[features::get_coin_to_fungible_asset_migration_feature()], vector[]); + setup_partial_voting(&aptos_framework, &proposer, &voter_1, &voter_2); + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let voter_1_addr = signer::address_of(&voter_1); + let voter_2_addr = signer::address_of(&voter_2); + stake::set_delegated_voter(&voter_2, voter_1_addr); + create_proposal_for_test(&proposer, true); + batch_vote(&voter_1, vector[voter_1_addr, voter_2_addr], 0, true); + test_resolving_proposal_generic(aptos_framework, true, execution_hash); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + public entry fun test_batch_partial_vote( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + features::change_feature_flags_for_testing(&aptos_framework, vector[features::get_coin_to_fungible_asset_migration_feature()], vector[]); + setup_partial_voting(&aptos_framework, &proposer, &voter_1, &voter_2); + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let voter_1_addr = signer::address_of(&voter_1); + let voter_2_addr = signer::address_of(&voter_2); + stake::set_delegated_voter(&voter_2, voter_1_addr); + create_proposal_for_test(&proposer, true); + batch_partial_vote(&voter_1, vector[voter_1_addr, voter_2_addr], 0, 9, true); + test_resolving_proposal_generic(aptos_framework, true, execution_hash); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + public entry fun test_stake_pool_can_vote_only_with_its_own_voting_power( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + setup_partial_voting(&aptos_framework, &proposer, &voter_1, &voter_2); + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let proposer_addr = signer::address_of(&proposer); + let voter_1_addr = signer::address_of(&voter_1); + let voter_2_addr = signer::address_of(&voter_2); + + create_proposal_for_test(&proposer, true); + + partial_vote(&voter_1, voter_1_addr, 0, 9, true); + // The total voting power of voter_1 is 20. It can only vote with 20 voting power even we pass 30 as the argument. + partial_vote(&voter_1, voter_1_addr, 0, 30, true); + + assert!(get_remaining_voting_power(proposer_addr, 0) == 100, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 0, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 10, 2); + + test_resolving_proposal_generic(aptos_framework, true, execution_hash); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + public entry fun test_stake_pool_can_vote_before_and_after_partial_governance_voting_enabled( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires ApprovedExecutionHashes, GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + setup_voting(&aptos_framework, &proposer, &voter_1, &voter_2); + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let proposer_addr = signer::address_of(&proposer); + let voter_1_addr = signer::address_of(&voter_1); + let voter_2_addr = signer::address_of(&voter_2); + + create_proposal_for_test(&proposer, true); + vote(&voter_1, voter_1_addr, 0, true); + assert!(get_remaining_voting_power(proposer_addr, 0) == 100, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 0, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 10, 2); + + initialize_partial_voting(&aptos_framework); + features::change_feature_flags_for_testing(&aptos_framework, vector[features::get_partial_governance_voting()], vector[]); + + coin::register(&voter_1); + coin::register(&voter_2); + stake::add_stake(&voter_1, 20); + stake::add_stake(&voter_2, 5); + + // voter1 has already voted before partial governance voting is enalbed. So it cannot vote even after adding stake. + // voter2's voting poewr increase after adding stake. + assert!(get_remaining_voting_power(proposer_addr, 0) == 100, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 0, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 15, 2); + + test_resolving_proposal_generic(aptos_framework, true, execution_hash); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, voter_1 = @0x234, voter_2 = @345)] + public entry fun test_no_remaining_voting_power_about_proposal_expiration_time( + aptos_framework: signer, + proposer: signer, + voter_1: signer, + voter_2: signer, + ) acquires GovernanceConfig, GovernanceResponsbility, VotingRecords, VotingRecordsV2, GovernanceEvents { + setup_voting_with_initialized_stake(&aptos_framework, &proposer, &voter_1, &voter_2); + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let proposer_addr = signer::address_of(&proposer); + let voter_1_addr = signer::address_of(&voter_1); + let voter_2_addr = signer::address_of(&voter_2); + + create_proposal_for_test(&proposer, true); + assert!(get_remaining_voting_power(proposer_addr, 0) == 100, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 0, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 0, 2); + + // 500 seconds later, lockup period of voter_1 and voter_2 is reset. + timestamp::fast_forward_seconds(440); + stake::end_epoch(); + assert!(get_remaining_voting_power(proposer_addr, 0) == 100, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 20, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 10, 2); + + // 501 seconds later, the proposal expires. + timestamp::fast_forward_seconds(441); + stake::end_epoch(); + assert!(get_remaining_voting_power(proposer_addr, 0) == 0, 0); + assert!(get_remaining_voting_power(voter_1_addr, 0) == 0, 1); + assert!(get_remaining_voting_power(voter_2_addr, 0) == 0, 2); + } + + #[test_only] + public fun setup_voting( + aptos_framework: &signer, + proposer: &signer, + yes_voter: &signer, + no_voter: &signer, + ) acquires GovernanceResponsbility { + use std::vector; + use aptos_framework::account; + use aptos_framework::coin; + use aptos_framework::aptos_coin::{Self, AptosCoin}; + + timestamp::set_time_has_started_for_testing(aptos_framework); + account::create_account_for_test(signer::address_of(aptos_framework)); + account::create_account_for_test(signer::address_of(proposer)); + account::create_account_for_test(signer::address_of(yes_voter)); + account::create_account_for_test(signer::address_of(no_voter)); + + // Initialize the governance. + staking_config::initialize_for_test(aptos_framework, 0, 1000, 2000, true, 0, 1, 100); + initialize(aptos_framework, 10, 100, 1000); + store_signer_cap( + aptos_framework, + @aptos_framework, + account::create_test_signer_cap(@aptos_framework), + ); + + // Initialize the stake pools for proposer and voters. + let active_validators = vector::empty
(); + vector::push_back(&mut active_validators, signer::address_of(proposer)); + vector::push_back(&mut active_validators, signer::address_of(yes_voter)); + vector::push_back(&mut active_validators, signer::address_of(no_voter)); + let (_sk_1, pk_1, _pop_1) = stake::generate_identity(); + let (_sk_2, pk_2, _pop_2) = stake::generate_identity(); + let (_sk_3, pk_3, _pop_3) = stake::generate_identity(); + let pks = vector[pk_1, pk_2, pk_3]; + stake::create_validator_set(aptos_framework, active_validators, pks); + + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(aptos_framework); + // Spread stake among active and pending_inactive because both need to be accounted for when computing voting + // power. + coin::register(proposer); + coin::deposit(signer::address_of(proposer), coin::mint(100, &mint_cap)); + coin::register(yes_voter); + coin::deposit(signer::address_of(yes_voter), coin::mint(20, &mint_cap)); + coin::register(no_voter); + coin::deposit(signer::address_of(no_voter), coin::mint(10, &mint_cap)); + stake::create_stake_pool(proposer, coin::mint(50, &mint_cap), coin::mint(50, &mint_cap), 10000); + stake::create_stake_pool(yes_voter, coin::mint(10, &mint_cap), coin::mint(10, &mint_cap), 10000); + stake::create_stake_pool(no_voter, coin::mint(5, &mint_cap), coin::mint(5, &mint_cap), 10000); + coin::destroy_mint_cap(mint_cap); + coin::destroy_burn_cap(burn_cap); + } + + #[test_only] + public fun setup_voting_with_initialized_stake( + aptos_framework: &signer, + proposer: &signer, + yes_voter: &signer, + no_voter: &signer, + ) acquires GovernanceResponsbility { + use aptos_framework::account; + use aptos_framework::coin; + use aptos_framework::aptos_coin::AptosCoin; + + timestamp::set_time_has_started_for_testing(aptos_framework); + account::create_account_for_test(signer::address_of(aptos_framework)); + account::create_account_for_test(signer::address_of(proposer)); + account::create_account_for_test(signer::address_of(yes_voter)); + account::create_account_for_test(signer::address_of(no_voter)); + + // Initialize the governance. + stake::initialize_for_test_custom(aptos_framework, 0, 1000, 2000, true, 0, 1, 1000); + initialize(aptos_framework, 10, 100, 1000); + store_signer_cap( + aptos_framework, + @aptos_framework, + account::create_test_signer_cap(@aptos_framework), + ); + + // Initialize the stake pools for proposer and voters. + // Spread stake among active and pending_inactive because both need to be accounted for when computing voting + // power. + coin::register(proposer); + coin::deposit(signer::address_of(proposer), stake::mint_coins(100)); + coin::register(yes_voter); + coin::deposit(signer::address_of(yes_voter), stake::mint_coins(20)); + coin::register(no_voter); + coin::deposit(signer::address_of(no_voter), stake::mint_coins(10)); + + let (_sk_1, pk_1, pop_1) = stake::generate_identity(); + let (_sk_2, pk_2, pop_2) = stake::generate_identity(); + let (_sk_3, pk_3, pop_3) = stake::generate_identity(); + stake::initialize_test_validator(&pk_2, &pop_2, yes_voter, 20, true, false); + stake::initialize_test_validator(&pk_3, &pop_3, no_voter, 10, true, false); + stake::end_epoch(); + timestamp::fast_forward_seconds(1440); + stake::initialize_test_validator(&pk_1, &pop_1, proposer, 100, true, false); + stake::end_epoch(); + } + + #[test_only] + public fun setup_partial_voting( + aptos_framework: &signer, + proposer: &signer, + voter_1: &signer, + voter_2: &signer, + ) acquires GovernanceResponsbility { + initialize_partial_voting(aptos_framework); + features::change_feature_flags_for_testing(aptos_framework, vector[features::get_partial_governance_voting()], vector[]); + setup_voting(aptos_framework, proposer, voter_1, voter_2); + } + + #[test(aptos_framework = @aptos_framework)] + public entry fun test_update_governance_config( + aptos_framework: signer, + ) acquires GovernanceConfig, GovernanceEvents { + account::create_account_for_test(signer::address_of(&aptos_framework)); + initialize(&aptos_framework, 1, 2, 3); + update_governance_config(&aptos_framework, 10, 20, 30); + + let config = borrow_global(@aptos_framework); + assert!(config.min_voting_threshold == 10, 0); + assert!(config.required_proposer_stake == 20, 1); + assert!(config.voting_duration_secs == 30, 3); + } + + #[test(account = @0x123)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + public entry fun test_update_governance_config_unauthorized_should_fail( + account: signer) acquires GovernanceConfig, GovernanceEvents { + initialize(&account, 1, 2, 3); + update_governance_config(&account, 10, 20, 30); + } + + #[test(aptos_framework = @aptos_framework, proposer = @0x123, yes_voter = @0x234, no_voter = @345)] + public entry fun test_replace_execution_hash( + aptos_framework: signer, + proposer: signer, + yes_voter: signer, + no_voter: signer, + ) acquires GovernanceResponsbility, GovernanceConfig, ApprovedExecutionHashes, VotingRecords, VotingRecordsV2, GovernanceEvents { + setup_voting(&aptos_framework, &proposer, &yes_voter, &no_voter); + + create_proposal_for_test(&proposer, true); + vote(&yes_voter, signer::address_of(&yes_voter), 0, true); + vote(&no_voter, signer::address_of(&no_voter), 0, false); + + // Add approved script hash. + timestamp::update_global_time_for_test(100001000000); + add_approved_script_hash(0); + + // Resolve the proposal. + let execution_hash = vector::empty(); + let next_execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + vector::push_back(&mut next_execution_hash, 10); + + voting::resolve_proposal_v2(@aptos_framework, 0, next_execution_hash); + + if (vector::length(&next_execution_hash) == 0) { + remove_approved_hash(0); + } else { + add_approved_script_hash(0) + }; + + let approved_hashes = borrow_global(@aptos_framework).hashes; + assert!(*simple_map::borrow(&approved_hashes, &0) == vector[10u8, ], 1); + } + + #[test_only] + public fun initialize_for_test( + aptos_framework: &signer, + min_voting_threshold: u128, + required_proposer_stake: u64, + voting_duration_secs: u64, + ) { + initialize(aptos_framework, min_voting_threshold, required_proposer_stake, voting_duration_secs); + } + + #[verify_only] + public fun initialize_for_verification( + aptos_framework: &signer, + min_voting_threshold: u128, + required_proposer_stake: u64, + voting_duration_secs: u64, + ) { + initialize(aptos_framework, min_voting_threshold, required_proposer_stake, voting_duration_secs); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/atomic_bridge.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/atomic_bridge.move new file mode 100644 index 000000000..ff1d9851a --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/atomic_bridge.move @@ -0,0 +1,1523 @@ +module aptos_framework::atomic_bridge_initiator { + use aptos_framework::account; + use aptos_framework::atomic_bridge; + use aptos_framework::atomic_bridge_configuration; + use aptos_framework::atomic_bridge_configuration::assert_is_caller_operator; + use aptos_framework::atomic_bridge_store; + use aptos_framework::atomic_bridge_store::{create_hashlock, bridge_transfer_id}; + use aptos_framework::ethereum; + use aptos_framework::ethereum::EthereumAddress; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::signer; + #[test_only] + use std::vector; + #[test_only] + use aptos_framework::aptos_account; + #[test_only] + use aptos_framework::aptos_coin::AptosCoin; + #[test_only] + use aptos_framework::atomic_bridge_store::{valid_hash_lock, assert_valid_bridge_transfer_id, plain_secret}; + #[test_only] + use aptos_framework::coin; + #[test_only] + use aptos_framework::ethereum::valid_eip55; + #[test_only] + use aptos_framework::timestamp; + + #[event] + struct BridgeTransferInitiatedEvent has store, drop { + bridge_transfer_id: vector, + initiator: address, + recipient: vector, + amount: u64, + hash_lock: vector, + time_lock: u64, + } + + #[event] + struct BridgeTransferCompletedEvent has store, drop { + bridge_transfer_id: vector, + pre_image: vector, + } + + #[event] + struct BridgeTransferRefundedEvent has store, drop { + bridge_transfer_id: vector, + } + + /// This struct will store the event handles for bridge events. + struct BridgeInitiatorEvents has key, store { + bridge_transfer_initiated_events: EventHandle, + bridge_transfer_completed_events: EventHandle, + bridge_transfer_refunded_events: EventHandle, + } + + /// Initializes the module and stores the `EventHandle`s in the resource. + public fun initialize(aptos_framework: &signer) { + move_to(aptos_framework, BridgeInitiatorEvents { + bridge_transfer_initiated_events: account::new_event_handle(aptos_framework), + bridge_transfer_completed_events: account::new_event_handle(aptos_framework), + bridge_transfer_refunded_events: account::new_event_handle(aptos_framework), + }); + } + + /// Initiate a bridge transfer of ETH from Movement to the base layer + /// Anyone can initiate a bridge transfer from the source chain + /// The amount is burnt from the initiator + public entry fun initiate_bridge_transfer( + initiator: &signer, + recipient: vector, + hash_lock: vector, + amount: u64 + ) acquires BridgeInitiatorEvents { + let ethereum_address = ethereum::ethereum_address_no_eip55(recipient); + let initiator_address = signer::address_of(initiator); + let time_lock = atomic_bridge_configuration::initiator_timelock_duration(); + + let details = + atomic_bridge_store::create_details( + initiator_address, + ethereum_address, amount, + hash_lock, + time_lock + ); + + let bridge_transfer_id = bridge_transfer_id(&details); + atomic_bridge_store::add(bridge_transfer_id, details); + atomic_bridge::burn(initiator_address, amount); + + let bridge_initiator_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_initiator_events.bridge_transfer_initiated_events, + BridgeTransferInitiatedEvent { + bridge_transfer_id, + initiator: initiator_address, + recipient, + amount, + hash_lock, + time_lock + }, + ); + } + + /// Bridge operator can complete the transfer + public entry fun complete_bridge_transfer ( + caller: &signer, + bridge_transfer_id: vector, + pre_image: vector, + ) acquires BridgeInitiatorEvents { + assert_is_caller_operator(caller); + let (_, _) = atomic_bridge_store::complete_transfer(bridge_transfer_id, create_hashlock(pre_image)); + + let bridge_initiator_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_initiator_events.bridge_transfer_completed_events, + BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image, + }, + ); + } + + /// Anyone can refund the transfer on the source chain once time lock has passed + public entry fun refund_bridge_transfer ( + _caller: &signer, + bridge_transfer_id: vector, + ) acquires BridgeInitiatorEvents { + let (receiver, amount) = atomic_bridge_store::cancel_transfer(bridge_transfer_id); + atomic_bridge::mint(receiver, amount); + + let bridge_initiator_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_initiator_events.bridge_transfer_refunded_events, + BridgeTransferRefundedEvent { + bridge_transfer_id, + }, + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + fun test_initiate_bridge_transfer( + sender: &signer, + aptos_framework: &signer, + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + initialize(aptos_framework); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let time_lock = atomic_bridge_configuration::initiator_timelock_duration(); + let amount = 1000; + + // Mint some coins + atomic_bridge::mint(sender_address, amount + 1); + + assert!(coin::balance(sender_address) == amount + 1, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + assert!(coin::balance(sender_address) == 1, 0); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + assert_valid_bridge_transfer_id(&bridge_transfer_initiated_event.bridge_transfer_id); + assert!(bridge_transfer_initiated_event.recipient == recipient, 0); + assert!(bridge_transfer_initiated_event.amount == amount, 0); + assert!(bridge_transfer_initiated_event.initiator == sender_address, 0); + assert!(bridge_transfer_initiated_event.hash_lock == hash_lock, 0); + assert!(bridge_transfer_initiated_event.time_lock == time_lock, 0); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x10006, location = 0x1::coin)] //EINSUFFICIENT_BALANCE + fun test_initiate_bridge_transfer_insufficient_balance( + sender: &signer, + aptos_framework: &signer, + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + fun test_complete_bridge_transfer( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + let account_balance = amount + 1; + + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + plain_secret(), + ); + + let bridge_initiator_events = borrow_global(signer::address_of(aptos_framework)); + let complete_events = event::emitted_events_by_handle(&bridge_initiator_events.bridge_transfer_completed_events); + let expected_event = BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image: plain_secret(), + }; + assert!(std::vector::contains(&complete_events, &expected_event), 0); + + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x1, location = 0x1::atomic_bridge_configuration)] // EINVALID_BRIDGE_OPERATOR + fun test_complete_bridge_transfer_by_sender( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + let account_balance = amount + 1; + + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + complete_bridge_transfer( + sender, + bridge_transfer_id, + plain_secret(), + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x1, location = 0x1::atomic_bridge_store)] // EINVALID_PRE_IMAGE + fun test_complete_bridge_transfer_with_invalid_preimage( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + let account_balance = amount + 1; + + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + b"bad secret", + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x10001, location = 0x1::smart_table)] // ENOT_FOUND + fun test_complete_bridge_with_errorneous_bridge_id_by_operator( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + + let bridge_transfer_id = b"guessing the id"; + + // As operator I send a complete request and it should fail + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + plain_secret(), + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + fun test_refund_bridge_transfer( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + let account_balance = amount + 1; + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + assert!(coin::balance(sender_address) == account_balance - amount, 0); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + timestamp::fast_forward_seconds(atomic_bridge_configuration::initiator_timelock_duration() + 1); + + refund_bridge_transfer(sender, bridge_transfer_id); + + assert!(coin::balance(sender_address) == account_balance, 0); + + let bridge_initiator_events = borrow_global(signer::address_of(aptos_framework)); + let refund_events = event::emitted_events_by_handle(&bridge_initiator_events.bridge_transfer_refunded_events); + let expected_event = BridgeTransferRefundedEvent { bridge_transfer_id }; + let was_event_emitted = std::vector::contains(&refund_events, &expected_event); + + assert!(was_event_emitted, 0); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x4, location = 0x1::atomic_bridge_store)] //ENOT_EXPIRED + fun test_refund_bridge_transfer_before_timelock( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + let account_balance = amount + 1; + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + assert!(coin::balance(sender_address) == account_balance - amount, 0); + + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + refund_bridge_transfer(sender, bridge_transfer_id); + } +} + +module aptos_framework::atomic_bridge_store { + use std::bcs; + use std::features; + use std::vector; + use aptos_std::aptos_hash::keccak256; + use aptos_std::smart_table; + use aptos_std::smart_table::SmartTable; + use aptos_framework::ethereum::EthereumAddress; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + use std::signer; + use aptos_framework::timestamp::CurrentTimeMicroseconds; + + friend aptos_framework::atomic_bridge_counterparty; + friend aptos_framework::atomic_bridge_initiator; + + #[test_only] + use std::hash::sha3_256; + #[test_only] + use aptos_framework::ethereum; + #[test_only] + use aptos_framework::atomic_bridge_configuration; + + /// Error codes + const EINVALID_PRE_IMAGE : u64 = 0x1; + const ENOT_PENDING_TRANSACTION : u64 = 0x2; + const EEXPIRED : u64 = 0x3; + const ENOT_EXPIRED : u64 = 0x4; + const EINVALID_HASH_LOCK : u64 = 0x5; + const EINVALID_TIME_LOCK : u64 = 0x6; + const EZERO_AMOUNT : u64 = 0x7; + const EINVALID_BRIDGE_TRANSFER_ID : u64 = 0x8; + const EATOMIC_BRIDGE_NOT_ENABLED : u64 = 0x9; + + /// Transaction states + const PENDING_TRANSACTION: u8 = 0x1; + const COMPLETED_TRANSACTION: u8 = 0x2; + const CANCELLED_TRANSACTION: u8 = 0x3; + + /// Minimum time lock of 1 second + const MIN_TIME_LOCK : u64 = 1; + const MAX_U64 : u64 = 0xFFFFFFFFFFFFFFFF; + + struct AddressPair has store, copy { + initiator: Initiator, + recipient: Recipient, + } + + /// A smart table wrapper + struct SmartTableWrapper has key, store { + inner: SmartTable, + } + + /// Details on the transfer + struct BridgeTransferDetails has store, copy { + addresses: AddressPair, + amount: u64, + hash_lock: vector, + time_lock: u64, + state: u8, + } + + struct Nonce has key { + inner: u64 + } + + /// Initializes the initiators and counterparties tables and nonce. + /// + /// @param aptos_framework The signer for Aptos framework. + public fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, Nonce { + inner: 0, + }); + + let initiators = SmartTableWrapper, BridgeTransferDetails> { + inner: smart_table::new(), + }; + + move_to(aptos_framework, initiators); + + let counterparties = SmartTableWrapper, BridgeTransferDetails> { + inner: smart_table::new(), + }; + + move_to(aptos_framework, counterparties); + } + + /// Returns the current time in seconds. + /// + /// @return Current timestamp in seconds. + fun now() : u64 { + timestamp::now_seconds() + } + + /// Creates a time lock by adding a duration to the current time. + /// + /// @param lock The duration to lock. + /// @return The calculated time lock. + /// @abort If lock is not above MIN_TIME_LOCK + public(friend) fun create_time_lock(time_lock: u64) : u64 { + assert_min_time_lock(time_lock); + now() + time_lock + } + + /// Creates bridge transfer details with validation. + /// + /// @param initiator The initiating party of the transfer. + /// @param recipient The receiving party of the transfer. + /// @param amount The amount to be transferred. + /// @param hash_lock The hash lock for the transfer. + /// @param time_lock The time lock for the transfer. + /// @return A `BridgeTransferDetails` object. + /// @abort If the amount is zero or locks are invalid. + public(friend) fun create_details(initiator: Initiator, recipient: Recipient, amount: u64, hash_lock: vector, time_lock: u64) + : BridgeTransferDetails { + assert!(amount > 0, EZERO_AMOUNT); + assert_valid_hash_lock(&hash_lock); + time_lock = create_time_lock(time_lock); + + BridgeTransferDetails { + addresses: AddressPair { + initiator, + recipient + }, + amount, + hash_lock, + time_lock, + state: PENDING_TRANSACTION, + } + } + + /// Record details of a transfer + /// + /// @param bridge_transfer_id Bridge transfer ID. + /// @param details The bridge transfer details + public(friend) fun add(bridge_transfer_id: vector, details: BridgeTransferDetails) acquires SmartTableWrapper { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + assert_valid_bridge_transfer_id(&bridge_transfer_id); + let table = borrow_global_mut, BridgeTransferDetails>>(@aptos_framework); + smart_table::add(&mut table.inner, bridge_transfer_id, details); + } + + /// Asserts that the time lock is valid. + /// + /// @param time_lock + /// @abort If the time lock is invalid. + fun assert_min_time_lock(time_lock: u64) { + assert!(time_lock >= MIN_TIME_LOCK, EINVALID_TIME_LOCK); + } + + /// Asserts that the details state is pending. + /// + /// @param details The bridge transfer details to check. + /// @abort If the state is not pending. + fun assert_pending(details: &BridgeTransferDetails) { + assert!(details.state == PENDING_TRANSACTION, ENOT_PENDING_TRANSACTION) + } + + /// Asserts that the hash lock is valid. + /// + /// @param hash_lock The hash lock to validate. + /// @abort If the hash lock is invalid. + fun assert_valid_hash_lock(hash_lock: &vector) { + assert!(vector::length(hash_lock) == 32, EINVALID_HASH_LOCK); + } + + /// Asserts that the bridge transfer ID is valid. + /// + /// @param bridge_transfer_id The bridge transfer ID to validate. + /// @abort If the ID is invalid. + public(friend) fun assert_valid_bridge_transfer_id(bridge_transfer_id: &vector) { + assert!(vector::length(bridge_transfer_id) == 32, EINVALID_BRIDGE_TRANSFER_ID); + } + + /// Creates a hash lock from a pre-image. + /// + /// @param pre_image The pre-image to hash. + /// @return The generated hash lock. + public(friend) fun create_hashlock(pre_image: vector) : vector { + assert!(vector::length(&pre_image) > 0, EINVALID_PRE_IMAGE); + keccak256(pre_image) + } + + /// Asserts that the hash lock matches the expected value. + /// + /// @param details The bridge transfer details. + /// @param hash_lock The hash lock to compare. + /// @abort If the hash lock is incorrect. + fun assert_correct_hash_lock(details: &BridgeTransferDetails, hash_lock: vector) { + assert!(&hash_lock == &details.hash_lock, EINVALID_PRE_IMAGE); + } + + /// Asserts that the time lock has expired. + /// + /// @param details The bridge transfer details. + /// @abort If the time lock has not expired. + fun assert_timed_out_lock(details: &BridgeTransferDetails) { + assert!(now() > details.time_lock, ENOT_EXPIRED); + } + + /// Asserts we are still within the timelock. + /// + /// @param details The bridge transfer details. + /// @abort If the time lock has expired. + fun assert_within_timelock(details: &BridgeTransferDetails) { + assert!(!(now() > details.time_lock), EEXPIRED); + } + + /// Completes the bridge transfer. + /// + /// @param details The bridge transfer details to complete. + fun complete(details: &mut BridgeTransferDetails) { + details.state = COMPLETED_TRANSACTION; + } + + /// Cancels the bridge transfer. + /// + /// @param details The bridge transfer details to cancel. + fun cancel(details: &mut BridgeTransferDetails) { + details.state = CANCELLED_TRANSACTION; + } + + /// Validates and completes a bridge transfer by confirming the hash lock and state. + /// + /// @param hash_lock The hash lock used to validate the transfer. + /// @param details The mutable reference to the bridge transfer details to be completed. + /// @return A tuple containing the recipient and the amount of the transfer. + /// @abort If the hash lock is invalid, the transfer is not pending, or the hash lock does not match. + fun complete_details(hash_lock: vector, details: &mut BridgeTransferDetails) : (Recipient, u64) { + assert_valid_hash_lock(&hash_lock); + assert_pending(details); + assert_correct_hash_lock(details, hash_lock); + assert_within_timelock(details); + + complete(details); + + (details.addresses.recipient, details.amount) + } + + /// Completes a bridge transfer by validating the hash lock and updating the transfer state. + /// + /// @param bridge_transfer_id The ID of the bridge transfer to complete. + /// @param hash_lock The hash lock used to validate the transfer. + /// @return A tuple containing the recipient of the transfer and the amount transferred. + /// @abort If the bridge transfer details are not found or if the completion checks in `complete_details` fail. + public(friend) fun complete_transfer(bridge_transfer_id: vector, hash_lock: vector) : (Recipient, u64) acquires SmartTableWrapper { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + let table = borrow_global_mut, BridgeTransferDetails>>(@aptos_framework); + + let details = smart_table::borrow_mut( + &mut table.inner, + bridge_transfer_id); + + complete_details(hash_lock, details) + } + + /// Cancels a pending bridge transfer if the time lock has expired. + /// + /// @param details A mutable reference to the bridge transfer details to be canceled. + /// @return A tuple containing the initiator of the transfer and the amount to be refunded. + /// @abort If the transfer is not in a pending state or the time lock has not expired. + fun cancel_details(details: &mut BridgeTransferDetails) : (Initiator, u64) { + assert_pending(details); + assert_timed_out_lock(details); + + cancel(details); + + (details.addresses.initiator, details.amount) + } + + /// Cancels a bridge transfer if it is pending and the time lock has expired. + /// + /// @param bridge_transfer_id The ID of the bridge transfer to cancel. + /// @return A tuple containing the initiator of the transfer and the amount to be refunded. + /// @abort If the bridge transfer details are not found or if the cancellation conditions in `cancel_details` fail. + public(friend) fun cancel_transfer(bridge_transfer_id: vector) : (Initiator, u64) acquires SmartTableWrapper { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + let table = borrow_global_mut, BridgeTransferDetails>>(@aptos_framework); + + let details = smart_table::borrow_mut( + &mut table.inner, + bridge_transfer_id); + + cancel_details(details) + } + + /// Generates a unique bridge transfer ID based on transfer details and nonce. + /// + /// @param details The bridge transfer details. + /// @return The generated bridge transfer ID. + public(friend) fun bridge_transfer_id(details: &BridgeTransferDetails) : vector acquires Nonce { + let nonce = borrow_global_mut(@aptos_framework); + let combined_bytes = vector::empty(); + vector::append(&mut combined_bytes, bcs::to_bytes(&details.addresses.initiator)); + vector::append(&mut combined_bytes, bcs::to_bytes(&details.addresses.recipient)); + vector::append(&mut combined_bytes, details.hash_lock); + if (nonce.inner == MAX_U64) { + nonce.inner = 0; // Wrap around to 0 if at maximum value + } else { + nonce.inner = nonce.inner + 1; // Safe to increment without overflow + }; + vector::append(&mut combined_bytes, bcs::to_bytes(&nonce.inner)); + + keccak256(combined_bytes) + } + + #[view] + /// Gets initiator bridge transfer details given a bridge transfer ID + /// + /// @param bridge_transfer_id A 32-byte vector of unsigned 8-bit integers. + /// @return A `BridgeTransferDetails` struct. + /// @abort If there is no transfer in the atomic bridge store. + public fun get_bridge_transfer_details_initiator( + bridge_transfer_id: vector + ): BridgeTransferDetails acquires SmartTableWrapper { + get_bridge_transfer_details(bridge_transfer_id) + } + + #[view] + /// Gets counterparty bridge transfer details given a bridge transfer ID + /// + /// @param bridge_transfer_id A 32-byte vector of unsigned 8-bit integers. + /// @return A `BridgeTransferDetails` struct. + /// @abort If there is no transfer in the atomic bridge store. + public fun get_bridge_transfer_details_counterparty( + bridge_transfer_id: vector + ): BridgeTransferDetails acquires SmartTableWrapper { + get_bridge_transfer_details(bridge_transfer_id) + } + + fun get_bridge_transfer_details(bridge_transfer_id: vector + ): BridgeTransferDetails acquires SmartTableWrapper { + let table = borrow_global, BridgeTransferDetails>>(@aptos_framework); + + let details_ref = smart_table::borrow( + &table.inner, + bridge_transfer_id + ); + + *details_ref + } + + #[test_only] + public fun valid_bridge_transfer_id() : vector { + sha3_256(b"atomic bridge") + } + + #[test_only] + public fun plain_secret() : vector { + b"too secret!" + } + + #[test_only] + public fun valid_hash_lock() : vector { + keccak256(plain_secret()) + } + + + #[test(aptos_framework = @aptos_framework)] + public fun test_get_bridge_transfer_details_initiator(aptos_framework: &signer) acquires SmartTableWrapper { + timestamp::set_time_has_started_for_testing(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + atomic_bridge_configuration::initialize(aptos_framework); + initialize(aptos_framework); + + let initiator = signer::address_of(aptos_framework); + let recipient = ethereum::ethereum_address(ethereum::valid_eip55()); + let amount = 1000; + let hash_lock = valid_hash_lock(); + let time_lock = create_time_lock(3600); + let bridge_transfer_id = valid_bridge_transfer_id(); + + let details = create_details( + initiator, + recipient, + amount, + hash_lock, + time_lock + ); + + add(bridge_transfer_id, details); + + let retrieved_details = get_bridge_transfer_details_initiator(bridge_transfer_id); + + let BridgeTransferDetails { + addresses: AddressPair { + initiator: retrieved_initiator, + recipient: retrieved_recipient + }, + amount: retrieved_amount, + hash_lock: retrieved_hash_lock, + time_lock: retrieved_time_lock, + state: retrieved_state + } = retrieved_details; + + assert!(retrieved_initiator == initiator, 0); + assert!(retrieved_recipient == recipient, 1); + assert!(retrieved_amount == amount, 2); + assert!(retrieved_hash_lock == hash_lock, 3); + assert!(retrieved_time_lock == time_lock, 4); + assert!(retrieved_state == PENDING_TRANSACTION, 5); + } + + #[test(aptos_framework = @aptos_framework)] + public fun test_get_bridge_transfer_details_counterparty(aptos_framework: &signer) acquires SmartTableWrapper { + timestamp::set_time_has_started_for_testing(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + initialize(aptos_framework); + + let initiator = ethereum::ethereum_address(ethereum::valid_eip55()); + let recipient = signer::address_of(aptos_framework); + let amount = 500; + let hash_lock = valid_hash_lock(); + let time_lock = create_time_lock(3600); + let bridge_transfer_id = valid_bridge_transfer_id(); + + let details = create_details( + initiator, + recipient, + amount, + hash_lock, + time_lock + ); + + add(bridge_transfer_id, details); + + let retrieved_details = get_bridge_transfer_details_counterparty(bridge_transfer_id); + + let BridgeTransferDetails { + addresses: AddressPair { + initiator: retrieved_initiator, + recipient: retrieved_recipient + }, + amount: retrieved_amount, + hash_lock: retrieved_hash_lock, + time_lock: retrieved_time_lock, + state: retrieved_state + } = retrieved_details; + + assert!(retrieved_initiator == initiator, 0); + assert!(retrieved_recipient == recipient, 1); + assert!(retrieved_amount == amount, 2); + assert!(retrieved_hash_lock == hash_lock, 3); + assert!(retrieved_time_lock == time_lock, 4); + assert!(retrieved_state == PENDING_TRANSACTION, 5); + } +} + +module aptos_framework::atomic_bridge_configuration { + use std::signer; + use aptos_framework::event; + use aptos_framework::system_addresses; + + friend aptos_framework::atomic_bridge_counterparty; + friend aptos_framework::atomic_bridge_initiator; + + /// Error code for invalid bridge operator + const EINVALID_BRIDGE_OPERATOR: u64 = 0x1; + + /// Counterparty time lock duration is 24 hours in seconds + const COUNTERPARTY_TIME_LOCK_DUARTION: u64 = 24 * 60 * 60; + /// Initiator time lock duration is 48 hours in seconds + const INITIATOR_TIME_LOCK_DUARTION: u64 = 48 * 60 * 60; + + struct BridgeConfig has key { + bridge_operator: address, + initiator_time_lock: u64, + counterparty_time_lock: u64, + } + + #[event] + /// Event emitted when the bridge operator is updated. + struct BridgeConfigOperatorUpdated has store, drop { + old_operator: address, + new_operator: address, + } + + #[event] + /// Event emitted when the initiator time lock has been updated. + struct InitiatorTimeLockUpdated has store, drop { + time_lock: u64, + } + + #[event] + /// Event emitted when the initiator time lock has been updated. + struct CounterpartyTimeLockUpdated has store, drop { + time_lock: u64, + } + + /// Initializes the bridge configuration with Aptos framework as the bridge operator. + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + let bridge_config = BridgeConfig { + bridge_operator: signer::address_of(aptos_framework), + initiator_time_lock: INITIATOR_TIME_LOCK_DUARTION, + counterparty_time_lock: COUNTERPARTY_TIME_LOCK_DUARTION, + }; + move_to(aptos_framework, bridge_config); + } + + /// Updates the bridge operator, requiring governance validation. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param new_operator The new address to be set as the bridge operator. + /// @abort If the current operator is the same as the new operator. + public fun update_bridge_operator(aptos_framework: &signer, new_operator: address + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + let bridge_config = borrow_global_mut(@aptos_framework); + let old_operator = bridge_config.bridge_operator; + assert!(old_operator != new_operator, EINVALID_BRIDGE_OPERATOR); + + bridge_config.bridge_operator = new_operator; + + event::emit( + BridgeConfigOperatorUpdated { + old_operator, + new_operator, + }, + ); + } + + public fun set_initiator_time_lock_duration(aptos_framework: &signer, time_lock: u64 + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + borrow_global_mut(@aptos_framework).initiator_time_lock = time_lock; + + event::emit( + InitiatorTimeLockUpdated { + time_lock + }, + ); + } + + public fun set_counterparty_time_lock_duration(aptos_framework: &signer, time_lock: u64 + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + borrow_global_mut(@aptos_framework).counterparty_time_lock = time_lock; + + event::emit( + CounterpartyTimeLockUpdated { + time_lock + }, + ); + } + + #[view] + public fun initiator_timelock_duration() : u64 acquires BridgeConfig { + borrow_global(@aptos_framework).initiator_time_lock + } + + #[view] + public fun counterparty_timelock_duration() : u64 acquires BridgeConfig { + borrow_global(@aptos_framework).counterparty_time_lock + } + + #[view] + /// Retrieves the address of the current bridge operator. + /// + /// @return The address of the current bridge operator. + public fun bridge_operator(): address acquires BridgeConfig { + borrow_global_mut(@aptos_framework).bridge_operator + } + + /// Asserts that the caller is the current bridge operator. + /// + /// @param caller The signer whose authority is being checked. + /// @abort If the caller is not the current bridge operator. + public(friend) fun assert_is_caller_operator(caller: &signer + ) acquires BridgeConfig { + assert!(borrow_global(@aptos_framework).bridge_operator == signer::address_of(caller), EINVALID_BRIDGE_OPERATOR); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests initialization of the bridge configuration. + fun test_initialization(aptos_framework: &signer) { + initialize(aptos_framework); + assert!(exists(@aptos_framework), 0); + } + + #[test(aptos_framework = @aptos_framework, new_operator = @0xcafe)] + /// Tests updating the bridge operator and emitting the corresponding event. + fun test_update_bridge_operator(aptos_framework: &signer, new_operator: address + ) acquires BridgeConfig { + initialize(aptos_framework); + update_bridge_operator(aptos_framework, new_operator); + + assert!( + event::was_event_emitted( + &BridgeConfigOperatorUpdated { + old_operator: @aptos_framework, + new_operator, + } + ), 0); + + assert!(bridge_operator() == new_operator, 0); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad, new_operator = @0xcafe)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that updating the bridge operator with an invalid signer fails. + fun test_failing_update_bridge_operator(aptos_framework: &signer, bad: &signer, new_operator: address + ) acquires BridgeConfig { + initialize(aptos_framework); + update_bridge_operator(bad, new_operator); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests that the correct operator is validated successfully. + fun test_is_valid_operator(aptos_framework: &signer) acquires BridgeConfig { + initialize(aptos_framework); + assert_is_caller_operator(aptos_framework); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 0x1, location = 0x1::atomic_bridge_configuration)] + /// Tests that an incorrect operator is not validated and results in an abort. + fun test_is_not_valid_operator(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize(aptos_framework); + assert_is_caller_operator(bad); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests we can update the initiator time lock + fun test_update_initiator_time_lock(aptos_framework: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_initiator_time_lock_duration(aptos_framework, 1); + assert!(initiator_timelock_duration() == 1, 0); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests we can update the initiator time lock + fun test_update_counterparty_time_lock(aptos_framework: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_counterparty_time_lock_duration(aptos_framework, 1); + assert!(counterparty_timelock_duration() == 1, 0); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that an incorrect signer cannot update the initiator time lock + fun test_not_able_to_set_initiator_time_lock(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_initiator_time_lock_duration(bad, 1); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that an incorrect signer cannot update the counterparty time lock + fun test_not_able_to_set_counterparty_time_lock(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_counterparty_time_lock_duration(bad, 1); + } +} + +module aptos_framework::atomic_bridge { + use std::features; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::atomic_bridge_configuration; + use aptos_framework::atomic_bridge_store; + use aptos_framework::coin; + use aptos_framework::coin::{BurnCapability, MintCapability}; + use aptos_framework::fungible_asset::{BurnRef, MintRef}; + use aptos_framework::system_addresses; + #[test_only] + use aptos_framework::account; + #[test_only] + use aptos_framework::aptos_coin; + #[test_only] + use aptos_framework::timestamp; + + friend aptos_framework::atomic_bridge_counterparty; + friend aptos_framework::atomic_bridge_initiator; + friend aptos_framework::genesis; + + const EATOMIC_BRIDGE_NOT_ENABLED : u64 = 0x1; + + struct AptosCoinBurnCapability has key { + burn_cap: BurnCapability, + } + + struct AptosCoinMintCapability has key { + mint_cap: MintCapability, + } + + struct AptosFABurnCapabilities has key { + burn_ref: BurnRef, + } + + struct AptosFAMintCapabilities has key { + burn_ref: MintRef, + } + + /// Initializes the atomic bridge by setting up necessary configurations. + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize(aptos_framework: &signer) { + atomic_bridge_configuration::initialize(aptos_framework); + atomic_bridge_store::initialize(aptos_framework); + } + + #[test_only] + /// Initializes the atomic bridge for testing purposes, including setting up accounts and timestamps. + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize_for_test(aptos_framework: &signer) { + timestamp::set_time_has_started_for_testing(aptos_framework); + account::create_account_for_test(@aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + initialize(aptos_framework); + + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(aptos_framework); + + store_aptos_coin_mint_cap(aptos_framework, mint_cap); + store_aptos_coin_burn_cap(aptos_framework, burn_cap); + } + + /// Stores the burn capability for AptosCoin, converting to a fungible asset reference if the feature is enabled. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param burn_cap The burn capability for AptosCoin. + public fun store_aptos_coin_burn_cap(aptos_framework: &signer, burn_cap: BurnCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + if (features::operations_default_to_fa_apt_store_enabled()) { + let burn_ref = coin::convert_and_take_paired_burn_ref(burn_cap); + move_to(aptos_framework, AptosFABurnCapabilities { burn_ref }); + } else { + move_to(aptos_framework, AptosCoinBurnCapability { burn_cap }) + } + } + + /// Stores the mint capability for AptosCoin. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param mint_cap The mint capability for AptosCoin. + public fun store_aptos_coin_mint_cap(aptos_framework: &signer, mint_cap: MintCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, AptosCoinMintCapability { mint_cap }) + } + + /// Mints a specified amount of AptosCoin to a recipient's address. + /// + /// @param recipient The address of the recipient to mint coins to. + /// @param amount The amount of AptosCoin to mint. + /// @abort If the mint capability is not available. + public(friend) fun mint(recipient: address, amount: u64) acquires AptosCoinMintCapability { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + coin::deposit(recipient, coin::mint( + amount, + &borrow_global(@aptos_framework).mint_cap + )); + } + + /// Burns a specified amount of AptosCoin from an address. + /// + /// @param from The address from which to burn AptosCoin. + /// @param amount The amount of AptosCoin to burn. + /// @abort If the burn capability is not available. + public(friend) fun burn(from: address, amount: u64) acquires AptosCoinBurnCapability { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + coin::burn_from( + from, + amount, + &borrow_global(@aptos_framework).burn_cap, + ); + } +} + +module aptos_framework::atomic_bridge_counterparty { + use aptos_framework::account; + use aptos_framework::atomic_bridge; + use aptos_framework::atomic_bridge_configuration; + use aptos_framework::atomic_bridge_store; + use aptos_framework::atomic_bridge_store::create_hashlock; + use aptos_framework::ethereum; + use aptos_framework::ethereum::EthereumAddress; + use aptos_framework::event::{Self, EventHandle}; + #[test_only] + use aptos_framework::aptos_account; + #[test_only] + use aptos_framework::atomic_bridge::initialize_for_test; + #[test_only] + use aptos_framework::atomic_bridge_store::{valid_bridge_transfer_id, valid_hash_lock, plain_secret}; + #[test_only] + use aptos_framework::ethereum::valid_eip55; + #[test_only] + use aptos_framework::signer; + #[test_only] + use aptos_framework::timestamp; + + #[event] + /// An event triggered upon locking assets for a bridge transfer + struct BridgeTransferLockedEvent has store, drop { + bridge_transfer_id: vector, + initiator: vector, + recipient: address, + amount: u64, + hash_lock: vector, + time_lock: u64, + } + + #[event] + /// An event triggered upon completing a bridge transfer + struct BridgeTransferCompletedEvent has store, drop { + bridge_transfer_id: vector, + pre_image: vector, + } + + #[event] + /// An event triggered upon cancelling a bridge transfer + struct BridgeTransferCancelledEvent has store, drop { + bridge_transfer_id: vector, + } + + /// This struct will store the event handles for bridge events. + struct BridgeCounterpartyEvents has key, store { + bridge_transfer_locked_events: EventHandle, + bridge_transfer_completed_events: EventHandle, + bridge_transfer_cancelled_events: EventHandle, + } + + /// Initializes the module and stores the `EventHandle`s in the resource. + public fun initialize(aptos_framework: &signer) { + move_to(aptos_framework, BridgeCounterpartyEvents { + bridge_transfer_locked_events: account::new_event_handle(aptos_framework), + bridge_transfer_completed_events: account::new_event_handle(aptos_framework), + bridge_transfer_cancelled_events: account::new_event_handle(aptos_framework), + }); + } + + /// Locks assets for a bridge transfer by the initiator. + /// + /// @param caller The signer representing the bridge operator. + /// @param initiator The initiator's Ethereum address as a vector of bytes. + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @param hash_lock The hash lock for securing the transfer. + /// @param time_lock The time lock duration for the transfer. + /// @param recipient The address of the recipient on the Aptos blockchain. + /// @param amount The amount of assets to be locked. + /// @abort If the caller is not the bridge operator. + public entry fun lock_bridge_transfer_assets ( + caller: &signer, + initiator: vector, + bridge_transfer_id: vector, + hash_lock: vector, + recipient: address, + amount: u64 + ) acquires BridgeCounterpartyEvents { + atomic_bridge_configuration::assert_is_caller_operator(caller); + let ethereum_address = ethereum::ethereum_address_no_eip55(initiator); + let time_lock = atomic_bridge_configuration::counterparty_timelock_duration(); + let details = atomic_bridge_store::create_details( + ethereum_address, + recipient, + amount, + hash_lock, + time_lock + ); + + // bridge_store::add_counterparty(bridge_transfer_id, details); + atomic_bridge_store::add(bridge_transfer_id, details); + + let bridge_events = borrow_global_mut(@aptos_framework); + + event::emit_event( + &mut bridge_events.bridge_transfer_locked_events, + BridgeTransferLockedEvent { + bridge_transfer_id, + initiator, + recipient, + amount, + hash_lock, + time_lock, + }, + ); + } + + /// Completes a bridge transfer by revealing the pre-image. + /// + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @param pre_image The pre-image that matches the hash lock to complete the transfer. + /// @abort If the caller is not the bridge operator or the hash lock validation fails. + public entry fun complete_bridge_transfer ( + bridge_transfer_id: vector, + pre_image: vector, + ) acquires BridgeCounterpartyEvents { + let (recipient, amount) = atomic_bridge_store::complete_transfer( + bridge_transfer_id, + create_hashlock(pre_image) + ); + + // Mint, fails silently + atomic_bridge::mint(recipient, amount); + + let bridge_counterparty_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_counterparty_events.bridge_transfer_completed_events, + BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image, + }, + ); + } + + /// Aborts a bridge transfer if the time lock has expired. + /// + /// @param caller The signer representing the bridge operator. + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @abort If the caller is not the bridge operator or if the time lock has not expired. + public entry fun abort_bridge_transfer ( + caller: &signer, + bridge_transfer_id: vector + ) acquires BridgeCounterpartyEvents { + atomic_bridge_configuration::assert_is_caller_operator(caller); + + atomic_bridge_store::cancel_transfer(bridge_transfer_id); + + let bridge_counterparty_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_counterparty_events.bridge_transfer_cancelled_events, + BridgeTransferCancelledEvent { + bridge_transfer_id, + }, + ); + } + + #[test(aptos_framework = @aptos_framework)] + fun test_lock_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + let bridge_counterparty_events = borrow_global(signer::address_of(aptos_framework)); + let lock_events = event::emitted_events_by_handle(&bridge_counterparty_events.bridge_transfer_locked_events); + + // Assert that the event was emitted + let expected_event = BridgeTransferLockedEvent { + bridge_transfer_id, + initiator, + recipient, + amount, + hash_lock, + time_lock: atomic_bridge_configuration::counterparty_timelock_duration(), + }; + assert!(std::vector::contains(&lock_events, &expected_event), 0); + + } + + #[test(aptos_framework = @aptos_framework)] + fun test_abort_transfer_of_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + timestamp::fast_forward_seconds(atomic_bridge_configuration::counterparty_timelock_duration() + 1); + abort_bridge_transfer(aptos_framework, bridge_transfer_id); + + let bridge_counterparty_events = borrow_global(signer::address_of(aptos_framework)); + let cancel_events = event::emitted_events_by_handle(&bridge_counterparty_events.bridge_transfer_cancelled_events); + let expected_event = BridgeTransferCancelledEvent { bridge_transfer_id }; + assert!(std::vector::contains(&cancel_events, &expected_event), 0); + } + + #[test(aptos_framework = @aptos_framework)] + fun test_complete_transfer_of_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + // Create an account for our recipient + aptos_account::create_account(recipient); + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + complete_bridge_transfer(bridge_transfer_id, plain_secret()); + + let bridge_counterparty_events = borrow_global(signer::address_of(aptos_framework)); + let complete_events = event::emitted_events_by_handle(&bridge_counterparty_events.bridge_transfer_completed_events); + let expected_event = BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image: plain_secret(), + }; + assert!(std::vector::contains(&complete_events, &expected_event), 0); + + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x1, location = atomic_bridge_store)] + fun test_failing_complete_transfer_of_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + complete_bridge_transfer(bridge_transfer_id, b"not the secret"); + } +} + diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/atomic_bridge_configuration.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/atomic_bridge_configuration.move new file mode 100644 index 000000000..ff1d9851a --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/atomic_bridge_configuration.move @@ -0,0 +1,1523 @@ +module aptos_framework::atomic_bridge_initiator { + use aptos_framework::account; + use aptos_framework::atomic_bridge; + use aptos_framework::atomic_bridge_configuration; + use aptos_framework::atomic_bridge_configuration::assert_is_caller_operator; + use aptos_framework::atomic_bridge_store; + use aptos_framework::atomic_bridge_store::{create_hashlock, bridge_transfer_id}; + use aptos_framework::ethereum; + use aptos_framework::ethereum::EthereumAddress; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::signer; + #[test_only] + use std::vector; + #[test_only] + use aptos_framework::aptos_account; + #[test_only] + use aptos_framework::aptos_coin::AptosCoin; + #[test_only] + use aptos_framework::atomic_bridge_store::{valid_hash_lock, assert_valid_bridge_transfer_id, plain_secret}; + #[test_only] + use aptos_framework::coin; + #[test_only] + use aptos_framework::ethereum::valid_eip55; + #[test_only] + use aptos_framework::timestamp; + + #[event] + struct BridgeTransferInitiatedEvent has store, drop { + bridge_transfer_id: vector, + initiator: address, + recipient: vector, + amount: u64, + hash_lock: vector, + time_lock: u64, + } + + #[event] + struct BridgeTransferCompletedEvent has store, drop { + bridge_transfer_id: vector, + pre_image: vector, + } + + #[event] + struct BridgeTransferRefundedEvent has store, drop { + bridge_transfer_id: vector, + } + + /// This struct will store the event handles for bridge events. + struct BridgeInitiatorEvents has key, store { + bridge_transfer_initiated_events: EventHandle, + bridge_transfer_completed_events: EventHandle, + bridge_transfer_refunded_events: EventHandle, + } + + /// Initializes the module and stores the `EventHandle`s in the resource. + public fun initialize(aptos_framework: &signer) { + move_to(aptos_framework, BridgeInitiatorEvents { + bridge_transfer_initiated_events: account::new_event_handle(aptos_framework), + bridge_transfer_completed_events: account::new_event_handle(aptos_framework), + bridge_transfer_refunded_events: account::new_event_handle(aptos_framework), + }); + } + + /// Initiate a bridge transfer of ETH from Movement to the base layer + /// Anyone can initiate a bridge transfer from the source chain + /// The amount is burnt from the initiator + public entry fun initiate_bridge_transfer( + initiator: &signer, + recipient: vector, + hash_lock: vector, + amount: u64 + ) acquires BridgeInitiatorEvents { + let ethereum_address = ethereum::ethereum_address_no_eip55(recipient); + let initiator_address = signer::address_of(initiator); + let time_lock = atomic_bridge_configuration::initiator_timelock_duration(); + + let details = + atomic_bridge_store::create_details( + initiator_address, + ethereum_address, amount, + hash_lock, + time_lock + ); + + let bridge_transfer_id = bridge_transfer_id(&details); + atomic_bridge_store::add(bridge_transfer_id, details); + atomic_bridge::burn(initiator_address, amount); + + let bridge_initiator_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_initiator_events.bridge_transfer_initiated_events, + BridgeTransferInitiatedEvent { + bridge_transfer_id, + initiator: initiator_address, + recipient, + amount, + hash_lock, + time_lock + }, + ); + } + + /// Bridge operator can complete the transfer + public entry fun complete_bridge_transfer ( + caller: &signer, + bridge_transfer_id: vector, + pre_image: vector, + ) acquires BridgeInitiatorEvents { + assert_is_caller_operator(caller); + let (_, _) = atomic_bridge_store::complete_transfer(bridge_transfer_id, create_hashlock(pre_image)); + + let bridge_initiator_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_initiator_events.bridge_transfer_completed_events, + BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image, + }, + ); + } + + /// Anyone can refund the transfer on the source chain once time lock has passed + public entry fun refund_bridge_transfer ( + _caller: &signer, + bridge_transfer_id: vector, + ) acquires BridgeInitiatorEvents { + let (receiver, amount) = atomic_bridge_store::cancel_transfer(bridge_transfer_id); + atomic_bridge::mint(receiver, amount); + + let bridge_initiator_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_initiator_events.bridge_transfer_refunded_events, + BridgeTransferRefundedEvent { + bridge_transfer_id, + }, + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + fun test_initiate_bridge_transfer( + sender: &signer, + aptos_framework: &signer, + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + initialize(aptos_framework); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let time_lock = atomic_bridge_configuration::initiator_timelock_duration(); + let amount = 1000; + + // Mint some coins + atomic_bridge::mint(sender_address, amount + 1); + + assert!(coin::balance(sender_address) == amount + 1, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + assert!(coin::balance(sender_address) == 1, 0); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + assert_valid_bridge_transfer_id(&bridge_transfer_initiated_event.bridge_transfer_id); + assert!(bridge_transfer_initiated_event.recipient == recipient, 0); + assert!(bridge_transfer_initiated_event.amount == amount, 0); + assert!(bridge_transfer_initiated_event.initiator == sender_address, 0); + assert!(bridge_transfer_initiated_event.hash_lock == hash_lock, 0); + assert!(bridge_transfer_initiated_event.time_lock == time_lock, 0); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x10006, location = 0x1::coin)] //EINSUFFICIENT_BALANCE + fun test_initiate_bridge_transfer_insufficient_balance( + sender: &signer, + aptos_framework: &signer, + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + fun test_complete_bridge_transfer( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + let account_balance = amount + 1; + + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + plain_secret(), + ); + + let bridge_initiator_events = borrow_global(signer::address_of(aptos_framework)); + let complete_events = event::emitted_events_by_handle(&bridge_initiator_events.bridge_transfer_completed_events); + let expected_event = BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image: plain_secret(), + }; + assert!(std::vector::contains(&complete_events, &expected_event), 0); + + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x1, location = 0x1::atomic_bridge_configuration)] // EINVALID_BRIDGE_OPERATOR + fun test_complete_bridge_transfer_by_sender( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + let account_balance = amount + 1; + + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + complete_bridge_transfer( + sender, + bridge_transfer_id, + plain_secret(), + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x1, location = 0x1::atomic_bridge_store)] // EINVALID_PRE_IMAGE + fun test_complete_bridge_transfer_with_invalid_preimage( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + let account_balance = amount + 1; + + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + b"bad secret", + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x10001, location = 0x1::smart_table)] // ENOT_FOUND + fun test_complete_bridge_with_errorneous_bridge_id_by_operator( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + + let bridge_transfer_id = b"guessing the id"; + + // As operator I send a complete request and it should fail + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + plain_secret(), + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + fun test_refund_bridge_transfer( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + let account_balance = amount + 1; + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + assert!(coin::balance(sender_address) == account_balance - amount, 0); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + timestamp::fast_forward_seconds(atomic_bridge_configuration::initiator_timelock_duration() + 1); + + refund_bridge_transfer(sender, bridge_transfer_id); + + assert!(coin::balance(sender_address) == account_balance, 0); + + let bridge_initiator_events = borrow_global(signer::address_of(aptos_framework)); + let refund_events = event::emitted_events_by_handle(&bridge_initiator_events.bridge_transfer_refunded_events); + let expected_event = BridgeTransferRefundedEvent { bridge_transfer_id }; + let was_event_emitted = std::vector::contains(&refund_events, &expected_event); + + assert!(was_event_emitted, 0); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x4, location = 0x1::atomic_bridge_store)] //ENOT_EXPIRED + fun test_refund_bridge_transfer_before_timelock( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + let account_balance = amount + 1; + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + assert!(coin::balance(sender_address) == account_balance - amount, 0); + + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + refund_bridge_transfer(sender, bridge_transfer_id); + } +} + +module aptos_framework::atomic_bridge_store { + use std::bcs; + use std::features; + use std::vector; + use aptos_std::aptos_hash::keccak256; + use aptos_std::smart_table; + use aptos_std::smart_table::SmartTable; + use aptos_framework::ethereum::EthereumAddress; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + use std::signer; + use aptos_framework::timestamp::CurrentTimeMicroseconds; + + friend aptos_framework::atomic_bridge_counterparty; + friend aptos_framework::atomic_bridge_initiator; + + #[test_only] + use std::hash::sha3_256; + #[test_only] + use aptos_framework::ethereum; + #[test_only] + use aptos_framework::atomic_bridge_configuration; + + /// Error codes + const EINVALID_PRE_IMAGE : u64 = 0x1; + const ENOT_PENDING_TRANSACTION : u64 = 0x2; + const EEXPIRED : u64 = 0x3; + const ENOT_EXPIRED : u64 = 0x4; + const EINVALID_HASH_LOCK : u64 = 0x5; + const EINVALID_TIME_LOCK : u64 = 0x6; + const EZERO_AMOUNT : u64 = 0x7; + const EINVALID_BRIDGE_TRANSFER_ID : u64 = 0x8; + const EATOMIC_BRIDGE_NOT_ENABLED : u64 = 0x9; + + /// Transaction states + const PENDING_TRANSACTION: u8 = 0x1; + const COMPLETED_TRANSACTION: u8 = 0x2; + const CANCELLED_TRANSACTION: u8 = 0x3; + + /// Minimum time lock of 1 second + const MIN_TIME_LOCK : u64 = 1; + const MAX_U64 : u64 = 0xFFFFFFFFFFFFFFFF; + + struct AddressPair has store, copy { + initiator: Initiator, + recipient: Recipient, + } + + /// A smart table wrapper + struct SmartTableWrapper has key, store { + inner: SmartTable, + } + + /// Details on the transfer + struct BridgeTransferDetails has store, copy { + addresses: AddressPair, + amount: u64, + hash_lock: vector, + time_lock: u64, + state: u8, + } + + struct Nonce has key { + inner: u64 + } + + /// Initializes the initiators and counterparties tables and nonce. + /// + /// @param aptos_framework The signer for Aptos framework. + public fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, Nonce { + inner: 0, + }); + + let initiators = SmartTableWrapper, BridgeTransferDetails> { + inner: smart_table::new(), + }; + + move_to(aptos_framework, initiators); + + let counterparties = SmartTableWrapper, BridgeTransferDetails> { + inner: smart_table::new(), + }; + + move_to(aptos_framework, counterparties); + } + + /// Returns the current time in seconds. + /// + /// @return Current timestamp in seconds. + fun now() : u64 { + timestamp::now_seconds() + } + + /// Creates a time lock by adding a duration to the current time. + /// + /// @param lock The duration to lock. + /// @return The calculated time lock. + /// @abort If lock is not above MIN_TIME_LOCK + public(friend) fun create_time_lock(time_lock: u64) : u64 { + assert_min_time_lock(time_lock); + now() + time_lock + } + + /// Creates bridge transfer details with validation. + /// + /// @param initiator The initiating party of the transfer. + /// @param recipient The receiving party of the transfer. + /// @param amount The amount to be transferred. + /// @param hash_lock The hash lock for the transfer. + /// @param time_lock The time lock for the transfer. + /// @return A `BridgeTransferDetails` object. + /// @abort If the amount is zero or locks are invalid. + public(friend) fun create_details(initiator: Initiator, recipient: Recipient, amount: u64, hash_lock: vector, time_lock: u64) + : BridgeTransferDetails { + assert!(amount > 0, EZERO_AMOUNT); + assert_valid_hash_lock(&hash_lock); + time_lock = create_time_lock(time_lock); + + BridgeTransferDetails { + addresses: AddressPair { + initiator, + recipient + }, + amount, + hash_lock, + time_lock, + state: PENDING_TRANSACTION, + } + } + + /// Record details of a transfer + /// + /// @param bridge_transfer_id Bridge transfer ID. + /// @param details The bridge transfer details + public(friend) fun add(bridge_transfer_id: vector, details: BridgeTransferDetails) acquires SmartTableWrapper { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + assert_valid_bridge_transfer_id(&bridge_transfer_id); + let table = borrow_global_mut, BridgeTransferDetails>>(@aptos_framework); + smart_table::add(&mut table.inner, bridge_transfer_id, details); + } + + /// Asserts that the time lock is valid. + /// + /// @param time_lock + /// @abort If the time lock is invalid. + fun assert_min_time_lock(time_lock: u64) { + assert!(time_lock >= MIN_TIME_LOCK, EINVALID_TIME_LOCK); + } + + /// Asserts that the details state is pending. + /// + /// @param details The bridge transfer details to check. + /// @abort If the state is not pending. + fun assert_pending(details: &BridgeTransferDetails) { + assert!(details.state == PENDING_TRANSACTION, ENOT_PENDING_TRANSACTION) + } + + /// Asserts that the hash lock is valid. + /// + /// @param hash_lock The hash lock to validate. + /// @abort If the hash lock is invalid. + fun assert_valid_hash_lock(hash_lock: &vector) { + assert!(vector::length(hash_lock) == 32, EINVALID_HASH_LOCK); + } + + /// Asserts that the bridge transfer ID is valid. + /// + /// @param bridge_transfer_id The bridge transfer ID to validate. + /// @abort If the ID is invalid. + public(friend) fun assert_valid_bridge_transfer_id(bridge_transfer_id: &vector) { + assert!(vector::length(bridge_transfer_id) == 32, EINVALID_BRIDGE_TRANSFER_ID); + } + + /// Creates a hash lock from a pre-image. + /// + /// @param pre_image The pre-image to hash. + /// @return The generated hash lock. + public(friend) fun create_hashlock(pre_image: vector) : vector { + assert!(vector::length(&pre_image) > 0, EINVALID_PRE_IMAGE); + keccak256(pre_image) + } + + /// Asserts that the hash lock matches the expected value. + /// + /// @param details The bridge transfer details. + /// @param hash_lock The hash lock to compare. + /// @abort If the hash lock is incorrect. + fun assert_correct_hash_lock(details: &BridgeTransferDetails, hash_lock: vector) { + assert!(&hash_lock == &details.hash_lock, EINVALID_PRE_IMAGE); + } + + /// Asserts that the time lock has expired. + /// + /// @param details The bridge transfer details. + /// @abort If the time lock has not expired. + fun assert_timed_out_lock(details: &BridgeTransferDetails) { + assert!(now() > details.time_lock, ENOT_EXPIRED); + } + + /// Asserts we are still within the timelock. + /// + /// @param details The bridge transfer details. + /// @abort If the time lock has expired. + fun assert_within_timelock(details: &BridgeTransferDetails) { + assert!(!(now() > details.time_lock), EEXPIRED); + } + + /// Completes the bridge transfer. + /// + /// @param details The bridge transfer details to complete. + fun complete(details: &mut BridgeTransferDetails) { + details.state = COMPLETED_TRANSACTION; + } + + /// Cancels the bridge transfer. + /// + /// @param details The bridge transfer details to cancel. + fun cancel(details: &mut BridgeTransferDetails) { + details.state = CANCELLED_TRANSACTION; + } + + /// Validates and completes a bridge transfer by confirming the hash lock and state. + /// + /// @param hash_lock The hash lock used to validate the transfer. + /// @param details The mutable reference to the bridge transfer details to be completed. + /// @return A tuple containing the recipient and the amount of the transfer. + /// @abort If the hash lock is invalid, the transfer is not pending, or the hash lock does not match. + fun complete_details(hash_lock: vector, details: &mut BridgeTransferDetails) : (Recipient, u64) { + assert_valid_hash_lock(&hash_lock); + assert_pending(details); + assert_correct_hash_lock(details, hash_lock); + assert_within_timelock(details); + + complete(details); + + (details.addresses.recipient, details.amount) + } + + /// Completes a bridge transfer by validating the hash lock and updating the transfer state. + /// + /// @param bridge_transfer_id The ID of the bridge transfer to complete. + /// @param hash_lock The hash lock used to validate the transfer. + /// @return A tuple containing the recipient of the transfer and the amount transferred. + /// @abort If the bridge transfer details are not found or if the completion checks in `complete_details` fail. + public(friend) fun complete_transfer(bridge_transfer_id: vector, hash_lock: vector) : (Recipient, u64) acquires SmartTableWrapper { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + let table = borrow_global_mut, BridgeTransferDetails>>(@aptos_framework); + + let details = smart_table::borrow_mut( + &mut table.inner, + bridge_transfer_id); + + complete_details(hash_lock, details) + } + + /// Cancels a pending bridge transfer if the time lock has expired. + /// + /// @param details A mutable reference to the bridge transfer details to be canceled. + /// @return A tuple containing the initiator of the transfer and the amount to be refunded. + /// @abort If the transfer is not in a pending state or the time lock has not expired. + fun cancel_details(details: &mut BridgeTransferDetails) : (Initiator, u64) { + assert_pending(details); + assert_timed_out_lock(details); + + cancel(details); + + (details.addresses.initiator, details.amount) + } + + /// Cancels a bridge transfer if it is pending and the time lock has expired. + /// + /// @param bridge_transfer_id The ID of the bridge transfer to cancel. + /// @return A tuple containing the initiator of the transfer and the amount to be refunded. + /// @abort If the bridge transfer details are not found or if the cancellation conditions in `cancel_details` fail. + public(friend) fun cancel_transfer(bridge_transfer_id: vector) : (Initiator, u64) acquires SmartTableWrapper { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + let table = borrow_global_mut, BridgeTransferDetails>>(@aptos_framework); + + let details = smart_table::borrow_mut( + &mut table.inner, + bridge_transfer_id); + + cancel_details(details) + } + + /// Generates a unique bridge transfer ID based on transfer details and nonce. + /// + /// @param details The bridge transfer details. + /// @return The generated bridge transfer ID. + public(friend) fun bridge_transfer_id(details: &BridgeTransferDetails) : vector acquires Nonce { + let nonce = borrow_global_mut(@aptos_framework); + let combined_bytes = vector::empty(); + vector::append(&mut combined_bytes, bcs::to_bytes(&details.addresses.initiator)); + vector::append(&mut combined_bytes, bcs::to_bytes(&details.addresses.recipient)); + vector::append(&mut combined_bytes, details.hash_lock); + if (nonce.inner == MAX_U64) { + nonce.inner = 0; // Wrap around to 0 if at maximum value + } else { + nonce.inner = nonce.inner + 1; // Safe to increment without overflow + }; + vector::append(&mut combined_bytes, bcs::to_bytes(&nonce.inner)); + + keccak256(combined_bytes) + } + + #[view] + /// Gets initiator bridge transfer details given a bridge transfer ID + /// + /// @param bridge_transfer_id A 32-byte vector of unsigned 8-bit integers. + /// @return A `BridgeTransferDetails` struct. + /// @abort If there is no transfer in the atomic bridge store. + public fun get_bridge_transfer_details_initiator( + bridge_transfer_id: vector + ): BridgeTransferDetails acquires SmartTableWrapper { + get_bridge_transfer_details(bridge_transfer_id) + } + + #[view] + /// Gets counterparty bridge transfer details given a bridge transfer ID + /// + /// @param bridge_transfer_id A 32-byte vector of unsigned 8-bit integers. + /// @return A `BridgeTransferDetails` struct. + /// @abort If there is no transfer in the atomic bridge store. + public fun get_bridge_transfer_details_counterparty( + bridge_transfer_id: vector + ): BridgeTransferDetails acquires SmartTableWrapper { + get_bridge_transfer_details(bridge_transfer_id) + } + + fun get_bridge_transfer_details(bridge_transfer_id: vector + ): BridgeTransferDetails acquires SmartTableWrapper { + let table = borrow_global, BridgeTransferDetails>>(@aptos_framework); + + let details_ref = smart_table::borrow( + &table.inner, + bridge_transfer_id + ); + + *details_ref + } + + #[test_only] + public fun valid_bridge_transfer_id() : vector { + sha3_256(b"atomic bridge") + } + + #[test_only] + public fun plain_secret() : vector { + b"too secret!" + } + + #[test_only] + public fun valid_hash_lock() : vector { + keccak256(plain_secret()) + } + + + #[test(aptos_framework = @aptos_framework)] + public fun test_get_bridge_transfer_details_initiator(aptos_framework: &signer) acquires SmartTableWrapper { + timestamp::set_time_has_started_for_testing(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + atomic_bridge_configuration::initialize(aptos_framework); + initialize(aptos_framework); + + let initiator = signer::address_of(aptos_framework); + let recipient = ethereum::ethereum_address(ethereum::valid_eip55()); + let amount = 1000; + let hash_lock = valid_hash_lock(); + let time_lock = create_time_lock(3600); + let bridge_transfer_id = valid_bridge_transfer_id(); + + let details = create_details( + initiator, + recipient, + amount, + hash_lock, + time_lock + ); + + add(bridge_transfer_id, details); + + let retrieved_details = get_bridge_transfer_details_initiator(bridge_transfer_id); + + let BridgeTransferDetails { + addresses: AddressPair { + initiator: retrieved_initiator, + recipient: retrieved_recipient + }, + amount: retrieved_amount, + hash_lock: retrieved_hash_lock, + time_lock: retrieved_time_lock, + state: retrieved_state + } = retrieved_details; + + assert!(retrieved_initiator == initiator, 0); + assert!(retrieved_recipient == recipient, 1); + assert!(retrieved_amount == amount, 2); + assert!(retrieved_hash_lock == hash_lock, 3); + assert!(retrieved_time_lock == time_lock, 4); + assert!(retrieved_state == PENDING_TRANSACTION, 5); + } + + #[test(aptos_framework = @aptos_framework)] + public fun test_get_bridge_transfer_details_counterparty(aptos_framework: &signer) acquires SmartTableWrapper { + timestamp::set_time_has_started_for_testing(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + initialize(aptos_framework); + + let initiator = ethereum::ethereum_address(ethereum::valid_eip55()); + let recipient = signer::address_of(aptos_framework); + let amount = 500; + let hash_lock = valid_hash_lock(); + let time_lock = create_time_lock(3600); + let bridge_transfer_id = valid_bridge_transfer_id(); + + let details = create_details( + initiator, + recipient, + amount, + hash_lock, + time_lock + ); + + add(bridge_transfer_id, details); + + let retrieved_details = get_bridge_transfer_details_counterparty(bridge_transfer_id); + + let BridgeTransferDetails { + addresses: AddressPair { + initiator: retrieved_initiator, + recipient: retrieved_recipient + }, + amount: retrieved_amount, + hash_lock: retrieved_hash_lock, + time_lock: retrieved_time_lock, + state: retrieved_state + } = retrieved_details; + + assert!(retrieved_initiator == initiator, 0); + assert!(retrieved_recipient == recipient, 1); + assert!(retrieved_amount == amount, 2); + assert!(retrieved_hash_lock == hash_lock, 3); + assert!(retrieved_time_lock == time_lock, 4); + assert!(retrieved_state == PENDING_TRANSACTION, 5); + } +} + +module aptos_framework::atomic_bridge_configuration { + use std::signer; + use aptos_framework::event; + use aptos_framework::system_addresses; + + friend aptos_framework::atomic_bridge_counterparty; + friend aptos_framework::atomic_bridge_initiator; + + /// Error code for invalid bridge operator + const EINVALID_BRIDGE_OPERATOR: u64 = 0x1; + + /// Counterparty time lock duration is 24 hours in seconds + const COUNTERPARTY_TIME_LOCK_DUARTION: u64 = 24 * 60 * 60; + /// Initiator time lock duration is 48 hours in seconds + const INITIATOR_TIME_LOCK_DUARTION: u64 = 48 * 60 * 60; + + struct BridgeConfig has key { + bridge_operator: address, + initiator_time_lock: u64, + counterparty_time_lock: u64, + } + + #[event] + /// Event emitted when the bridge operator is updated. + struct BridgeConfigOperatorUpdated has store, drop { + old_operator: address, + new_operator: address, + } + + #[event] + /// Event emitted when the initiator time lock has been updated. + struct InitiatorTimeLockUpdated has store, drop { + time_lock: u64, + } + + #[event] + /// Event emitted when the initiator time lock has been updated. + struct CounterpartyTimeLockUpdated has store, drop { + time_lock: u64, + } + + /// Initializes the bridge configuration with Aptos framework as the bridge operator. + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + let bridge_config = BridgeConfig { + bridge_operator: signer::address_of(aptos_framework), + initiator_time_lock: INITIATOR_TIME_LOCK_DUARTION, + counterparty_time_lock: COUNTERPARTY_TIME_LOCK_DUARTION, + }; + move_to(aptos_framework, bridge_config); + } + + /// Updates the bridge operator, requiring governance validation. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param new_operator The new address to be set as the bridge operator. + /// @abort If the current operator is the same as the new operator. + public fun update_bridge_operator(aptos_framework: &signer, new_operator: address + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + let bridge_config = borrow_global_mut(@aptos_framework); + let old_operator = bridge_config.bridge_operator; + assert!(old_operator != new_operator, EINVALID_BRIDGE_OPERATOR); + + bridge_config.bridge_operator = new_operator; + + event::emit( + BridgeConfigOperatorUpdated { + old_operator, + new_operator, + }, + ); + } + + public fun set_initiator_time_lock_duration(aptos_framework: &signer, time_lock: u64 + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + borrow_global_mut(@aptos_framework).initiator_time_lock = time_lock; + + event::emit( + InitiatorTimeLockUpdated { + time_lock + }, + ); + } + + public fun set_counterparty_time_lock_duration(aptos_framework: &signer, time_lock: u64 + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + borrow_global_mut(@aptos_framework).counterparty_time_lock = time_lock; + + event::emit( + CounterpartyTimeLockUpdated { + time_lock + }, + ); + } + + #[view] + public fun initiator_timelock_duration() : u64 acquires BridgeConfig { + borrow_global(@aptos_framework).initiator_time_lock + } + + #[view] + public fun counterparty_timelock_duration() : u64 acquires BridgeConfig { + borrow_global(@aptos_framework).counterparty_time_lock + } + + #[view] + /// Retrieves the address of the current bridge operator. + /// + /// @return The address of the current bridge operator. + public fun bridge_operator(): address acquires BridgeConfig { + borrow_global_mut(@aptos_framework).bridge_operator + } + + /// Asserts that the caller is the current bridge operator. + /// + /// @param caller The signer whose authority is being checked. + /// @abort If the caller is not the current bridge operator. + public(friend) fun assert_is_caller_operator(caller: &signer + ) acquires BridgeConfig { + assert!(borrow_global(@aptos_framework).bridge_operator == signer::address_of(caller), EINVALID_BRIDGE_OPERATOR); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests initialization of the bridge configuration. + fun test_initialization(aptos_framework: &signer) { + initialize(aptos_framework); + assert!(exists(@aptos_framework), 0); + } + + #[test(aptos_framework = @aptos_framework, new_operator = @0xcafe)] + /// Tests updating the bridge operator and emitting the corresponding event. + fun test_update_bridge_operator(aptos_framework: &signer, new_operator: address + ) acquires BridgeConfig { + initialize(aptos_framework); + update_bridge_operator(aptos_framework, new_operator); + + assert!( + event::was_event_emitted( + &BridgeConfigOperatorUpdated { + old_operator: @aptos_framework, + new_operator, + } + ), 0); + + assert!(bridge_operator() == new_operator, 0); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad, new_operator = @0xcafe)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that updating the bridge operator with an invalid signer fails. + fun test_failing_update_bridge_operator(aptos_framework: &signer, bad: &signer, new_operator: address + ) acquires BridgeConfig { + initialize(aptos_framework); + update_bridge_operator(bad, new_operator); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests that the correct operator is validated successfully. + fun test_is_valid_operator(aptos_framework: &signer) acquires BridgeConfig { + initialize(aptos_framework); + assert_is_caller_operator(aptos_framework); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 0x1, location = 0x1::atomic_bridge_configuration)] + /// Tests that an incorrect operator is not validated and results in an abort. + fun test_is_not_valid_operator(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize(aptos_framework); + assert_is_caller_operator(bad); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests we can update the initiator time lock + fun test_update_initiator_time_lock(aptos_framework: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_initiator_time_lock_duration(aptos_framework, 1); + assert!(initiator_timelock_duration() == 1, 0); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests we can update the initiator time lock + fun test_update_counterparty_time_lock(aptos_framework: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_counterparty_time_lock_duration(aptos_framework, 1); + assert!(counterparty_timelock_duration() == 1, 0); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that an incorrect signer cannot update the initiator time lock + fun test_not_able_to_set_initiator_time_lock(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_initiator_time_lock_duration(bad, 1); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that an incorrect signer cannot update the counterparty time lock + fun test_not_able_to_set_counterparty_time_lock(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_counterparty_time_lock_duration(bad, 1); + } +} + +module aptos_framework::atomic_bridge { + use std::features; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::atomic_bridge_configuration; + use aptos_framework::atomic_bridge_store; + use aptos_framework::coin; + use aptos_framework::coin::{BurnCapability, MintCapability}; + use aptos_framework::fungible_asset::{BurnRef, MintRef}; + use aptos_framework::system_addresses; + #[test_only] + use aptos_framework::account; + #[test_only] + use aptos_framework::aptos_coin; + #[test_only] + use aptos_framework::timestamp; + + friend aptos_framework::atomic_bridge_counterparty; + friend aptos_framework::atomic_bridge_initiator; + friend aptos_framework::genesis; + + const EATOMIC_BRIDGE_NOT_ENABLED : u64 = 0x1; + + struct AptosCoinBurnCapability has key { + burn_cap: BurnCapability, + } + + struct AptosCoinMintCapability has key { + mint_cap: MintCapability, + } + + struct AptosFABurnCapabilities has key { + burn_ref: BurnRef, + } + + struct AptosFAMintCapabilities has key { + burn_ref: MintRef, + } + + /// Initializes the atomic bridge by setting up necessary configurations. + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize(aptos_framework: &signer) { + atomic_bridge_configuration::initialize(aptos_framework); + atomic_bridge_store::initialize(aptos_framework); + } + + #[test_only] + /// Initializes the atomic bridge for testing purposes, including setting up accounts and timestamps. + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize_for_test(aptos_framework: &signer) { + timestamp::set_time_has_started_for_testing(aptos_framework); + account::create_account_for_test(@aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + initialize(aptos_framework); + + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(aptos_framework); + + store_aptos_coin_mint_cap(aptos_framework, mint_cap); + store_aptos_coin_burn_cap(aptos_framework, burn_cap); + } + + /// Stores the burn capability for AptosCoin, converting to a fungible asset reference if the feature is enabled. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param burn_cap The burn capability for AptosCoin. + public fun store_aptos_coin_burn_cap(aptos_framework: &signer, burn_cap: BurnCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + if (features::operations_default_to_fa_apt_store_enabled()) { + let burn_ref = coin::convert_and_take_paired_burn_ref(burn_cap); + move_to(aptos_framework, AptosFABurnCapabilities { burn_ref }); + } else { + move_to(aptos_framework, AptosCoinBurnCapability { burn_cap }) + } + } + + /// Stores the mint capability for AptosCoin. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param mint_cap The mint capability for AptosCoin. + public fun store_aptos_coin_mint_cap(aptos_framework: &signer, mint_cap: MintCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, AptosCoinMintCapability { mint_cap }) + } + + /// Mints a specified amount of AptosCoin to a recipient's address. + /// + /// @param recipient The address of the recipient to mint coins to. + /// @param amount The amount of AptosCoin to mint. + /// @abort If the mint capability is not available. + public(friend) fun mint(recipient: address, amount: u64) acquires AptosCoinMintCapability { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + coin::deposit(recipient, coin::mint( + amount, + &borrow_global(@aptos_framework).mint_cap + )); + } + + /// Burns a specified amount of AptosCoin from an address. + /// + /// @param from The address from which to burn AptosCoin. + /// @param amount The amount of AptosCoin to burn. + /// @abort If the burn capability is not available. + public(friend) fun burn(from: address, amount: u64) acquires AptosCoinBurnCapability { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + coin::burn_from( + from, + amount, + &borrow_global(@aptos_framework).burn_cap, + ); + } +} + +module aptos_framework::atomic_bridge_counterparty { + use aptos_framework::account; + use aptos_framework::atomic_bridge; + use aptos_framework::atomic_bridge_configuration; + use aptos_framework::atomic_bridge_store; + use aptos_framework::atomic_bridge_store::create_hashlock; + use aptos_framework::ethereum; + use aptos_framework::ethereum::EthereumAddress; + use aptos_framework::event::{Self, EventHandle}; + #[test_only] + use aptos_framework::aptos_account; + #[test_only] + use aptos_framework::atomic_bridge::initialize_for_test; + #[test_only] + use aptos_framework::atomic_bridge_store::{valid_bridge_transfer_id, valid_hash_lock, plain_secret}; + #[test_only] + use aptos_framework::ethereum::valid_eip55; + #[test_only] + use aptos_framework::signer; + #[test_only] + use aptos_framework::timestamp; + + #[event] + /// An event triggered upon locking assets for a bridge transfer + struct BridgeTransferLockedEvent has store, drop { + bridge_transfer_id: vector, + initiator: vector, + recipient: address, + amount: u64, + hash_lock: vector, + time_lock: u64, + } + + #[event] + /// An event triggered upon completing a bridge transfer + struct BridgeTransferCompletedEvent has store, drop { + bridge_transfer_id: vector, + pre_image: vector, + } + + #[event] + /// An event triggered upon cancelling a bridge transfer + struct BridgeTransferCancelledEvent has store, drop { + bridge_transfer_id: vector, + } + + /// This struct will store the event handles for bridge events. + struct BridgeCounterpartyEvents has key, store { + bridge_transfer_locked_events: EventHandle, + bridge_transfer_completed_events: EventHandle, + bridge_transfer_cancelled_events: EventHandle, + } + + /// Initializes the module and stores the `EventHandle`s in the resource. + public fun initialize(aptos_framework: &signer) { + move_to(aptos_framework, BridgeCounterpartyEvents { + bridge_transfer_locked_events: account::new_event_handle(aptos_framework), + bridge_transfer_completed_events: account::new_event_handle(aptos_framework), + bridge_transfer_cancelled_events: account::new_event_handle(aptos_framework), + }); + } + + /// Locks assets for a bridge transfer by the initiator. + /// + /// @param caller The signer representing the bridge operator. + /// @param initiator The initiator's Ethereum address as a vector of bytes. + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @param hash_lock The hash lock for securing the transfer. + /// @param time_lock The time lock duration for the transfer. + /// @param recipient The address of the recipient on the Aptos blockchain. + /// @param amount The amount of assets to be locked. + /// @abort If the caller is not the bridge operator. + public entry fun lock_bridge_transfer_assets ( + caller: &signer, + initiator: vector, + bridge_transfer_id: vector, + hash_lock: vector, + recipient: address, + amount: u64 + ) acquires BridgeCounterpartyEvents { + atomic_bridge_configuration::assert_is_caller_operator(caller); + let ethereum_address = ethereum::ethereum_address_no_eip55(initiator); + let time_lock = atomic_bridge_configuration::counterparty_timelock_duration(); + let details = atomic_bridge_store::create_details( + ethereum_address, + recipient, + amount, + hash_lock, + time_lock + ); + + // bridge_store::add_counterparty(bridge_transfer_id, details); + atomic_bridge_store::add(bridge_transfer_id, details); + + let bridge_events = borrow_global_mut(@aptos_framework); + + event::emit_event( + &mut bridge_events.bridge_transfer_locked_events, + BridgeTransferLockedEvent { + bridge_transfer_id, + initiator, + recipient, + amount, + hash_lock, + time_lock, + }, + ); + } + + /// Completes a bridge transfer by revealing the pre-image. + /// + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @param pre_image The pre-image that matches the hash lock to complete the transfer. + /// @abort If the caller is not the bridge operator or the hash lock validation fails. + public entry fun complete_bridge_transfer ( + bridge_transfer_id: vector, + pre_image: vector, + ) acquires BridgeCounterpartyEvents { + let (recipient, amount) = atomic_bridge_store::complete_transfer( + bridge_transfer_id, + create_hashlock(pre_image) + ); + + // Mint, fails silently + atomic_bridge::mint(recipient, amount); + + let bridge_counterparty_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_counterparty_events.bridge_transfer_completed_events, + BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image, + }, + ); + } + + /// Aborts a bridge transfer if the time lock has expired. + /// + /// @param caller The signer representing the bridge operator. + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @abort If the caller is not the bridge operator or if the time lock has not expired. + public entry fun abort_bridge_transfer ( + caller: &signer, + bridge_transfer_id: vector + ) acquires BridgeCounterpartyEvents { + atomic_bridge_configuration::assert_is_caller_operator(caller); + + atomic_bridge_store::cancel_transfer(bridge_transfer_id); + + let bridge_counterparty_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_counterparty_events.bridge_transfer_cancelled_events, + BridgeTransferCancelledEvent { + bridge_transfer_id, + }, + ); + } + + #[test(aptos_framework = @aptos_framework)] + fun test_lock_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + let bridge_counterparty_events = borrow_global(signer::address_of(aptos_framework)); + let lock_events = event::emitted_events_by_handle(&bridge_counterparty_events.bridge_transfer_locked_events); + + // Assert that the event was emitted + let expected_event = BridgeTransferLockedEvent { + bridge_transfer_id, + initiator, + recipient, + amount, + hash_lock, + time_lock: atomic_bridge_configuration::counterparty_timelock_duration(), + }; + assert!(std::vector::contains(&lock_events, &expected_event), 0); + + } + + #[test(aptos_framework = @aptos_framework)] + fun test_abort_transfer_of_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + timestamp::fast_forward_seconds(atomic_bridge_configuration::counterparty_timelock_duration() + 1); + abort_bridge_transfer(aptos_framework, bridge_transfer_id); + + let bridge_counterparty_events = borrow_global(signer::address_of(aptos_framework)); + let cancel_events = event::emitted_events_by_handle(&bridge_counterparty_events.bridge_transfer_cancelled_events); + let expected_event = BridgeTransferCancelledEvent { bridge_transfer_id }; + assert!(std::vector::contains(&cancel_events, &expected_event), 0); + } + + #[test(aptos_framework = @aptos_framework)] + fun test_complete_transfer_of_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + // Create an account for our recipient + aptos_account::create_account(recipient); + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + complete_bridge_transfer(bridge_transfer_id, plain_secret()); + + let bridge_counterparty_events = borrow_global(signer::address_of(aptos_framework)); + let complete_events = event::emitted_events_by_handle(&bridge_counterparty_events.bridge_transfer_completed_events); + let expected_event = BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image: plain_secret(), + }; + assert!(std::vector::contains(&complete_events, &expected_event), 0); + + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x1, location = atomic_bridge_store)] + fun test_failing_complete_transfer_of_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + complete_bridge_transfer(bridge_transfer_id, b"not the secret"); + } +} + diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/atomic_bridge_counterparty.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/atomic_bridge_counterparty.move new file mode 100644 index 000000000..ff1d9851a --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/atomic_bridge_counterparty.move @@ -0,0 +1,1523 @@ +module aptos_framework::atomic_bridge_initiator { + use aptos_framework::account; + use aptos_framework::atomic_bridge; + use aptos_framework::atomic_bridge_configuration; + use aptos_framework::atomic_bridge_configuration::assert_is_caller_operator; + use aptos_framework::atomic_bridge_store; + use aptos_framework::atomic_bridge_store::{create_hashlock, bridge_transfer_id}; + use aptos_framework::ethereum; + use aptos_framework::ethereum::EthereumAddress; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::signer; + #[test_only] + use std::vector; + #[test_only] + use aptos_framework::aptos_account; + #[test_only] + use aptos_framework::aptos_coin::AptosCoin; + #[test_only] + use aptos_framework::atomic_bridge_store::{valid_hash_lock, assert_valid_bridge_transfer_id, plain_secret}; + #[test_only] + use aptos_framework::coin; + #[test_only] + use aptos_framework::ethereum::valid_eip55; + #[test_only] + use aptos_framework::timestamp; + + #[event] + struct BridgeTransferInitiatedEvent has store, drop { + bridge_transfer_id: vector, + initiator: address, + recipient: vector, + amount: u64, + hash_lock: vector, + time_lock: u64, + } + + #[event] + struct BridgeTransferCompletedEvent has store, drop { + bridge_transfer_id: vector, + pre_image: vector, + } + + #[event] + struct BridgeTransferRefundedEvent has store, drop { + bridge_transfer_id: vector, + } + + /// This struct will store the event handles for bridge events. + struct BridgeInitiatorEvents has key, store { + bridge_transfer_initiated_events: EventHandle, + bridge_transfer_completed_events: EventHandle, + bridge_transfer_refunded_events: EventHandle, + } + + /// Initializes the module and stores the `EventHandle`s in the resource. + public fun initialize(aptos_framework: &signer) { + move_to(aptos_framework, BridgeInitiatorEvents { + bridge_transfer_initiated_events: account::new_event_handle(aptos_framework), + bridge_transfer_completed_events: account::new_event_handle(aptos_framework), + bridge_transfer_refunded_events: account::new_event_handle(aptos_framework), + }); + } + + /// Initiate a bridge transfer of ETH from Movement to the base layer + /// Anyone can initiate a bridge transfer from the source chain + /// The amount is burnt from the initiator + public entry fun initiate_bridge_transfer( + initiator: &signer, + recipient: vector, + hash_lock: vector, + amount: u64 + ) acquires BridgeInitiatorEvents { + let ethereum_address = ethereum::ethereum_address_no_eip55(recipient); + let initiator_address = signer::address_of(initiator); + let time_lock = atomic_bridge_configuration::initiator_timelock_duration(); + + let details = + atomic_bridge_store::create_details( + initiator_address, + ethereum_address, amount, + hash_lock, + time_lock + ); + + let bridge_transfer_id = bridge_transfer_id(&details); + atomic_bridge_store::add(bridge_transfer_id, details); + atomic_bridge::burn(initiator_address, amount); + + let bridge_initiator_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_initiator_events.bridge_transfer_initiated_events, + BridgeTransferInitiatedEvent { + bridge_transfer_id, + initiator: initiator_address, + recipient, + amount, + hash_lock, + time_lock + }, + ); + } + + /// Bridge operator can complete the transfer + public entry fun complete_bridge_transfer ( + caller: &signer, + bridge_transfer_id: vector, + pre_image: vector, + ) acquires BridgeInitiatorEvents { + assert_is_caller_operator(caller); + let (_, _) = atomic_bridge_store::complete_transfer(bridge_transfer_id, create_hashlock(pre_image)); + + let bridge_initiator_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_initiator_events.bridge_transfer_completed_events, + BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image, + }, + ); + } + + /// Anyone can refund the transfer on the source chain once time lock has passed + public entry fun refund_bridge_transfer ( + _caller: &signer, + bridge_transfer_id: vector, + ) acquires BridgeInitiatorEvents { + let (receiver, amount) = atomic_bridge_store::cancel_transfer(bridge_transfer_id); + atomic_bridge::mint(receiver, amount); + + let bridge_initiator_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_initiator_events.bridge_transfer_refunded_events, + BridgeTransferRefundedEvent { + bridge_transfer_id, + }, + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + fun test_initiate_bridge_transfer( + sender: &signer, + aptos_framework: &signer, + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + initialize(aptos_framework); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let time_lock = atomic_bridge_configuration::initiator_timelock_duration(); + let amount = 1000; + + // Mint some coins + atomic_bridge::mint(sender_address, amount + 1); + + assert!(coin::balance(sender_address) == amount + 1, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + assert!(coin::balance(sender_address) == 1, 0); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + assert_valid_bridge_transfer_id(&bridge_transfer_initiated_event.bridge_transfer_id); + assert!(bridge_transfer_initiated_event.recipient == recipient, 0); + assert!(bridge_transfer_initiated_event.amount == amount, 0); + assert!(bridge_transfer_initiated_event.initiator == sender_address, 0); + assert!(bridge_transfer_initiated_event.hash_lock == hash_lock, 0); + assert!(bridge_transfer_initiated_event.time_lock == time_lock, 0); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x10006, location = 0x1::coin)] //EINSUFFICIENT_BALANCE + fun test_initiate_bridge_transfer_insufficient_balance( + sender: &signer, + aptos_framework: &signer, + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + fun test_complete_bridge_transfer( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + let account_balance = amount + 1; + + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + plain_secret(), + ); + + let bridge_initiator_events = borrow_global(signer::address_of(aptos_framework)); + let complete_events = event::emitted_events_by_handle(&bridge_initiator_events.bridge_transfer_completed_events); + let expected_event = BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image: plain_secret(), + }; + assert!(std::vector::contains(&complete_events, &expected_event), 0); + + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x1, location = 0x1::atomic_bridge_configuration)] // EINVALID_BRIDGE_OPERATOR + fun test_complete_bridge_transfer_by_sender( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + let account_balance = amount + 1; + + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + complete_bridge_transfer( + sender, + bridge_transfer_id, + plain_secret(), + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x1, location = 0x1::atomic_bridge_store)] // EINVALID_PRE_IMAGE + fun test_complete_bridge_transfer_with_invalid_preimage( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + let account_balance = amount + 1; + + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + b"bad secret", + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x10001, location = 0x1::smart_table)] // ENOT_FOUND + fun test_complete_bridge_with_errorneous_bridge_id_by_operator( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + + let bridge_transfer_id = b"guessing the id"; + + // As operator I send a complete request and it should fail + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + plain_secret(), + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + fun test_refund_bridge_transfer( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + let account_balance = amount + 1; + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + assert!(coin::balance(sender_address) == account_balance - amount, 0); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + timestamp::fast_forward_seconds(atomic_bridge_configuration::initiator_timelock_duration() + 1); + + refund_bridge_transfer(sender, bridge_transfer_id); + + assert!(coin::balance(sender_address) == account_balance, 0); + + let bridge_initiator_events = borrow_global(signer::address_of(aptos_framework)); + let refund_events = event::emitted_events_by_handle(&bridge_initiator_events.bridge_transfer_refunded_events); + let expected_event = BridgeTransferRefundedEvent { bridge_transfer_id }; + let was_event_emitted = std::vector::contains(&refund_events, &expected_event); + + assert!(was_event_emitted, 0); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x4, location = 0x1::atomic_bridge_store)] //ENOT_EXPIRED + fun test_refund_bridge_transfer_before_timelock( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + let account_balance = amount + 1; + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + assert!(coin::balance(sender_address) == account_balance - amount, 0); + + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + refund_bridge_transfer(sender, bridge_transfer_id); + } +} + +module aptos_framework::atomic_bridge_store { + use std::bcs; + use std::features; + use std::vector; + use aptos_std::aptos_hash::keccak256; + use aptos_std::smart_table; + use aptos_std::smart_table::SmartTable; + use aptos_framework::ethereum::EthereumAddress; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + use std::signer; + use aptos_framework::timestamp::CurrentTimeMicroseconds; + + friend aptos_framework::atomic_bridge_counterparty; + friend aptos_framework::atomic_bridge_initiator; + + #[test_only] + use std::hash::sha3_256; + #[test_only] + use aptos_framework::ethereum; + #[test_only] + use aptos_framework::atomic_bridge_configuration; + + /// Error codes + const EINVALID_PRE_IMAGE : u64 = 0x1; + const ENOT_PENDING_TRANSACTION : u64 = 0x2; + const EEXPIRED : u64 = 0x3; + const ENOT_EXPIRED : u64 = 0x4; + const EINVALID_HASH_LOCK : u64 = 0x5; + const EINVALID_TIME_LOCK : u64 = 0x6; + const EZERO_AMOUNT : u64 = 0x7; + const EINVALID_BRIDGE_TRANSFER_ID : u64 = 0x8; + const EATOMIC_BRIDGE_NOT_ENABLED : u64 = 0x9; + + /// Transaction states + const PENDING_TRANSACTION: u8 = 0x1; + const COMPLETED_TRANSACTION: u8 = 0x2; + const CANCELLED_TRANSACTION: u8 = 0x3; + + /// Minimum time lock of 1 second + const MIN_TIME_LOCK : u64 = 1; + const MAX_U64 : u64 = 0xFFFFFFFFFFFFFFFF; + + struct AddressPair has store, copy { + initiator: Initiator, + recipient: Recipient, + } + + /// A smart table wrapper + struct SmartTableWrapper has key, store { + inner: SmartTable, + } + + /// Details on the transfer + struct BridgeTransferDetails has store, copy { + addresses: AddressPair, + amount: u64, + hash_lock: vector, + time_lock: u64, + state: u8, + } + + struct Nonce has key { + inner: u64 + } + + /// Initializes the initiators and counterparties tables and nonce. + /// + /// @param aptos_framework The signer for Aptos framework. + public fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, Nonce { + inner: 0, + }); + + let initiators = SmartTableWrapper, BridgeTransferDetails> { + inner: smart_table::new(), + }; + + move_to(aptos_framework, initiators); + + let counterparties = SmartTableWrapper, BridgeTransferDetails> { + inner: smart_table::new(), + }; + + move_to(aptos_framework, counterparties); + } + + /// Returns the current time in seconds. + /// + /// @return Current timestamp in seconds. + fun now() : u64 { + timestamp::now_seconds() + } + + /// Creates a time lock by adding a duration to the current time. + /// + /// @param lock The duration to lock. + /// @return The calculated time lock. + /// @abort If lock is not above MIN_TIME_LOCK + public(friend) fun create_time_lock(time_lock: u64) : u64 { + assert_min_time_lock(time_lock); + now() + time_lock + } + + /// Creates bridge transfer details with validation. + /// + /// @param initiator The initiating party of the transfer. + /// @param recipient The receiving party of the transfer. + /// @param amount The amount to be transferred. + /// @param hash_lock The hash lock for the transfer. + /// @param time_lock The time lock for the transfer. + /// @return A `BridgeTransferDetails` object. + /// @abort If the amount is zero or locks are invalid. + public(friend) fun create_details(initiator: Initiator, recipient: Recipient, amount: u64, hash_lock: vector, time_lock: u64) + : BridgeTransferDetails { + assert!(amount > 0, EZERO_AMOUNT); + assert_valid_hash_lock(&hash_lock); + time_lock = create_time_lock(time_lock); + + BridgeTransferDetails { + addresses: AddressPair { + initiator, + recipient + }, + amount, + hash_lock, + time_lock, + state: PENDING_TRANSACTION, + } + } + + /// Record details of a transfer + /// + /// @param bridge_transfer_id Bridge transfer ID. + /// @param details The bridge transfer details + public(friend) fun add(bridge_transfer_id: vector, details: BridgeTransferDetails) acquires SmartTableWrapper { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + assert_valid_bridge_transfer_id(&bridge_transfer_id); + let table = borrow_global_mut, BridgeTransferDetails>>(@aptos_framework); + smart_table::add(&mut table.inner, bridge_transfer_id, details); + } + + /// Asserts that the time lock is valid. + /// + /// @param time_lock + /// @abort If the time lock is invalid. + fun assert_min_time_lock(time_lock: u64) { + assert!(time_lock >= MIN_TIME_LOCK, EINVALID_TIME_LOCK); + } + + /// Asserts that the details state is pending. + /// + /// @param details The bridge transfer details to check. + /// @abort If the state is not pending. + fun assert_pending(details: &BridgeTransferDetails) { + assert!(details.state == PENDING_TRANSACTION, ENOT_PENDING_TRANSACTION) + } + + /// Asserts that the hash lock is valid. + /// + /// @param hash_lock The hash lock to validate. + /// @abort If the hash lock is invalid. + fun assert_valid_hash_lock(hash_lock: &vector) { + assert!(vector::length(hash_lock) == 32, EINVALID_HASH_LOCK); + } + + /// Asserts that the bridge transfer ID is valid. + /// + /// @param bridge_transfer_id The bridge transfer ID to validate. + /// @abort If the ID is invalid. + public(friend) fun assert_valid_bridge_transfer_id(bridge_transfer_id: &vector) { + assert!(vector::length(bridge_transfer_id) == 32, EINVALID_BRIDGE_TRANSFER_ID); + } + + /// Creates a hash lock from a pre-image. + /// + /// @param pre_image The pre-image to hash. + /// @return The generated hash lock. + public(friend) fun create_hashlock(pre_image: vector) : vector { + assert!(vector::length(&pre_image) > 0, EINVALID_PRE_IMAGE); + keccak256(pre_image) + } + + /// Asserts that the hash lock matches the expected value. + /// + /// @param details The bridge transfer details. + /// @param hash_lock The hash lock to compare. + /// @abort If the hash lock is incorrect. + fun assert_correct_hash_lock(details: &BridgeTransferDetails, hash_lock: vector) { + assert!(&hash_lock == &details.hash_lock, EINVALID_PRE_IMAGE); + } + + /// Asserts that the time lock has expired. + /// + /// @param details The bridge transfer details. + /// @abort If the time lock has not expired. + fun assert_timed_out_lock(details: &BridgeTransferDetails) { + assert!(now() > details.time_lock, ENOT_EXPIRED); + } + + /// Asserts we are still within the timelock. + /// + /// @param details The bridge transfer details. + /// @abort If the time lock has expired. + fun assert_within_timelock(details: &BridgeTransferDetails) { + assert!(!(now() > details.time_lock), EEXPIRED); + } + + /// Completes the bridge transfer. + /// + /// @param details The bridge transfer details to complete. + fun complete(details: &mut BridgeTransferDetails) { + details.state = COMPLETED_TRANSACTION; + } + + /// Cancels the bridge transfer. + /// + /// @param details The bridge transfer details to cancel. + fun cancel(details: &mut BridgeTransferDetails) { + details.state = CANCELLED_TRANSACTION; + } + + /// Validates and completes a bridge transfer by confirming the hash lock and state. + /// + /// @param hash_lock The hash lock used to validate the transfer. + /// @param details The mutable reference to the bridge transfer details to be completed. + /// @return A tuple containing the recipient and the amount of the transfer. + /// @abort If the hash lock is invalid, the transfer is not pending, or the hash lock does not match. + fun complete_details(hash_lock: vector, details: &mut BridgeTransferDetails) : (Recipient, u64) { + assert_valid_hash_lock(&hash_lock); + assert_pending(details); + assert_correct_hash_lock(details, hash_lock); + assert_within_timelock(details); + + complete(details); + + (details.addresses.recipient, details.amount) + } + + /// Completes a bridge transfer by validating the hash lock and updating the transfer state. + /// + /// @param bridge_transfer_id The ID of the bridge transfer to complete. + /// @param hash_lock The hash lock used to validate the transfer. + /// @return A tuple containing the recipient of the transfer and the amount transferred. + /// @abort If the bridge transfer details are not found or if the completion checks in `complete_details` fail. + public(friend) fun complete_transfer(bridge_transfer_id: vector, hash_lock: vector) : (Recipient, u64) acquires SmartTableWrapper { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + let table = borrow_global_mut, BridgeTransferDetails>>(@aptos_framework); + + let details = smart_table::borrow_mut( + &mut table.inner, + bridge_transfer_id); + + complete_details(hash_lock, details) + } + + /// Cancels a pending bridge transfer if the time lock has expired. + /// + /// @param details A mutable reference to the bridge transfer details to be canceled. + /// @return A tuple containing the initiator of the transfer and the amount to be refunded. + /// @abort If the transfer is not in a pending state or the time lock has not expired. + fun cancel_details(details: &mut BridgeTransferDetails) : (Initiator, u64) { + assert_pending(details); + assert_timed_out_lock(details); + + cancel(details); + + (details.addresses.initiator, details.amount) + } + + /// Cancels a bridge transfer if it is pending and the time lock has expired. + /// + /// @param bridge_transfer_id The ID of the bridge transfer to cancel. + /// @return A tuple containing the initiator of the transfer and the amount to be refunded. + /// @abort If the bridge transfer details are not found or if the cancellation conditions in `cancel_details` fail. + public(friend) fun cancel_transfer(bridge_transfer_id: vector) : (Initiator, u64) acquires SmartTableWrapper { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + let table = borrow_global_mut, BridgeTransferDetails>>(@aptos_framework); + + let details = smart_table::borrow_mut( + &mut table.inner, + bridge_transfer_id); + + cancel_details(details) + } + + /// Generates a unique bridge transfer ID based on transfer details and nonce. + /// + /// @param details The bridge transfer details. + /// @return The generated bridge transfer ID. + public(friend) fun bridge_transfer_id(details: &BridgeTransferDetails) : vector acquires Nonce { + let nonce = borrow_global_mut(@aptos_framework); + let combined_bytes = vector::empty(); + vector::append(&mut combined_bytes, bcs::to_bytes(&details.addresses.initiator)); + vector::append(&mut combined_bytes, bcs::to_bytes(&details.addresses.recipient)); + vector::append(&mut combined_bytes, details.hash_lock); + if (nonce.inner == MAX_U64) { + nonce.inner = 0; // Wrap around to 0 if at maximum value + } else { + nonce.inner = nonce.inner + 1; // Safe to increment without overflow + }; + vector::append(&mut combined_bytes, bcs::to_bytes(&nonce.inner)); + + keccak256(combined_bytes) + } + + #[view] + /// Gets initiator bridge transfer details given a bridge transfer ID + /// + /// @param bridge_transfer_id A 32-byte vector of unsigned 8-bit integers. + /// @return A `BridgeTransferDetails` struct. + /// @abort If there is no transfer in the atomic bridge store. + public fun get_bridge_transfer_details_initiator( + bridge_transfer_id: vector + ): BridgeTransferDetails acquires SmartTableWrapper { + get_bridge_transfer_details(bridge_transfer_id) + } + + #[view] + /// Gets counterparty bridge transfer details given a bridge transfer ID + /// + /// @param bridge_transfer_id A 32-byte vector of unsigned 8-bit integers. + /// @return A `BridgeTransferDetails` struct. + /// @abort If there is no transfer in the atomic bridge store. + public fun get_bridge_transfer_details_counterparty( + bridge_transfer_id: vector + ): BridgeTransferDetails acquires SmartTableWrapper { + get_bridge_transfer_details(bridge_transfer_id) + } + + fun get_bridge_transfer_details(bridge_transfer_id: vector + ): BridgeTransferDetails acquires SmartTableWrapper { + let table = borrow_global, BridgeTransferDetails>>(@aptos_framework); + + let details_ref = smart_table::borrow( + &table.inner, + bridge_transfer_id + ); + + *details_ref + } + + #[test_only] + public fun valid_bridge_transfer_id() : vector { + sha3_256(b"atomic bridge") + } + + #[test_only] + public fun plain_secret() : vector { + b"too secret!" + } + + #[test_only] + public fun valid_hash_lock() : vector { + keccak256(plain_secret()) + } + + + #[test(aptos_framework = @aptos_framework)] + public fun test_get_bridge_transfer_details_initiator(aptos_framework: &signer) acquires SmartTableWrapper { + timestamp::set_time_has_started_for_testing(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + atomic_bridge_configuration::initialize(aptos_framework); + initialize(aptos_framework); + + let initiator = signer::address_of(aptos_framework); + let recipient = ethereum::ethereum_address(ethereum::valid_eip55()); + let amount = 1000; + let hash_lock = valid_hash_lock(); + let time_lock = create_time_lock(3600); + let bridge_transfer_id = valid_bridge_transfer_id(); + + let details = create_details( + initiator, + recipient, + amount, + hash_lock, + time_lock + ); + + add(bridge_transfer_id, details); + + let retrieved_details = get_bridge_transfer_details_initiator(bridge_transfer_id); + + let BridgeTransferDetails { + addresses: AddressPair { + initiator: retrieved_initiator, + recipient: retrieved_recipient + }, + amount: retrieved_amount, + hash_lock: retrieved_hash_lock, + time_lock: retrieved_time_lock, + state: retrieved_state + } = retrieved_details; + + assert!(retrieved_initiator == initiator, 0); + assert!(retrieved_recipient == recipient, 1); + assert!(retrieved_amount == amount, 2); + assert!(retrieved_hash_lock == hash_lock, 3); + assert!(retrieved_time_lock == time_lock, 4); + assert!(retrieved_state == PENDING_TRANSACTION, 5); + } + + #[test(aptos_framework = @aptos_framework)] + public fun test_get_bridge_transfer_details_counterparty(aptos_framework: &signer) acquires SmartTableWrapper { + timestamp::set_time_has_started_for_testing(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + initialize(aptos_framework); + + let initiator = ethereum::ethereum_address(ethereum::valid_eip55()); + let recipient = signer::address_of(aptos_framework); + let amount = 500; + let hash_lock = valid_hash_lock(); + let time_lock = create_time_lock(3600); + let bridge_transfer_id = valid_bridge_transfer_id(); + + let details = create_details( + initiator, + recipient, + amount, + hash_lock, + time_lock + ); + + add(bridge_transfer_id, details); + + let retrieved_details = get_bridge_transfer_details_counterparty(bridge_transfer_id); + + let BridgeTransferDetails { + addresses: AddressPair { + initiator: retrieved_initiator, + recipient: retrieved_recipient + }, + amount: retrieved_amount, + hash_lock: retrieved_hash_lock, + time_lock: retrieved_time_lock, + state: retrieved_state + } = retrieved_details; + + assert!(retrieved_initiator == initiator, 0); + assert!(retrieved_recipient == recipient, 1); + assert!(retrieved_amount == amount, 2); + assert!(retrieved_hash_lock == hash_lock, 3); + assert!(retrieved_time_lock == time_lock, 4); + assert!(retrieved_state == PENDING_TRANSACTION, 5); + } +} + +module aptos_framework::atomic_bridge_configuration { + use std::signer; + use aptos_framework::event; + use aptos_framework::system_addresses; + + friend aptos_framework::atomic_bridge_counterparty; + friend aptos_framework::atomic_bridge_initiator; + + /// Error code for invalid bridge operator + const EINVALID_BRIDGE_OPERATOR: u64 = 0x1; + + /// Counterparty time lock duration is 24 hours in seconds + const COUNTERPARTY_TIME_LOCK_DUARTION: u64 = 24 * 60 * 60; + /// Initiator time lock duration is 48 hours in seconds + const INITIATOR_TIME_LOCK_DUARTION: u64 = 48 * 60 * 60; + + struct BridgeConfig has key { + bridge_operator: address, + initiator_time_lock: u64, + counterparty_time_lock: u64, + } + + #[event] + /// Event emitted when the bridge operator is updated. + struct BridgeConfigOperatorUpdated has store, drop { + old_operator: address, + new_operator: address, + } + + #[event] + /// Event emitted when the initiator time lock has been updated. + struct InitiatorTimeLockUpdated has store, drop { + time_lock: u64, + } + + #[event] + /// Event emitted when the initiator time lock has been updated. + struct CounterpartyTimeLockUpdated has store, drop { + time_lock: u64, + } + + /// Initializes the bridge configuration with Aptos framework as the bridge operator. + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + let bridge_config = BridgeConfig { + bridge_operator: signer::address_of(aptos_framework), + initiator_time_lock: INITIATOR_TIME_LOCK_DUARTION, + counterparty_time_lock: COUNTERPARTY_TIME_LOCK_DUARTION, + }; + move_to(aptos_framework, bridge_config); + } + + /// Updates the bridge operator, requiring governance validation. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param new_operator The new address to be set as the bridge operator. + /// @abort If the current operator is the same as the new operator. + public fun update_bridge_operator(aptos_framework: &signer, new_operator: address + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + let bridge_config = borrow_global_mut(@aptos_framework); + let old_operator = bridge_config.bridge_operator; + assert!(old_operator != new_operator, EINVALID_BRIDGE_OPERATOR); + + bridge_config.bridge_operator = new_operator; + + event::emit( + BridgeConfigOperatorUpdated { + old_operator, + new_operator, + }, + ); + } + + public fun set_initiator_time_lock_duration(aptos_framework: &signer, time_lock: u64 + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + borrow_global_mut(@aptos_framework).initiator_time_lock = time_lock; + + event::emit( + InitiatorTimeLockUpdated { + time_lock + }, + ); + } + + public fun set_counterparty_time_lock_duration(aptos_framework: &signer, time_lock: u64 + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + borrow_global_mut(@aptos_framework).counterparty_time_lock = time_lock; + + event::emit( + CounterpartyTimeLockUpdated { + time_lock + }, + ); + } + + #[view] + public fun initiator_timelock_duration() : u64 acquires BridgeConfig { + borrow_global(@aptos_framework).initiator_time_lock + } + + #[view] + public fun counterparty_timelock_duration() : u64 acquires BridgeConfig { + borrow_global(@aptos_framework).counterparty_time_lock + } + + #[view] + /// Retrieves the address of the current bridge operator. + /// + /// @return The address of the current bridge operator. + public fun bridge_operator(): address acquires BridgeConfig { + borrow_global_mut(@aptos_framework).bridge_operator + } + + /// Asserts that the caller is the current bridge operator. + /// + /// @param caller The signer whose authority is being checked. + /// @abort If the caller is not the current bridge operator. + public(friend) fun assert_is_caller_operator(caller: &signer + ) acquires BridgeConfig { + assert!(borrow_global(@aptos_framework).bridge_operator == signer::address_of(caller), EINVALID_BRIDGE_OPERATOR); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests initialization of the bridge configuration. + fun test_initialization(aptos_framework: &signer) { + initialize(aptos_framework); + assert!(exists(@aptos_framework), 0); + } + + #[test(aptos_framework = @aptos_framework, new_operator = @0xcafe)] + /// Tests updating the bridge operator and emitting the corresponding event. + fun test_update_bridge_operator(aptos_framework: &signer, new_operator: address + ) acquires BridgeConfig { + initialize(aptos_framework); + update_bridge_operator(aptos_framework, new_operator); + + assert!( + event::was_event_emitted( + &BridgeConfigOperatorUpdated { + old_operator: @aptos_framework, + new_operator, + } + ), 0); + + assert!(bridge_operator() == new_operator, 0); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad, new_operator = @0xcafe)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that updating the bridge operator with an invalid signer fails. + fun test_failing_update_bridge_operator(aptos_framework: &signer, bad: &signer, new_operator: address + ) acquires BridgeConfig { + initialize(aptos_framework); + update_bridge_operator(bad, new_operator); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests that the correct operator is validated successfully. + fun test_is_valid_operator(aptos_framework: &signer) acquires BridgeConfig { + initialize(aptos_framework); + assert_is_caller_operator(aptos_framework); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 0x1, location = 0x1::atomic_bridge_configuration)] + /// Tests that an incorrect operator is not validated and results in an abort. + fun test_is_not_valid_operator(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize(aptos_framework); + assert_is_caller_operator(bad); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests we can update the initiator time lock + fun test_update_initiator_time_lock(aptos_framework: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_initiator_time_lock_duration(aptos_framework, 1); + assert!(initiator_timelock_duration() == 1, 0); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests we can update the initiator time lock + fun test_update_counterparty_time_lock(aptos_framework: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_counterparty_time_lock_duration(aptos_framework, 1); + assert!(counterparty_timelock_duration() == 1, 0); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that an incorrect signer cannot update the initiator time lock + fun test_not_able_to_set_initiator_time_lock(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_initiator_time_lock_duration(bad, 1); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that an incorrect signer cannot update the counterparty time lock + fun test_not_able_to_set_counterparty_time_lock(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_counterparty_time_lock_duration(bad, 1); + } +} + +module aptos_framework::atomic_bridge { + use std::features; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::atomic_bridge_configuration; + use aptos_framework::atomic_bridge_store; + use aptos_framework::coin; + use aptos_framework::coin::{BurnCapability, MintCapability}; + use aptos_framework::fungible_asset::{BurnRef, MintRef}; + use aptos_framework::system_addresses; + #[test_only] + use aptos_framework::account; + #[test_only] + use aptos_framework::aptos_coin; + #[test_only] + use aptos_framework::timestamp; + + friend aptos_framework::atomic_bridge_counterparty; + friend aptos_framework::atomic_bridge_initiator; + friend aptos_framework::genesis; + + const EATOMIC_BRIDGE_NOT_ENABLED : u64 = 0x1; + + struct AptosCoinBurnCapability has key { + burn_cap: BurnCapability, + } + + struct AptosCoinMintCapability has key { + mint_cap: MintCapability, + } + + struct AptosFABurnCapabilities has key { + burn_ref: BurnRef, + } + + struct AptosFAMintCapabilities has key { + burn_ref: MintRef, + } + + /// Initializes the atomic bridge by setting up necessary configurations. + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize(aptos_framework: &signer) { + atomic_bridge_configuration::initialize(aptos_framework); + atomic_bridge_store::initialize(aptos_framework); + } + + #[test_only] + /// Initializes the atomic bridge for testing purposes, including setting up accounts and timestamps. + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize_for_test(aptos_framework: &signer) { + timestamp::set_time_has_started_for_testing(aptos_framework); + account::create_account_for_test(@aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + initialize(aptos_framework); + + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(aptos_framework); + + store_aptos_coin_mint_cap(aptos_framework, mint_cap); + store_aptos_coin_burn_cap(aptos_framework, burn_cap); + } + + /// Stores the burn capability for AptosCoin, converting to a fungible asset reference if the feature is enabled. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param burn_cap The burn capability for AptosCoin. + public fun store_aptos_coin_burn_cap(aptos_framework: &signer, burn_cap: BurnCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + if (features::operations_default_to_fa_apt_store_enabled()) { + let burn_ref = coin::convert_and_take_paired_burn_ref(burn_cap); + move_to(aptos_framework, AptosFABurnCapabilities { burn_ref }); + } else { + move_to(aptos_framework, AptosCoinBurnCapability { burn_cap }) + } + } + + /// Stores the mint capability for AptosCoin. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param mint_cap The mint capability for AptosCoin. + public fun store_aptos_coin_mint_cap(aptos_framework: &signer, mint_cap: MintCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, AptosCoinMintCapability { mint_cap }) + } + + /// Mints a specified amount of AptosCoin to a recipient's address. + /// + /// @param recipient The address of the recipient to mint coins to. + /// @param amount The amount of AptosCoin to mint. + /// @abort If the mint capability is not available. + public(friend) fun mint(recipient: address, amount: u64) acquires AptosCoinMintCapability { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + coin::deposit(recipient, coin::mint( + amount, + &borrow_global(@aptos_framework).mint_cap + )); + } + + /// Burns a specified amount of AptosCoin from an address. + /// + /// @param from The address from which to burn AptosCoin. + /// @param amount The amount of AptosCoin to burn. + /// @abort If the burn capability is not available. + public(friend) fun burn(from: address, amount: u64) acquires AptosCoinBurnCapability { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + coin::burn_from( + from, + amount, + &borrow_global(@aptos_framework).burn_cap, + ); + } +} + +module aptos_framework::atomic_bridge_counterparty { + use aptos_framework::account; + use aptos_framework::atomic_bridge; + use aptos_framework::atomic_bridge_configuration; + use aptos_framework::atomic_bridge_store; + use aptos_framework::atomic_bridge_store::create_hashlock; + use aptos_framework::ethereum; + use aptos_framework::ethereum::EthereumAddress; + use aptos_framework::event::{Self, EventHandle}; + #[test_only] + use aptos_framework::aptos_account; + #[test_only] + use aptos_framework::atomic_bridge::initialize_for_test; + #[test_only] + use aptos_framework::atomic_bridge_store::{valid_bridge_transfer_id, valid_hash_lock, plain_secret}; + #[test_only] + use aptos_framework::ethereum::valid_eip55; + #[test_only] + use aptos_framework::signer; + #[test_only] + use aptos_framework::timestamp; + + #[event] + /// An event triggered upon locking assets for a bridge transfer + struct BridgeTransferLockedEvent has store, drop { + bridge_transfer_id: vector, + initiator: vector, + recipient: address, + amount: u64, + hash_lock: vector, + time_lock: u64, + } + + #[event] + /// An event triggered upon completing a bridge transfer + struct BridgeTransferCompletedEvent has store, drop { + bridge_transfer_id: vector, + pre_image: vector, + } + + #[event] + /// An event triggered upon cancelling a bridge transfer + struct BridgeTransferCancelledEvent has store, drop { + bridge_transfer_id: vector, + } + + /// This struct will store the event handles for bridge events. + struct BridgeCounterpartyEvents has key, store { + bridge_transfer_locked_events: EventHandle, + bridge_transfer_completed_events: EventHandle, + bridge_transfer_cancelled_events: EventHandle, + } + + /// Initializes the module and stores the `EventHandle`s in the resource. + public fun initialize(aptos_framework: &signer) { + move_to(aptos_framework, BridgeCounterpartyEvents { + bridge_transfer_locked_events: account::new_event_handle(aptos_framework), + bridge_transfer_completed_events: account::new_event_handle(aptos_framework), + bridge_transfer_cancelled_events: account::new_event_handle(aptos_framework), + }); + } + + /// Locks assets for a bridge transfer by the initiator. + /// + /// @param caller The signer representing the bridge operator. + /// @param initiator The initiator's Ethereum address as a vector of bytes. + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @param hash_lock The hash lock for securing the transfer. + /// @param time_lock The time lock duration for the transfer. + /// @param recipient The address of the recipient on the Aptos blockchain. + /// @param amount The amount of assets to be locked. + /// @abort If the caller is not the bridge operator. + public entry fun lock_bridge_transfer_assets ( + caller: &signer, + initiator: vector, + bridge_transfer_id: vector, + hash_lock: vector, + recipient: address, + amount: u64 + ) acquires BridgeCounterpartyEvents { + atomic_bridge_configuration::assert_is_caller_operator(caller); + let ethereum_address = ethereum::ethereum_address_no_eip55(initiator); + let time_lock = atomic_bridge_configuration::counterparty_timelock_duration(); + let details = atomic_bridge_store::create_details( + ethereum_address, + recipient, + amount, + hash_lock, + time_lock + ); + + // bridge_store::add_counterparty(bridge_transfer_id, details); + atomic_bridge_store::add(bridge_transfer_id, details); + + let bridge_events = borrow_global_mut(@aptos_framework); + + event::emit_event( + &mut bridge_events.bridge_transfer_locked_events, + BridgeTransferLockedEvent { + bridge_transfer_id, + initiator, + recipient, + amount, + hash_lock, + time_lock, + }, + ); + } + + /// Completes a bridge transfer by revealing the pre-image. + /// + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @param pre_image The pre-image that matches the hash lock to complete the transfer. + /// @abort If the caller is not the bridge operator or the hash lock validation fails. + public entry fun complete_bridge_transfer ( + bridge_transfer_id: vector, + pre_image: vector, + ) acquires BridgeCounterpartyEvents { + let (recipient, amount) = atomic_bridge_store::complete_transfer( + bridge_transfer_id, + create_hashlock(pre_image) + ); + + // Mint, fails silently + atomic_bridge::mint(recipient, amount); + + let bridge_counterparty_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_counterparty_events.bridge_transfer_completed_events, + BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image, + }, + ); + } + + /// Aborts a bridge transfer if the time lock has expired. + /// + /// @param caller The signer representing the bridge operator. + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @abort If the caller is not the bridge operator or if the time lock has not expired. + public entry fun abort_bridge_transfer ( + caller: &signer, + bridge_transfer_id: vector + ) acquires BridgeCounterpartyEvents { + atomic_bridge_configuration::assert_is_caller_operator(caller); + + atomic_bridge_store::cancel_transfer(bridge_transfer_id); + + let bridge_counterparty_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_counterparty_events.bridge_transfer_cancelled_events, + BridgeTransferCancelledEvent { + bridge_transfer_id, + }, + ); + } + + #[test(aptos_framework = @aptos_framework)] + fun test_lock_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + let bridge_counterparty_events = borrow_global(signer::address_of(aptos_framework)); + let lock_events = event::emitted_events_by_handle(&bridge_counterparty_events.bridge_transfer_locked_events); + + // Assert that the event was emitted + let expected_event = BridgeTransferLockedEvent { + bridge_transfer_id, + initiator, + recipient, + amount, + hash_lock, + time_lock: atomic_bridge_configuration::counterparty_timelock_duration(), + }; + assert!(std::vector::contains(&lock_events, &expected_event), 0); + + } + + #[test(aptos_framework = @aptos_framework)] + fun test_abort_transfer_of_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + timestamp::fast_forward_seconds(atomic_bridge_configuration::counterparty_timelock_duration() + 1); + abort_bridge_transfer(aptos_framework, bridge_transfer_id); + + let bridge_counterparty_events = borrow_global(signer::address_of(aptos_framework)); + let cancel_events = event::emitted_events_by_handle(&bridge_counterparty_events.bridge_transfer_cancelled_events); + let expected_event = BridgeTransferCancelledEvent { bridge_transfer_id }; + assert!(std::vector::contains(&cancel_events, &expected_event), 0); + } + + #[test(aptos_framework = @aptos_framework)] + fun test_complete_transfer_of_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + // Create an account for our recipient + aptos_account::create_account(recipient); + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + complete_bridge_transfer(bridge_transfer_id, plain_secret()); + + let bridge_counterparty_events = borrow_global(signer::address_of(aptos_framework)); + let complete_events = event::emitted_events_by_handle(&bridge_counterparty_events.bridge_transfer_completed_events); + let expected_event = BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image: plain_secret(), + }; + assert!(std::vector::contains(&complete_events, &expected_event), 0); + + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x1, location = atomic_bridge_store)] + fun test_failing_complete_transfer_of_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + complete_bridge_transfer(bridge_transfer_id, b"not the secret"); + } +} + diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/atomic_bridge_initiator.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/atomic_bridge_initiator.move new file mode 100644 index 000000000..ff1d9851a --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/atomic_bridge_initiator.move @@ -0,0 +1,1523 @@ +module aptos_framework::atomic_bridge_initiator { + use aptos_framework::account; + use aptos_framework::atomic_bridge; + use aptos_framework::atomic_bridge_configuration; + use aptos_framework::atomic_bridge_configuration::assert_is_caller_operator; + use aptos_framework::atomic_bridge_store; + use aptos_framework::atomic_bridge_store::{create_hashlock, bridge_transfer_id}; + use aptos_framework::ethereum; + use aptos_framework::ethereum::EthereumAddress; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::signer; + #[test_only] + use std::vector; + #[test_only] + use aptos_framework::aptos_account; + #[test_only] + use aptos_framework::aptos_coin::AptosCoin; + #[test_only] + use aptos_framework::atomic_bridge_store::{valid_hash_lock, assert_valid_bridge_transfer_id, plain_secret}; + #[test_only] + use aptos_framework::coin; + #[test_only] + use aptos_framework::ethereum::valid_eip55; + #[test_only] + use aptos_framework::timestamp; + + #[event] + struct BridgeTransferInitiatedEvent has store, drop { + bridge_transfer_id: vector, + initiator: address, + recipient: vector, + amount: u64, + hash_lock: vector, + time_lock: u64, + } + + #[event] + struct BridgeTransferCompletedEvent has store, drop { + bridge_transfer_id: vector, + pre_image: vector, + } + + #[event] + struct BridgeTransferRefundedEvent has store, drop { + bridge_transfer_id: vector, + } + + /// This struct will store the event handles for bridge events. + struct BridgeInitiatorEvents has key, store { + bridge_transfer_initiated_events: EventHandle, + bridge_transfer_completed_events: EventHandle, + bridge_transfer_refunded_events: EventHandle, + } + + /// Initializes the module and stores the `EventHandle`s in the resource. + public fun initialize(aptos_framework: &signer) { + move_to(aptos_framework, BridgeInitiatorEvents { + bridge_transfer_initiated_events: account::new_event_handle(aptos_framework), + bridge_transfer_completed_events: account::new_event_handle(aptos_framework), + bridge_transfer_refunded_events: account::new_event_handle(aptos_framework), + }); + } + + /// Initiate a bridge transfer of ETH from Movement to the base layer + /// Anyone can initiate a bridge transfer from the source chain + /// The amount is burnt from the initiator + public entry fun initiate_bridge_transfer( + initiator: &signer, + recipient: vector, + hash_lock: vector, + amount: u64 + ) acquires BridgeInitiatorEvents { + let ethereum_address = ethereum::ethereum_address_no_eip55(recipient); + let initiator_address = signer::address_of(initiator); + let time_lock = atomic_bridge_configuration::initiator_timelock_duration(); + + let details = + atomic_bridge_store::create_details( + initiator_address, + ethereum_address, amount, + hash_lock, + time_lock + ); + + let bridge_transfer_id = bridge_transfer_id(&details); + atomic_bridge_store::add(bridge_transfer_id, details); + atomic_bridge::burn(initiator_address, amount); + + let bridge_initiator_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_initiator_events.bridge_transfer_initiated_events, + BridgeTransferInitiatedEvent { + bridge_transfer_id, + initiator: initiator_address, + recipient, + amount, + hash_lock, + time_lock + }, + ); + } + + /// Bridge operator can complete the transfer + public entry fun complete_bridge_transfer ( + caller: &signer, + bridge_transfer_id: vector, + pre_image: vector, + ) acquires BridgeInitiatorEvents { + assert_is_caller_operator(caller); + let (_, _) = atomic_bridge_store::complete_transfer(bridge_transfer_id, create_hashlock(pre_image)); + + let bridge_initiator_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_initiator_events.bridge_transfer_completed_events, + BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image, + }, + ); + } + + /// Anyone can refund the transfer on the source chain once time lock has passed + public entry fun refund_bridge_transfer ( + _caller: &signer, + bridge_transfer_id: vector, + ) acquires BridgeInitiatorEvents { + let (receiver, amount) = atomic_bridge_store::cancel_transfer(bridge_transfer_id); + atomic_bridge::mint(receiver, amount); + + let bridge_initiator_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_initiator_events.bridge_transfer_refunded_events, + BridgeTransferRefundedEvent { + bridge_transfer_id, + }, + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + fun test_initiate_bridge_transfer( + sender: &signer, + aptos_framework: &signer, + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + initialize(aptos_framework); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let time_lock = atomic_bridge_configuration::initiator_timelock_duration(); + let amount = 1000; + + // Mint some coins + atomic_bridge::mint(sender_address, amount + 1); + + assert!(coin::balance(sender_address) == amount + 1, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + assert!(coin::balance(sender_address) == 1, 0); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + assert_valid_bridge_transfer_id(&bridge_transfer_initiated_event.bridge_transfer_id); + assert!(bridge_transfer_initiated_event.recipient == recipient, 0); + assert!(bridge_transfer_initiated_event.amount == amount, 0); + assert!(bridge_transfer_initiated_event.initiator == sender_address, 0); + assert!(bridge_transfer_initiated_event.hash_lock == hash_lock, 0); + assert!(bridge_transfer_initiated_event.time_lock == time_lock, 0); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x10006, location = 0x1::coin)] //EINSUFFICIENT_BALANCE + fun test_initiate_bridge_transfer_insufficient_balance( + sender: &signer, + aptos_framework: &signer, + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + fun test_complete_bridge_transfer( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + let account_balance = amount + 1; + + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + plain_secret(), + ); + + let bridge_initiator_events = borrow_global(signer::address_of(aptos_framework)); + let complete_events = event::emitted_events_by_handle(&bridge_initiator_events.bridge_transfer_completed_events); + let expected_event = BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image: plain_secret(), + }; + assert!(std::vector::contains(&complete_events, &expected_event), 0); + + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x1, location = 0x1::atomic_bridge_configuration)] // EINVALID_BRIDGE_OPERATOR + fun test_complete_bridge_transfer_by_sender( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + let account_balance = amount + 1; + + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + complete_bridge_transfer( + sender, + bridge_transfer_id, + plain_secret(), + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x1, location = 0x1::atomic_bridge_store)] // EINVALID_PRE_IMAGE + fun test_complete_bridge_transfer_with_invalid_preimage( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + let account_balance = amount + 1; + + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + b"bad secret", + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x10001, location = 0x1::smart_table)] // ENOT_FOUND + fun test_complete_bridge_with_errorneous_bridge_id_by_operator( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + + let bridge_transfer_id = b"guessing the id"; + + // As operator I send a complete request and it should fail + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + plain_secret(), + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + fun test_refund_bridge_transfer( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + let account_balance = amount + 1; + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + assert!(coin::balance(sender_address) == account_balance - amount, 0); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + timestamp::fast_forward_seconds(atomic_bridge_configuration::initiator_timelock_duration() + 1); + + refund_bridge_transfer(sender, bridge_transfer_id); + + assert!(coin::balance(sender_address) == account_balance, 0); + + let bridge_initiator_events = borrow_global(signer::address_of(aptos_framework)); + let refund_events = event::emitted_events_by_handle(&bridge_initiator_events.bridge_transfer_refunded_events); + let expected_event = BridgeTransferRefundedEvent { bridge_transfer_id }; + let was_event_emitted = std::vector::contains(&refund_events, &expected_event); + + assert!(was_event_emitted, 0); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x4, location = 0x1::atomic_bridge_store)] //ENOT_EXPIRED + fun test_refund_bridge_transfer_before_timelock( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + let account_balance = amount + 1; + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + assert!(coin::balance(sender_address) == account_balance - amount, 0); + + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + refund_bridge_transfer(sender, bridge_transfer_id); + } +} + +module aptos_framework::atomic_bridge_store { + use std::bcs; + use std::features; + use std::vector; + use aptos_std::aptos_hash::keccak256; + use aptos_std::smart_table; + use aptos_std::smart_table::SmartTable; + use aptos_framework::ethereum::EthereumAddress; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + use std::signer; + use aptos_framework::timestamp::CurrentTimeMicroseconds; + + friend aptos_framework::atomic_bridge_counterparty; + friend aptos_framework::atomic_bridge_initiator; + + #[test_only] + use std::hash::sha3_256; + #[test_only] + use aptos_framework::ethereum; + #[test_only] + use aptos_framework::atomic_bridge_configuration; + + /// Error codes + const EINVALID_PRE_IMAGE : u64 = 0x1; + const ENOT_PENDING_TRANSACTION : u64 = 0x2; + const EEXPIRED : u64 = 0x3; + const ENOT_EXPIRED : u64 = 0x4; + const EINVALID_HASH_LOCK : u64 = 0x5; + const EINVALID_TIME_LOCK : u64 = 0x6; + const EZERO_AMOUNT : u64 = 0x7; + const EINVALID_BRIDGE_TRANSFER_ID : u64 = 0x8; + const EATOMIC_BRIDGE_NOT_ENABLED : u64 = 0x9; + + /// Transaction states + const PENDING_TRANSACTION: u8 = 0x1; + const COMPLETED_TRANSACTION: u8 = 0x2; + const CANCELLED_TRANSACTION: u8 = 0x3; + + /// Minimum time lock of 1 second + const MIN_TIME_LOCK : u64 = 1; + const MAX_U64 : u64 = 0xFFFFFFFFFFFFFFFF; + + struct AddressPair has store, copy { + initiator: Initiator, + recipient: Recipient, + } + + /// A smart table wrapper + struct SmartTableWrapper has key, store { + inner: SmartTable, + } + + /// Details on the transfer + struct BridgeTransferDetails has store, copy { + addresses: AddressPair, + amount: u64, + hash_lock: vector, + time_lock: u64, + state: u8, + } + + struct Nonce has key { + inner: u64 + } + + /// Initializes the initiators and counterparties tables and nonce. + /// + /// @param aptos_framework The signer for Aptos framework. + public fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, Nonce { + inner: 0, + }); + + let initiators = SmartTableWrapper, BridgeTransferDetails> { + inner: smart_table::new(), + }; + + move_to(aptos_framework, initiators); + + let counterparties = SmartTableWrapper, BridgeTransferDetails> { + inner: smart_table::new(), + }; + + move_to(aptos_framework, counterparties); + } + + /// Returns the current time in seconds. + /// + /// @return Current timestamp in seconds. + fun now() : u64 { + timestamp::now_seconds() + } + + /// Creates a time lock by adding a duration to the current time. + /// + /// @param lock The duration to lock. + /// @return The calculated time lock. + /// @abort If lock is not above MIN_TIME_LOCK + public(friend) fun create_time_lock(time_lock: u64) : u64 { + assert_min_time_lock(time_lock); + now() + time_lock + } + + /// Creates bridge transfer details with validation. + /// + /// @param initiator The initiating party of the transfer. + /// @param recipient The receiving party of the transfer. + /// @param amount The amount to be transferred. + /// @param hash_lock The hash lock for the transfer. + /// @param time_lock The time lock for the transfer. + /// @return A `BridgeTransferDetails` object. + /// @abort If the amount is zero or locks are invalid. + public(friend) fun create_details(initiator: Initiator, recipient: Recipient, amount: u64, hash_lock: vector, time_lock: u64) + : BridgeTransferDetails { + assert!(amount > 0, EZERO_AMOUNT); + assert_valid_hash_lock(&hash_lock); + time_lock = create_time_lock(time_lock); + + BridgeTransferDetails { + addresses: AddressPair { + initiator, + recipient + }, + amount, + hash_lock, + time_lock, + state: PENDING_TRANSACTION, + } + } + + /// Record details of a transfer + /// + /// @param bridge_transfer_id Bridge transfer ID. + /// @param details The bridge transfer details + public(friend) fun add(bridge_transfer_id: vector, details: BridgeTransferDetails) acquires SmartTableWrapper { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + assert_valid_bridge_transfer_id(&bridge_transfer_id); + let table = borrow_global_mut, BridgeTransferDetails>>(@aptos_framework); + smart_table::add(&mut table.inner, bridge_transfer_id, details); + } + + /// Asserts that the time lock is valid. + /// + /// @param time_lock + /// @abort If the time lock is invalid. + fun assert_min_time_lock(time_lock: u64) { + assert!(time_lock >= MIN_TIME_LOCK, EINVALID_TIME_LOCK); + } + + /// Asserts that the details state is pending. + /// + /// @param details The bridge transfer details to check. + /// @abort If the state is not pending. + fun assert_pending(details: &BridgeTransferDetails) { + assert!(details.state == PENDING_TRANSACTION, ENOT_PENDING_TRANSACTION) + } + + /// Asserts that the hash lock is valid. + /// + /// @param hash_lock The hash lock to validate. + /// @abort If the hash lock is invalid. + fun assert_valid_hash_lock(hash_lock: &vector) { + assert!(vector::length(hash_lock) == 32, EINVALID_HASH_LOCK); + } + + /// Asserts that the bridge transfer ID is valid. + /// + /// @param bridge_transfer_id The bridge transfer ID to validate. + /// @abort If the ID is invalid. + public(friend) fun assert_valid_bridge_transfer_id(bridge_transfer_id: &vector) { + assert!(vector::length(bridge_transfer_id) == 32, EINVALID_BRIDGE_TRANSFER_ID); + } + + /// Creates a hash lock from a pre-image. + /// + /// @param pre_image The pre-image to hash. + /// @return The generated hash lock. + public(friend) fun create_hashlock(pre_image: vector) : vector { + assert!(vector::length(&pre_image) > 0, EINVALID_PRE_IMAGE); + keccak256(pre_image) + } + + /// Asserts that the hash lock matches the expected value. + /// + /// @param details The bridge transfer details. + /// @param hash_lock The hash lock to compare. + /// @abort If the hash lock is incorrect. + fun assert_correct_hash_lock(details: &BridgeTransferDetails, hash_lock: vector) { + assert!(&hash_lock == &details.hash_lock, EINVALID_PRE_IMAGE); + } + + /// Asserts that the time lock has expired. + /// + /// @param details The bridge transfer details. + /// @abort If the time lock has not expired. + fun assert_timed_out_lock(details: &BridgeTransferDetails) { + assert!(now() > details.time_lock, ENOT_EXPIRED); + } + + /// Asserts we are still within the timelock. + /// + /// @param details The bridge transfer details. + /// @abort If the time lock has expired. + fun assert_within_timelock(details: &BridgeTransferDetails) { + assert!(!(now() > details.time_lock), EEXPIRED); + } + + /// Completes the bridge transfer. + /// + /// @param details The bridge transfer details to complete. + fun complete(details: &mut BridgeTransferDetails) { + details.state = COMPLETED_TRANSACTION; + } + + /// Cancels the bridge transfer. + /// + /// @param details The bridge transfer details to cancel. + fun cancel(details: &mut BridgeTransferDetails) { + details.state = CANCELLED_TRANSACTION; + } + + /// Validates and completes a bridge transfer by confirming the hash lock and state. + /// + /// @param hash_lock The hash lock used to validate the transfer. + /// @param details The mutable reference to the bridge transfer details to be completed. + /// @return A tuple containing the recipient and the amount of the transfer. + /// @abort If the hash lock is invalid, the transfer is not pending, or the hash lock does not match. + fun complete_details(hash_lock: vector, details: &mut BridgeTransferDetails) : (Recipient, u64) { + assert_valid_hash_lock(&hash_lock); + assert_pending(details); + assert_correct_hash_lock(details, hash_lock); + assert_within_timelock(details); + + complete(details); + + (details.addresses.recipient, details.amount) + } + + /// Completes a bridge transfer by validating the hash lock and updating the transfer state. + /// + /// @param bridge_transfer_id The ID of the bridge transfer to complete. + /// @param hash_lock The hash lock used to validate the transfer. + /// @return A tuple containing the recipient of the transfer and the amount transferred. + /// @abort If the bridge transfer details are not found or if the completion checks in `complete_details` fail. + public(friend) fun complete_transfer(bridge_transfer_id: vector, hash_lock: vector) : (Recipient, u64) acquires SmartTableWrapper { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + let table = borrow_global_mut, BridgeTransferDetails>>(@aptos_framework); + + let details = smart_table::borrow_mut( + &mut table.inner, + bridge_transfer_id); + + complete_details(hash_lock, details) + } + + /// Cancels a pending bridge transfer if the time lock has expired. + /// + /// @param details A mutable reference to the bridge transfer details to be canceled. + /// @return A tuple containing the initiator of the transfer and the amount to be refunded. + /// @abort If the transfer is not in a pending state or the time lock has not expired. + fun cancel_details(details: &mut BridgeTransferDetails) : (Initiator, u64) { + assert_pending(details); + assert_timed_out_lock(details); + + cancel(details); + + (details.addresses.initiator, details.amount) + } + + /// Cancels a bridge transfer if it is pending and the time lock has expired. + /// + /// @param bridge_transfer_id The ID of the bridge transfer to cancel. + /// @return A tuple containing the initiator of the transfer and the amount to be refunded. + /// @abort If the bridge transfer details are not found or if the cancellation conditions in `cancel_details` fail. + public(friend) fun cancel_transfer(bridge_transfer_id: vector) : (Initiator, u64) acquires SmartTableWrapper { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + let table = borrow_global_mut, BridgeTransferDetails>>(@aptos_framework); + + let details = smart_table::borrow_mut( + &mut table.inner, + bridge_transfer_id); + + cancel_details(details) + } + + /// Generates a unique bridge transfer ID based on transfer details and nonce. + /// + /// @param details The bridge transfer details. + /// @return The generated bridge transfer ID. + public(friend) fun bridge_transfer_id(details: &BridgeTransferDetails) : vector acquires Nonce { + let nonce = borrow_global_mut(@aptos_framework); + let combined_bytes = vector::empty(); + vector::append(&mut combined_bytes, bcs::to_bytes(&details.addresses.initiator)); + vector::append(&mut combined_bytes, bcs::to_bytes(&details.addresses.recipient)); + vector::append(&mut combined_bytes, details.hash_lock); + if (nonce.inner == MAX_U64) { + nonce.inner = 0; // Wrap around to 0 if at maximum value + } else { + nonce.inner = nonce.inner + 1; // Safe to increment without overflow + }; + vector::append(&mut combined_bytes, bcs::to_bytes(&nonce.inner)); + + keccak256(combined_bytes) + } + + #[view] + /// Gets initiator bridge transfer details given a bridge transfer ID + /// + /// @param bridge_transfer_id A 32-byte vector of unsigned 8-bit integers. + /// @return A `BridgeTransferDetails` struct. + /// @abort If there is no transfer in the atomic bridge store. + public fun get_bridge_transfer_details_initiator( + bridge_transfer_id: vector + ): BridgeTransferDetails acquires SmartTableWrapper { + get_bridge_transfer_details(bridge_transfer_id) + } + + #[view] + /// Gets counterparty bridge transfer details given a bridge transfer ID + /// + /// @param bridge_transfer_id A 32-byte vector of unsigned 8-bit integers. + /// @return A `BridgeTransferDetails` struct. + /// @abort If there is no transfer in the atomic bridge store. + public fun get_bridge_transfer_details_counterparty( + bridge_transfer_id: vector + ): BridgeTransferDetails acquires SmartTableWrapper { + get_bridge_transfer_details(bridge_transfer_id) + } + + fun get_bridge_transfer_details(bridge_transfer_id: vector + ): BridgeTransferDetails acquires SmartTableWrapper { + let table = borrow_global, BridgeTransferDetails>>(@aptos_framework); + + let details_ref = smart_table::borrow( + &table.inner, + bridge_transfer_id + ); + + *details_ref + } + + #[test_only] + public fun valid_bridge_transfer_id() : vector { + sha3_256(b"atomic bridge") + } + + #[test_only] + public fun plain_secret() : vector { + b"too secret!" + } + + #[test_only] + public fun valid_hash_lock() : vector { + keccak256(plain_secret()) + } + + + #[test(aptos_framework = @aptos_framework)] + public fun test_get_bridge_transfer_details_initiator(aptos_framework: &signer) acquires SmartTableWrapper { + timestamp::set_time_has_started_for_testing(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + atomic_bridge_configuration::initialize(aptos_framework); + initialize(aptos_framework); + + let initiator = signer::address_of(aptos_framework); + let recipient = ethereum::ethereum_address(ethereum::valid_eip55()); + let amount = 1000; + let hash_lock = valid_hash_lock(); + let time_lock = create_time_lock(3600); + let bridge_transfer_id = valid_bridge_transfer_id(); + + let details = create_details( + initiator, + recipient, + amount, + hash_lock, + time_lock + ); + + add(bridge_transfer_id, details); + + let retrieved_details = get_bridge_transfer_details_initiator(bridge_transfer_id); + + let BridgeTransferDetails { + addresses: AddressPair { + initiator: retrieved_initiator, + recipient: retrieved_recipient + }, + amount: retrieved_amount, + hash_lock: retrieved_hash_lock, + time_lock: retrieved_time_lock, + state: retrieved_state + } = retrieved_details; + + assert!(retrieved_initiator == initiator, 0); + assert!(retrieved_recipient == recipient, 1); + assert!(retrieved_amount == amount, 2); + assert!(retrieved_hash_lock == hash_lock, 3); + assert!(retrieved_time_lock == time_lock, 4); + assert!(retrieved_state == PENDING_TRANSACTION, 5); + } + + #[test(aptos_framework = @aptos_framework)] + public fun test_get_bridge_transfer_details_counterparty(aptos_framework: &signer) acquires SmartTableWrapper { + timestamp::set_time_has_started_for_testing(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + initialize(aptos_framework); + + let initiator = ethereum::ethereum_address(ethereum::valid_eip55()); + let recipient = signer::address_of(aptos_framework); + let amount = 500; + let hash_lock = valid_hash_lock(); + let time_lock = create_time_lock(3600); + let bridge_transfer_id = valid_bridge_transfer_id(); + + let details = create_details( + initiator, + recipient, + amount, + hash_lock, + time_lock + ); + + add(bridge_transfer_id, details); + + let retrieved_details = get_bridge_transfer_details_counterparty(bridge_transfer_id); + + let BridgeTransferDetails { + addresses: AddressPair { + initiator: retrieved_initiator, + recipient: retrieved_recipient + }, + amount: retrieved_amount, + hash_lock: retrieved_hash_lock, + time_lock: retrieved_time_lock, + state: retrieved_state + } = retrieved_details; + + assert!(retrieved_initiator == initiator, 0); + assert!(retrieved_recipient == recipient, 1); + assert!(retrieved_amount == amount, 2); + assert!(retrieved_hash_lock == hash_lock, 3); + assert!(retrieved_time_lock == time_lock, 4); + assert!(retrieved_state == PENDING_TRANSACTION, 5); + } +} + +module aptos_framework::atomic_bridge_configuration { + use std::signer; + use aptos_framework::event; + use aptos_framework::system_addresses; + + friend aptos_framework::atomic_bridge_counterparty; + friend aptos_framework::atomic_bridge_initiator; + + /// Error code for invalid bridge operator + const EINVALID_BRIDGE_OPERATOR: u64 = 0x1; + + /// Counterparty time lock duration is 24 hours in seconds + const COUNTERPARTY_TIME_LOCK_DUARTION: u64 = 24 * 60 * 60; + /// Initiator time lock duration is 48 hours in seconds + const INITIATOR_TIME_LOCK_DUARTION: u64 = 48 * 60 * 60; + + struct BridgeConfig has key { + bridge_operator: address, + initiator_time_lock: u64, + counterparty_time_lock: u64, + } + + #[event] + /// Event emitted when the bridge operator is updated. + struct BridgeConfigOperatorUpdated has store, drop { + old_operator: address, + new_operator: address, + } + + #[event] + /// Event emitted when the initiator time lock has been updated. + struct InitiatorTimeLockUpdated has store, drop { + time_lock: u64, + } + + #[event] + /// Event emitted when the initiator time lock has been updated. + struct CounterpartyTimeLockUpdated has store, drop { + time_lock: u64, + } + + /// Initializes the bridge configuration with Aptos framework as the bridge operator. + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + let bridge_config = BridgeConfig { + bridge_operator: signer::address_of(aptos_framework), + initiator_time_lock: INITIATOR_TIME_LOCK_DUARTION, + counterparty_time_lock: COUNTERPARTY_TIME_LOCK_DUARTION, + }; + move_to(aptos_framework, bridge_config); + } + + /// Updates the bridge operator, requiring governance validation. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param new_operator The new address to be set as the bridge operator. + /// @abort If the current operator is the same as the new operator. + public fun update_bridge_operator(aptos_framework: &signer, new_operator: address + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + let bridge_config = borrow_global_mut(@aptos_framework); + let old_operator = bridge_config.bridge_operator; + assert!(old_operator != new_operator, EINVALID_BRIDGE_OPERATOR); + + bridge_config.bridge_operator = new_operator; + + event::emit( + BridgeConfigOperatorUpdated { + old_operator, + new_operator, + }, + ); + } + + public fun set_initiator_time_lock_duration(aptos_framework: &signer, time_lock: u64 + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + borrow_global_mut(@aptos_framework).initiator_time_lock = time_lock; + + event::emit( + InitiatorTimeLockUpdated { + time_lock + }, + ); + } + + public fun set_counterparty_time_lock_duration(aptos_framework: &signer, time_lock: u64 + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + borrow_global_mut(@aptos_framework).counterparty_time_lock = time_lock; + + event::emit( + CounterpartyTimeLockUpdated { + time_lock + }, + ); + } + + #[view] + public fun initiator_timelock_duration() : u64 acquires BridgeConfig { + borrow_global(@aptos_framework).initiator_time_lock + } + + #[view] + public fun counterparty_timelock_duration() : u64 acquires BridgeConfig { + borrow_global(@aptos_framework).counterparty_time_lock + } + + #[view] + /// Retrieves the address of the current bridge operator. + /// + /// @return The address of the current bridge operator. + public fun bridge_operator(): address acquires BridgeConfig { + borrow_global_mut(@aptos_framework).bridge_operator + } + + /// Asserts that the caller is the current bridge operator. + /// + /// @param caller The signer whose authority is being checked. + /// @abort If the caller is not the current bridge operator. + public(friend) fun assert_is_caller_operator(caller: &signer + ) acquires BridgeConfig { + assert!(borrow_global(@aptos_framework).bridge_operator == signer::address_of(caller), EINVALID_BRIDGE_OPERATOR); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests initialization of the bridge configuration. + fun test_initialization(aptos_framework: &signer) { + initialize(aptos_framework); + assert!(exists(@aptos_framework), 0); + } + + #[test(aptos_framework = @aptos_framework, new_operator = @0xcafe)] + /// Tests updating the bridge operator and emitting the corresponding event. + fun test_update_bridge_operator(aptos_framework: &signer, new_operator: address + ) acquires BridgeConfig { + initialize(aptos_framework); + update_bridge_operator(aptos_framework, new_operator); + + assert!( + event::was_event_emitted( + &BridgeConfigOperatorUpdated { + old_operator: @aptos_framework, + new_operator, + } + ), 0); + + assert!(bridge_operator() == new_operator, 0); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad, new_operator = @0xcafe)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that updating the bridge operator with an invalid signer fails. + fun test_failing_update_bridge_operator(aptos_framework: &signer, bad: &signer, new_operator: address + ) acquires BridgeConfig { + initialize(aptos_framework); + update_bridge_operator(bad, new_operator); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests that the correct operator is validated successfully. + fun test_is_valid_operator(aptos_framework: &signer) acquires BridgeConfig { + initialize(aptos_framework); + assert_is_caller_operator(aptos_framework); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 0x1, location = 0x1::atomic_bridge_configuration)] + /// Tests that an incorrect operator is not validated and results in an abort. + fun test_is_not_valid_operator(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize(aptos_framework); + assert_is_caller_operator(bad); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests we can update the initiator time lock + fun test_update_initiator_time_lock(aptos_framework: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_initiator_time_lock_duration(aptos_framework, 1); + assert!(initiator_timelock_duration() == 1, 0); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests we can update the initiator time lock + fun test_update_counterparty_time_lock(aptos_framework: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_counterparty_time_lock_duration(aptos_framework, 1); + assert!(counterparty_timelock_duration() == 1, 0); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that an incorrect signer cannot update the initiator time lock + fun test_not_able_to_set_initiator_time_lock(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_initiator_time_lock_duration(bad, 1); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that an incorrect signer cannot update the counterparty time lock + fun test_not_able_to_set_counterparty_time_lock(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_counterparty_time_lock_duration(bad, 1); + } +} + +module aptos_framework::atomic_bridge { + use std::features; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::atomic_bridge_configuration; + use aptos_framework::atomic_bridge_store; + use aptos_framework::coin; + use aptos_framework::coin::{BurnCapability, MintCapability}; + use aptos_framework::fungible_asset::{BurnRef, MintRef}; + use aptos_framework::system_addresses; + #[test_only] + use aptos_framework::account; + #[test_only] + use aptos_framework::aptos_coin; + #[test_only] + use aptos_framework::timestamp; + + friend aptos_framework::atomic_bridge_counterparty; + friend aptos_framework::atomic_bridge_initiator; + friend aptos_framework::genesis; + + const EATOMIC_BRIDGE_NOT_ENABLED : u64 = 0x1; + + struct AptosCoinBurnCapability has key { + burn_cap: BurnCapability, + } + + struct AptosCoinMintCapability has key { + mint_cap: MintCapability, + } + + struct AptosFABurnCapabilities has key { + burn_ref: BurnRef, + } + + struct AptosFAMintCapabilities has key { + burn_ref: MintRef, + } + + /// Initializes the atomic bridge by setting up necessary configurations. + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize(aptos_framework: &signer) { + atomic_bridge_configuration::initialize(aptos_framework); + atomic_bridge_store::initialize(aptos_framework); + } + + #[test_only] + /// Initializes the atomic bridge for testing purposes, including setting up accounts and timestamps. + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize_for_test(aptos_framework: &signer) { + timestamp::set_time_has_started_for_testing(aptos_framework); + account::create_account_for_test(@aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + initialize(aptos_framework); + + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(aptos_framework); + + store_aptos_coin_mint_cap(aptos_framework, mint_cap); + store_aptos_coin_burn_cap(aptos_framework, burn_cap); + } + + /// Stores the burn capability for AptosCoin, converting to a fungible asset reference if the feature is enabled. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param burn_cap The burn capability for AptosCoin. + public fun store_aptos_coin_burn_cap(aptos_framework: &signer, burn_cap: BurnCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + if (features::operations_default_to_fa_apt_store_enabled()) { + let burn_ref = coin::convert_and_take_paired_burn_ref(burn_cap); + move_to(aptos_framework, AptosFABurnCapabilities { burn_ref }); + } else { + move_to(aptos_framework, AptosCoinBurnCapability { burn_cap }) + } + } + + /// Stores the mint capability for AptosCoin. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param mint_cap The mint capability for AptosCoin. + public fun store_aptos_coin_mint_cap(aptos_framework: &signer, mint_cap: MintCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, AptosCoinMintCapability { mint_cap }) + } + + /// Mints a specified amount of AptosCoin to a recipient's address. + /// + /// @param recipient The address of the recipient to mint coins to. + /// @param amount The amount of AptosCoin to mint. + /// @abort If the mint capability is not available. + public(friend) fun mint(recipient: address, amount: u64) acquires AptosCoinMintCapability { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + coin::deposit(recipient, coin::mint( + amount, + &borrow_global(@aptos_framework).mint_cap + )); + } + + /// Burns a specified amount of AptosCoin from an address. + /// + /// @param from The address from which to burn AptosCoin. + /// @param amount The amount of AptosCoin to burn. + /// @abort If the burn capability is not available. + public(friend) fun burn(from: address, amount: u64) acquires AptosCoinBurnCapability { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + coin::burn_from( + from, + amount, + &borrow_global(@aptos_framework).burn_cap, + ); + } +} + +module aptos_framework::atomic_bridge_counterparty { + use aptos_framework::account; + use aptos_framework::atomic_bridge; + use aptos_framework::atomic_bridge_configuration; + use aptos_framework::atomic_bridge_store; + use aptos_framework::atomic_bridge_store::create_hashlock; + use aptos_framework::ethereum; + use aptos_framework::ethereum::EthereumAddress; + use aptos_framework::event::{Self, EventHandle}; + #[test_only] + use aptos_framework::aptos_account; + #[test_only] + use aptos_framework::atomic_bridge::initialize_for_test; + #[test_only] + use aptos_framework::atomic_bridge_store::{valid_bridge_transfer_id, valid_hash_lock, plain_secret}; + #[test_only] + use aptos_framework::ethereum::valid_eip55; + #[test_only] + use aptos_framework::signer; + #[test_only] + use aptos_framework::timestamp; + + #[event] + /// An event triggered upon locking assets for a bridge transfer + struct BridgeTransferLockedEvent has store, drop { + bridge_transfer_id: vector, + initiator: vector, + recipient: address, + amount: u64, + hash_lock: vector, + time_lock: u64, + } + + #[event] + /// An event triggered upon completing a bridge transfer + struct BridgeTransferCompletedEvent has store, drop { + bridge_transfer_id: vector, + pre_image: vector, + } + + #[event] + /// An event triggered upon cancelling a bridge transfer + struct BridgeTransferCancelledEvent has store, drop { + bridge_transfer_id: vector, + } + + /// This struct will store the event handles for bridge events. + struct BridgeCounterpartyEvents has key, store { + bridge_transfer_locked_events: EventHandle, + bridge_transfer_completed_events: EventHandle, + bridge_transfer_cancelled_events: EventHandle, + } + + /// Initializes the module and stores the `EventHandle`s in the resource. + public fun initialize(aptos_framework: &signer) { + move_to(aptos_framework, BridgeCounterpartyEvents { + bridge_transfer_locked_events: account::new_event_handle(aptos_framework), + bridge_transfer_completed_events: account::new_event_handle(aptos_framework), + bridge_transfer_cancelled_events: account::new_event_handle(aptos_framework), + }); + } + + /// Locks assets for a bridge transfer by the initiator. + /// + /// @param caller The signer representing the bridge operator. + /// @param initiator The initiator's Ethereum address as a vector of bytes. + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @param hash_lock The hash lock for securing the transfer. + /// @param time_lock The time lock duration for the transfer. + /// @param recipient The address of the recipient on the Aptos blockchain. + /// @param amount The amount of assets to be locked. + /// @abort If the caller is not the bridge operator. + public entry fun lock_bridge_transfer_assets ( + caller: &signer, + initiator: vector, + bridge_transfer_id: vector, + hash_lock: vector, + recipient: address, + amount: u64 + ) acquires BridgeCounterpartyEvents { + atomic_bridge_configuration::assert_is_caller_operator(caller); + let ethereum_address = ethereum::ethereum_address_no_eip55(initiator); + let time_lock = atomic_bridge_configuration::counterparty_timelock_duration(); + let details = atomic_bridge_store::create_details( + ethereum_address, + recipient, + amount, + hash_lock, + time_lock + ); + + // bridge_store::add_counterparty(bridge_transfer_id, details); + atomic_bridge_store::add(bridge_transfer_id, details); + + let bridge_events = borrow_global_mut(@aptos_framework); + + event::emit_event( + &mut bridge_events.bridge_transfer_locked_events, + BridgeTransferLockedEvent { + bridge_transfer_id, + initiator, + recipient, + amount, + hash_lock, + time_lock, + }, + ); + } + + /// Completes a bridge transfer by revealing the pre-image. + /// + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @param pre_image The pre-image that matches the hash lock to complete the transfer. + /// @abort If the caller is not the bridge operator or the hash lock validation fails. + public entry fun complete_bridge_transfer ( + bridge_transfer_id: vector, + pre_image: vector, + ) acquires BridgeCounterpartyEvents { + let (recipient, amount) = atomic_bridge_store::complete_transfer( + bridge_transfer_id, + create_hashlock(pre_image) + ); + + // Mint, fails silently + atomic_bridge::mint(recipient, amount); + + let bridge_counterparty_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_counterparty_events.bridge_transfer_completed_events, + BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image, + }, + ); + } + + /// Aborts a bridge transfer if the time lock has expired. + /// + /// @param caller The signer representing the bridge operator. + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @abort If the caller is not the bridge operator or if the time lock has not expired. + public entry fun abort_bridge_transfer ( + caller: &signer, + bridge_transfer_id: vector + ) acquires BridgeCounterpartyEvents { + atomic_bridge_configuration::assert_is_caller_operator(caller); + + atomic_bridge_store::cancel_transfer(bridge_transfer_id); + + let bridge_counterparty_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_counterparty_events.bridge_transfer_cancelled_events, + BridgeTransferCancelledEvent { + bridge_transfer_id, + }, + ); + } + + #[test(aptos_framework = @aptos_framework)] + fun test_lock_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + let bridge_counterparty_events = borrow_global(signer::address_of(aptos_framework)); + let lock_events = event::emitted_events_by_handle(&bridge_counterparty_events.bridge_transfer_locked_events); + + // Assert that the event was emitted + let expected_event = BridgeTransferLockedEvent { + bridge_transfer_id, + initiator, + recipient, + amount, + hash_lock, + time_lock: atomic_bridge_configuration::counterparty_timelock_duration(), + }; + assert!(std::vector::contains(&lock_events, &expected_event), 0); + + } + + #[test(aptos_framework = @aptos_framework)] + fun test_abort_transfer_of_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + timestamp::fast_forward_seconds(atomic_bridge_configuration::counterparty_timelock_duration() + 1); + abort_bridge_transfer(aptos_framework, bridge_transfer_id); + + let bridge_counterparty_events = borrow_global(signer::address_of(aptos_framework)); + let cancel_events = event::emitted_events_by_handle(&bridge_counterparty_events.bridge_transfer_cancelled_events); + let expected_event = BridgeTransferCancelledEvent { bridge_transfer_id }; + assert!(std::vector::contains(&cancel_events, &expected_event), 0); + } + + #[test(aptos_framework = @aptos_framework)] + fun test_complete_transfer_of_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + // Create an account for our recipient + aptos_account::create_account(recipient); + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + complete_bridge_transfer(bridge_transfer_id, plain_secret()); + + let bridge_counterparty_events = borrow_global(signer::address_of(aptos_framework)); + let complete_events = event::emitted_events_by_handle(&bridge_counterparty_events.bridge_transfer_completed_events); + let expected_event = BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image: plain_secret(), + }; + assert!(std::vector::contains(&complete_events, &expected_event), 0); + + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x1, location = atomic_bridge_store)] + fun test_failing_complete_transfer_of_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + complete_bridge_transfer(bridge_transfer_id, b"not the secret"); + } +} + diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/atomic_bridge_store.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/atomic_bridge_store.move new file mode 100644 index 000000000..ff1d9851a --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/atomic_bridge_store.move @@ -0,0 +1,1523 @@ +module aptos_framework::atomic_bridge_initiator { + use aptos_framework::account; + use aptos_framework::atomic_bridge; + use aptos_framework::atomic_bridge_configuration; + use aptos_framework::atomic_bridge_configuration::assert_is_caller_operator; + use aptos_framework::atomic_bridge_store; + use aptos_framework::atomic_bridge_store::{create_hashlock, bridge_transfer_id}; + use aptos_framework::ethereum; + use aptos_framework::ethereum::EthereumAddress; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::signer; + #[test_only] + use std::vector; + #[test_only] + use aptos_framework::aptos_account; + #[test_only] + use aptos_framework::aptos_coin::AptosCoin; + #[test_only] + use aptos_framework::atomic_bridge_store::{valid_hash_lock, assert_valid_bridge_transfer_id, plain_secret}; + #[test_only] + use aptos_framework::coin; + #[test_only] + use aptos_framework::ethereum::valid_eip55; + #[test_only] + use aptos_framework::timestamp; + + #[event] + struct BridgeTransferInitiatedEvent has store, drop { + bridge_transfer_id: vector, + initiator: address, + recipient: vector, + amount: u64, + hash_lock: vector, + time_lock: u64, + } + + #[event] + struct BridgeTransferCompletedEvent has store, drop { + bridge_transfer_id: vector, + pre_image: vector, + } + + #[event] + struct BridgeTransferRefundedEvent has store, drop { + bridge_transfer_id: vector, + } + + /// This struct will store the event handles for bridge events. + struct BridgeInitiatorEvents has key, store { + bridge_transfer_initiated_events: EventHandle, + bridge_transfer_completed_events: EventHandle, + bridge_transfer_refunded_events: EventHandle, + } + + /// Initializes the module and stores the `EventHandle`s in the resource. + public fun initialize(aptos_framework: &signer) { + move_to(aptos_framework, BridgeInitiatorEvents { + bridge_transfer_initiated_events: account::new_event_handle(aptos_framework), + bridge_transfer_completed_events: account::new_event_handle(aptos_framework), + bridge_transfer_refunded_events: account::new_event_handle(aptos_framework), + }); + } + + /// Initiate a bridge transfer of ETH from Movement to the base layer + /// Anyone can initiate a bridge transfer from the source chain + /// The amount is burnt from the initiator + public entry fun initiate_bridge_transfer( + initiator: &signer, + recipient: vector, + hash_lock: vector, + amount: u64 + ) acquires BridgeInitiatorEvents { + let ethereum_address = ethereum::ethereum_address_no_eip55(recipient); + let initiator_address = signer::address_of(initiator); + let time_lock = atomic_bridge_configuration::initiator_timelock_duration(); + + let details = + atomic_bridge_store::create_details( + initiator_address, + ethereum_address, amount, + hash_lock, + time_lock + ); + + let bridge_transfer_id = bridge_transfer_id(&details); + atomic_bridge_store::add(bridge_transfer_id, details); + atomic_bridge::burn(initiator_address, amount); + + let bridge_initiator_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_initiator_events.bridge_transfer_initiated_events, + BridgeTransferInitiatedEvent { + bridge_transfer_id, + initiator: initiator_address, + recipient, + amount, + hash_lock, + time_lock + }, + ); + } + + /// Bridge operator can complete the transfer + public entry fun complete_bridge_transfer ( + caller: &signer, + bridge_transfer_id: vector, + pre_image: vector, + ) acquires BridgeInitiatorEvents { + assert_is_caller_operator(caller); + let (_, _) = atomic_bridge_store::complete_transfer(bridge_transfer_id, create_hashlock(pre_image)); + + let bridge_initiator_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_initiator_events.bridge_transfer_completed_events, + BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image, + }, + ); + } + + /// Anyone can refund the transfer on the source chain once time lock has passed + public entry fun refund_bridge_transfer ( + _caller: &signer, + bridge_transfer_id: vector, + ) acquires BridgeInitiatorEvents { + let (receiver, amount) = atomic_bridge_store::cancel_transfer(bridge_transfer_id); + atomic_bridge::mint(receiver, amount); + + let bridge_initiator_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_initiator_events.bridge_transfer_refunded_events, + BridgeTransferRefundedEvent { + bridge_transfer_id, + }, + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + fun test_initiate_bridge_transfer( + sender: &signer, + aptos_framework: &signer, + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + initialize(aptos_framework); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let time_lock = atomic_bridge_configuration::initiator_timelock_duration(); + let amount = 1000; + + // Mint some coins + atomic_bridge::mint(sender_address, amount + 1); + + assert!(coin::balance(sender_address) == amount + 1, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + assert!(coin::balance(sender_address) == 1, 0); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + assert_valid_bridge_transfer_id(&bridge_transfer_initiated_event.bridge_transfer_id); + assert!(bridge_transfer_initiated_event.recipient == recipient, 0); + assert!(bridge_transfer_initiated_event.amount == amount, 0); + assert!(bridge_transfer_initiated_event.initiator == sender_address, 0); + assert!(bridge_transfer_initiated_event.hash_lock == hash_lock, 0); + assert!(bridge_transfer_initiated_event.time_lock == time_lock, 0); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x10006, location = 0x1::coin)] //EINSUFFICIENT_BALANCE + fun test_initiate_bridge_transfer_insufficient_balance( + sender: &signer, + aptos_framework: &signer, + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + fun test_complete_bridge_transfer( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + let account_balance = amount + 1; + + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + plain_secret(), + ); + + let bridge_initiator_events = borrow_global(signer::address_of(aptos_framework)); + let complete_events = event::emitted_events_by_handle(&bridge_initiator_events.bridge_transfer_completed_events); + let expected_event = BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image: plain_secret(), + }; + assert!(std::vector::contains(&complete_events, &expected_event), 0); + + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x1, location = 0x1::atomic_bridge_configuration)] // EINVALID_BRIDGE_OPERATOR + fun test_complete_bridge_transfer_by_sender( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + let account_balance = amount + 1; + + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + complete_bridge_transfer( + sender, + bridge_transfer_id, + plain_secret(), + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x1, location = 0x1::atomic_bridge_store)] // EINVALID_PRE_IMAGE + fun test_complete_bridge_transfer_with_invalid_preimage( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + let account_balance = amount + 1; + + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + b"bad secret", + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x10001, location = 0x1::smart_table)] // ENOT_FOUND + fun test_complete_bridge_with_errorneous_bridge_id_by_operator( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + + let bridge_transfer_id = b"guessing the id"; + + // As operator I send a complete request and it should fail + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + plain_secret(), + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + fun test_refund_bridge_transfer( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + let account_balance = amount + 1; + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + assert!(coin::balance(sender_address) == account_balance - amount, 0); + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + timestamp::fast_forward_seconds(atomic_bridge_configuration::initiator_timelock_duration() + 1); + + refund_bridge_transfer(sender, bridge_transfer_id); + + assert!(coin::balance(sender_address) == account_balance, 0); + + let bridge_initiator_events = borrow_global(signer::address_of(aptos_framework)); + let refund_events = event::emitted_events_by_handle(&bridge_initiator_events.bridge_transfer_refunded_events); + let expected_event = BridgeTransferRefundedEvent { bridge_transfer_id }; + let was_event_emitted = std::vector::contains(&refund_events, &expected_event); + + assert!(was_event_emitted, 0); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 0x4, location = 0x1::atomic_bridge_store)] //ENOT_EXPIRED + fun test_refund_bridge_transfer_before_timelock( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeInitiatorEvents { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + atomic_bridge::initialize_for_test(aptos_framework); + initialize(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = valid_eip55(); + let hash_lock = valid_hash_lock(); + let amount = 1000; + + let account_balance = amount + 1; + // Mint some coins + atomic_bridge::mint(sender_address, account_balance); + + assert!(coin::balance(sender_address) == account_balance, 0); + + initiate_bridge_transfer( + sender, + recipient, + hash_lock, + amount + ); + + assert!(coin::balance(sender_address) == account_balance - amount, 0); + + + let bridge_initiator_events = borrow_global(@aptos_framework); + let bridge_transfer_initiated_events = event::emitted_events_by_handle( + &bridge_initiator_events.bridge_transfer_initiated_events + ); + let bridge_transfer_initiated_event = vector::borrow(&bridge_transfer_initiated_events, 0); + + let bridge_transfer_id = bridge_transfer_initiated_event.bridge_transfer_id; + + refund_bridge_transfer(sender, bridge_transfer_id); + } +} + +module aptos_framework::atomic_bridge_store { + use std::bcs; + use std::features; + use std::vector; + use aptos_std::aptos_hash::keccak256; + use aptos_std::smart_table; + use aptos_std::smart_table::SmartTable; + use aptos_framework::ethereum::EthereumAddress; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + use std::signer; + use aptos_framework::timestamp::CurrentTimeMicroseconds; + + friend aptos_framework::atomic_bridge_counterparty; + friend aptos_framework::atomic_bridge_initiator; + + #[test_only] + use std::hash::sha3_256; + #[test_only] + use aptos_framework::ethereum; + #[test_only] + use aptos_framework::atomic_bridge_configuration; + + /// Error codes + const EINVALID_PRE_IMAGE : u64 = 0x1; + const ENOT_PENDING_TRANSACTION : u64 = 0x2; + const EEXPIRED : u64 = 0x3; + const ENOT_EXPIRED : u64 = 0x4; + const EINVALID_HASH_LOCK : u64 = 0x5; + const EINVALID_TIME_LOCK : u64 = 0x6; + const EZERO_AMOUNT : u64 = 0x7; + const EINVALID_BRIDGE_TRANSFER_ID : u64 = 0x8; + const EATOMIC_BRIDGE_NOT_ENABLED : u64 = 0x9; + + /// Transaction states + const PENDING_TRANSACTION: u8 = 0x1; + const COMPLETED_TRANSACTION: u8 = 0x2; + const CANCELLED_TRANSACTION: u8 = 0x3; + + /// Minimum time lock of 1 second + const MIN_TIME_LOCK : u64 = 1; + const MAX_U64 : u64 = 0xFFFFFFFFFFFFFFFF; + + struct AddressPair has store, copy { + initiator: Initiator, + recipient: Recipient, + } + + /// A smart table wrapper + struct SmartTableWrapper has key, store { + inner: SmartTable, + } + + /// Details on the transfer + struct BridgeTransferDetails has store, copy { + addresses: AddressPair, + amount: u64, + hash_lock: vector, + time_lock: u64, + state: u8, + } + + struct Nonce has key { + inner: u64 + } + + /// Initializes the initiators and counterparties tables and nonce. + /// + /// @param aptos_framework The signer for Aptos framework. + public fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, Nonce { + inner: 0, + }); + + let initiators = SmartTableWrapper, BridgeTransferDetails> { + inner: smart_table::new(), + }; + + move_to(aptos_framework, initiators); + + let counterparties = SmartTableWrapper, BridgeTransferDetails> { + inner: smart_table::new(), + }; + + move_to(aptos_framework, counterparties); + } + + /// Returns the current time in seconds. + /// + /// @return Current timestamp in seconds. + fun now() : u64 { + timestamp::now_seconds() + } + + /// Creates a time lock by adding a duration to the current time. + /// + /// @param lock The duration to lock. + /// @return The calculated time lock. + /// @abort If lock is not above MIN_TIME_LOCK + public(friend) fun create_time_lock(time_lock: u64) : u64 { + assert_min_time_lock(time_lock); + now() + time_lock + } + + /// Creates bridge transfer details with validation. + /// + /// @param initiator The initiating party of the transfer. + /// @param recipient The receiving party of the transfer. + /// @param amount The amount to be transferred. + /// @param hash_lock The hash lock for the transfer. + /// @param time_lock The time lock for the transfer. + /// @return A `BridgeTransferDetails` object. + /// @abort If the amount is zero or locks are invalid. + public(friend) fun create_details(initiator: Initiator, recipient: Recipient, amount: u64, hash_lock: vector, time_lock: u64) + : BridgeTransferDetails { + assert!(amount > 0, EZERO_AMOUNT); + assert_valid_hash_lock(&hash_lock); + time_lock = create_time_lock(time_lock); + + BridgeTransferDetails { + addresses: AddressPair { + initiator, + recipient + }, + amount, + hash_lock, + time_lock, + state: PENDING_TRANSACTION, + } + } + + /// Record details of a transfer + /// + /// @param bridge_transfer_id Bridge transfer ID. + /// @param details The bridge transfer details + public(friend) fun add(bridge_transfer_id: vector, details: BridgeTransferDetails) acquires SmartTableWrapper { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + assert_valid_bridge_transfer_id(&bridge_transfer_id); + let table = borrow_global_mut, BridgeTransferDetails>>(@aptos_framework); + smart_table::add(&mut table.inner, bridge_transfer_id, details); + } + + /// Asserts that the time lock is valid. + /// + /// @param time_lock + /// @abort If the time lock is invalid. + fun assert_min_time_lock(time_lock: u64) { + assert!(time_lock >= MIN_TIME_LOCK, EINVALID_TIME_LOCK); + } + + /// Asserts that the details state is pending. + /// + /// @param details The bridge transfer details to check. + /// @abort If the state is not pending. + fun assert_pending(details: &BridgeTransferDetails) { + assert!(details.state == PENDING_TRANSACTION, ENOT_PENDING_TRANSACTION) + } + + /// Asserts that the hash lock is valid. + /// + /// @param hash_lock The hash lock to validate. + /// @abort If the hash lock is invalid. + fun assert_valid_hash_lock(hash_lock: &vector) { + assert!(vector::length(hash_lock) == 32, EINVALID_HASH_LOCK); + } + + /// Asserts that the bridge transfer ID is valid. + /// + /// @param bridge_transfer_id The bridge transfer ID to validate. + /// @abort If the ID is invalid. + public(friend) fun assert_valid_bridge_transfer_id(bridge_transfer_id: &vector) { + assert!(vector::length(bridge_transfer_id) == 32, EINVALID_BRIDGE_TRANSFER_ID); + } + + /// Creates a hash lock from a pre-image. + /// + /// @param pre_image The pre-image to hash. + /// @return The generated hash lock. + public(friend) fun create_hashlock(pre_image: vector) : vector { + assert!(vector::length(&pre_image) > 0, EINVALID_PRE_IMAGE); + keccak256(pre_image) + } + + /// Asserts that the hash lock matches the expected value. + /// + /// @param details The bridge transfer details. + /// @param hash_lock The hash lock to compare. + /// @abort If the hash lock is incorrect. + fun assert_correct_hash_lock(details: &BridgeTransferDetails, hash_lock: vector) { + assert!(&hash_lock == &details.hash_lock, EINVALID_PRE_IMAGE); + } + + /// Asserts that the time lock has expired. + /// + /// @param details The bridge transfer details. + /// @abort If the time lock has not expired. + fun assert_timed_out_lock(details: &BridgeTransferDetails) { + assert!(now() > details.time_lock, ENOT_EXPIRED); + } + + /// Asserts we are still within the timelock. + /// + /// @param details The bridge transfer details. + /// @abort If the time lock has expired. + fun assert_within_timelock(details: &BridgeTransferDetails) { + assert!(!(now() > details.time_lock), EEXPIRED); + } + + /// Completes the bridge transfer. + /// + /// @param details The bridge transfer details to complete. + fun complete(details: &mut BridgeTransferDetails) { + details.state = COMPLETED_TRANSACTION; + } + + /// Cancels the bridge transfer. + /// + /// @param details The bridge transfer details to cancel. + fun cancel(details: &mut BridgeTransferDetails) { + details.state = CANCELLED_TRANSACTION; + } + + /// Validates and completes a bridge transfer by confirming the hash lock and state. + /// + /// @param hash_lock The hash lock used to validate the transfer. + /// @param details The mutable reference to the bridge transfer details to be completed. + /// @return A tuple containing the recipient and the amount of the transfer. + /// @abort If the hash lock is invalid, the transfer is not pending, or the hash lock does not match. + fun complete_details(hash_lock: vector, details: &mut BridgeTransferDetails) : (Recipient, u64) { + assert_valid_hash_lock(&hash_lock); + assert_pending(details); + assert_correct_hash_lock(details, hash_lock); + assert_within_timelock(details); + + complete(details); + + (details.addresses.recipient, details.amount) + } + + /// Completes a bridge transfer by validating the hash lock and updating the transfer state. + /// + /// @param bridge_transfer_id The ID of the bridge transfer to complete. + /// @param hash_lock The hash lock used to validate the transfer. + /// @return A tuple containing the recipient of the transfer and the amount transferred. + /// @abort If the bridge transfer details are not found or if the completion checks in `complete_details` fail. + public(friend) fun complete_transfer(bridge_transfer_id: vector, hash_lock: vector) : (Recipient, u64) acquires SmartTableWrapper { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + let table = borrow_global_mut, BridgeTransferDetails>>(@aptos_framework); + + let details = smart_table::borrow_mut( + &mut table.inner, + bridge_transfer_id); + + complete_details(hash_lock, details) + } + + /// Cancels a pending bridge transfer if the time lock has expired. + /// + /// @param details A mutable reference to the bridge transfer details to be canceled. + /// @return A tuple containing the initiator of the transfer and the amount to be refunded. + /// @abort If the transfer is not in a pending state or the time lock has not expired. + fun cancel_details(details: &mut BridgeTransferDetails) : (Initiator, u64) { + assert_pending(details); + assert_timed_out_lock(details); + + cancel(details); + + (details.addresses.initiator, details.amount) + } + + /// Cancels a bridge transfer if it is pending and the time lock has expired. + /// + /// @param bridge_transfer_id The ID of the bridge transfer to cancel. + /// @return A tuple containing the initiator of the transfer and the amount to be refunded. + /// @abort If the bridge transfer details are not found or if the cancellation conditions in `cancel_details` fail. + public(friend) fun cancel_transfer(bridge_transfer_id: vector) : (Initiator, u64) acquires SmartTableWrapper { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + let table = borrow_global_mut, BridgeTransferDetails>>(@aptos_framework); + + let details = smart_table::borrow_mut( + &mut table.inner, + bridge_transfer_id); + + cancel_details(details) + } + + /// Generates a unique bridge transfer ID based on transfer details and nonce. + /// + /// @param details The bridge transfer details. + /// @return The generated bridge transfer ID. + public(friend) fun bridge_transfer_id(details: &BridgeTransferDetails) : vector acquires Nonce { + let nonce = borrow_global_mut(@aptos_framework); + let combined_bytes = vector::empty(); + vector::append(&mut combined_bytes, bcs::to_bytes(&details.addresses.initiator)); + vector::append(&mut combined_bytes, bcs::to_bytes(&details.addresses.recipient)); + vector::append(&mut combined_bytes, details.hash_lock); + if (nonce.inner == MAX_U64) { + nonce.inner = 0; // Wrap around to 0 if at maximum value + } else { + nonce.inner = nonce.inner + 1; // Safe to increment without overflow + }; + vector::append(&mut combined_bytes, bcs::to_bytes(&nonce.inner)); + + keccak256(combined_bytes) + } + + #[view] + /// Gets initiator bridge transfer details given a bridge transfer ID + /// + /// @param bridge_transfer_id A 32-byte vector of unsigned 8-bit integers. + /// @return A `BridgeTransferDetails` struct. + /// @abort If there is no transfer in the atomic bridge store. + public fun get_bridge_transfer_details_initiator( + bridge_transfer_id: vector + ): BridgeTransferDetails acquires SmartTableWrapper { + get_bridge_transfer_details(bridge_transfer_id) + } + + #[view] + /// Gets counterparty bridge transfer details given a bridge transfer ID + /// + /// @param bridge_transfer_id A 32-byte vector of unsigned 8-bit integers. + /// @return A `BridgeTransferDetails` struct. + /// @abort If there is no transfer in the atomic bridge store. + public fun get_bridge_transfer_details_counterparty( + bridge_transfer_id: vector + ): BridgeTransferDetails acquires SmartTableWrapper { + get_bridge_transfer_details(bridge_transfer_id) + } + + fun get_bridge_transfer_details(bridge_transfer_id: vector + ): BridgeTransferDetails acquires SmartTableWrapper { + let table = borrow_global, BridgeTransferDetails>>(@aptos_framework); + + let details_ref = smart_table::borrow( + &table.inner, + bridge_transfer_id + ); + + *details_ref + } + + #[test_only] + public fun valid_bridge_transfer_id() : vector { + sha3_256(b"atomic bridge") + } + + #[test_only] + public fun plain_secret() : vector { + b"too secret!" + } + + #[test_only] + public fun valid_hash_lock() : vector { + keccak256(plain_secret()) + } + + + #[test(aptos_framework = @aptos_framework)] + public fun test_get_bridge_transfer_details_initiator(aptos_framework: &signer) acquires SmartTableWrapper { + timestamp::set_time_has_started_for_testing(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + atomic_bridge_configuration::initialize(aptos_framework); + initialize(aptos_framework); + + let initiator = signer::address_of(aptos_framework); + let recipient = ethereum::ethereum_address(ethereum::valid_eip55()); + let amount = 1000; + let hash_lock = valid_hash_lock(); + let time_lock = create_time_lock(3600); + let bridge_transfer_id = valid_bridge_transfer_id(); + + let details = create_details( + initiator, + recipient, + amount, + hash_lock, + time_lock + ); + + add(bridge_transfer_id, details); + + let retrieved_details = get_bridge_transfer_details_initiator(bridge_transfer_id); + + let BridgeTransferDetails { + addresses: AddressPair { + initiator: retrieved_initiator, + recipient: retrieved_recipient + }, + amount: retrieved_amount, + hash_lock: retrieved_hash_lock, + time_lock: retrieved_time_lock, + state: retrieved_state + } = retrieved_details; + + assert!(retrieved_initiator == initiator, 0); + assert!(retrieved_recipient == recipient, 1); + assert!(retrieved_amount == amount, 2); + assert!(retrieved_hash_lock == hash_lock, 3); + assert!(retrieved_time_lock == time_lock, 4); + assert!(retrieved_state == PENDING_TRANSACTION, 5); + } + + #[test(aptos_framework = @aptos_framework)] + public fun test_get_bridge_transfer_details_counterparty(aptos_framework: &signer) acquires SmartTableWrapper { + timestamp::set_time_has_started_for_testing(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + initialize(aptos_framework); + + let initiator = ethereum::ethereum_address(ethereum::valid_eip55()); + let recipient = signer::address_of(aptos_framework); + let amount = 500; + let hash_lock = valid_hash_lock(); + let time_lock = create_time_lock(3600); + let bridge_transfer_id = valid_bridge_transfer_id(); + + let details = create_details( + initiator, + recipient, + amount, + hash_lock, + time_lock + ); + + add(bridge_transfer_id, details); + + let retrieved_details = get_bridge_transfer_details_counterparty(bridge_transfer_id); + + let BridgeTransferDetails { + addresses: AddressPair { + initiator: retrieved_initiator, + recipient: retrieved_recipient + }, + amount: retrieved_amount, + hash_lock: retrieved_hash_lock, + time_lock: retrieved_time_lock, + state: retrieved_state + } = retrieved_details; + + assert!(retrieved_initiator == initiator, 0); + assert!(retrieved_recipient == recipient, 1); + assert!(retrieved_amount == amount, 2); + assert!(retrieved_hash_lock == hash_lock, 3); + assert!(retrieved_time_lock == time_lock, 4); + assert!(retrieved_state == PENDING_TRANSACTION, 5); + } +} + +module aptos_framework::atomic_bridge_configuration { + use std::signer; + use aptos_framework::event; + use aptos_framework::system_addresses; + + friend aptos_framework::atomic_bridge_counterparty; + friend aptos_framework::atomic_bridge_initiator; + + /// Error code for invalid bridge operator + const EINVALID_BRIDGE_OPERATOR: u64 = 0x1; + + /// Counterparty time lock duration is 24 hours in seconds + const COUNTERPARTY_TIME_LOCK_DUARTION: u64 = 24 * 60 * 60; + /// Initiator time lock duration is 48 hours in seconds + const INITIATOR_TIME_LOCK_DUARTION: u64 = 48 * 60 * 60; + + struct BridgeConfig has key { + bridge_operator: address, + initiator_time_lock: u64, + counterparty_time_lock: u64, + } + + #[event] + /// Event emitted when the bridge operator is updated. + struct BridgeConfigOperatorUpdated has store, drop { + old_operator: address, + new_operator: address, + } + + #[event] + /// Event emitted when the initiator time lock has been updated. + struct InitiatorTimeLockUpdated has store, drop { + time_lock: u64, + } + + #[event] + /// Event emitted when the initiator time lock has been updated. + struct CounterpartyTimeLockUpdated has store, drop { + time_lock: u64, + } + + /// Initializes the bridge configuration with Aptos framework as the bridge operator. + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + let bridge_config = BridgeConfig { + bridge_operator: signer::address_of(aptos_framework), + initiator_time_lock: INITIATOR_TIME_LOCK_DUARTION, + counterparty_time_lock: COUNTERPARTY_TIME_LOCK_DUARTION, + }; + move_to(aptos_framework, bridge_config); + } + + /// Updates the bridge operator, requiring governance validation. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param new_operator The new address to be set as the bridge operator. + /// @abort If the current operator is the same as the new operator. + public fun update_bridge_operator(aptos_framework: &signer, new_operator: address + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + let bridge_config = borrow_global_mut(@aptos_framework); + let old_operator = bridge_config.bridge_operator; + assert!(old_operator != new_operator, EINVALID_BRIDGE_OPERATOR); + + bridge_config.bridge_operator = new_operator; + + event::emit( + BridgeConfigOperatorUpdated { + old_operator, + new_operator, + }, + ); + } + + public fun set_initiator_time_lock_duration(aptos_framework: &signer, time_lock: u64 + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + borrow_global_mut(@aptos_framework).initiator_time_lock = time_lock; + + event::emit( + InitiatorTimeLockUpdated { + time_lock + }, + ); + } + + public fun set_counterparty_time_lock_duration(aptos_framework: &signer, time_lock: u64 + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + borrow_global_mut(@aptos_framework).counterparty_time_lock = time_lock; + + event::emit( + CounterpartyTimeLockUpdated { + time_lock + }, + ); + } + + #[view] + public fun initiator_timelock_duration() : u64 acquires BridgeConfig { + borrow_global(@aptos_framework).initiator_time_lock + } + + #[view] + public fun counterparty_timelock_duration() : u64 acquires BridgeConfig { + borrow_global(@aptos_framework).counterparty_time_lock + } + + #[view] + /// Retrieves the address of the current bridge operator. + /// + /// @return The address of the current bridge operator. + public fun bridge_operator(): address acquires BridgeConfig { + borrow_global_mut(@aptos_framework).bridge_operator + } + + /// Asserts that the caller is the current bridge operator. + /// + /// @param caller The signer whose authority is being checked. + /// @abort If the caller is not the current bridge operator. + public(friend) fun assert_is_caller_operator(caller: &signer + ) acquires BridgeConfig { + assert!(borrow_global(@aptos_framework).bridge_operator == signer::address_of(caller), EINVALID_BRIDGE_OPERATOR); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests initialization of the bridge configuration. + fun test_initialization(aptos_framework: &signer) { + initialize(aptos_framework); + assert!(exists(@aptos_framework), 0); + } + + #[test(aptos_framework = @aptos_framework, new_operator = @0xcafe)] + /// Tests updating the bridge operator and emitting the corresponding event. + fun test_update_bridge_operator(aptos_framework: &signer, new_operator: address + ) acquires BridgeConfig { + initialize(aptos_framework); + update_bridge_operator(aptos_framework, new_operator); + + assert!( + event::was_event_emitted( + &BridgeConfigOperatorUpdated { + old_operator: @aptos_framework, + new_operator, + } + ), 0); + + assert!(bridge_operator() == new_operator, 0); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad, new_operator = @0xcafe)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that updating the bridge operator with an invalid signer fails. + fun test_failing_update_bridge_operator(aptos_framework: &signer, bad: &signer, new_operator: address + ) acquires BridgeConfig { + initialize(aptos_framework); + update_bridge_operator(bad, new_operator); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests that the correct operator is validated successfully. + fun test_is_valid_operator(aptos_framework: &signer) acquires BridgeConfig { + initialize(aptos_framework); + assert_is_caller_operator(aptos_framework); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 0x1, location = 0x1::atomic_bridge_configuration)] + /// Tests that an incorrect operator is not validated and results in an abort. + fun test_is_not_valid_operator(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize(aptos_framework); + assert_is_caller_operator(bad); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests we can update the initiator time lock + fun test_update_initiator_time_lock(aptos_framework: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_initiator_time_lock_duration(aptos_framework, 1); + assert!(initiator_timelock_duration() == 1, 0); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests we can update the initiator time lock + fun test_update_counterparty_time_lock(aptos_framework: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_counterparty_time_lock_duration(aptos_framework, 1); + assert!(counterparty_timelock_duration() == 1, 0); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that an incorrect signer cannot update the initiator time lock + fun test_not_able_to_set_initiator_time_lock(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_initiator_time_lock_duration(bad, 1); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that an incorrect signer cannot update the counterparty time lock + fun test_not_able_to_set_counterparty_time_lock(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize(aptos_framework); + set_counterparty_time_lock_duration(bad, 1); + } +} + +module aptos_framework::atomic_bridge { + use std::features; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::atomic_bridge_configuration; + use aptos_framework::atomic_bridge_store; + use aptos_framework::coin; + use aptos_framework::coin::{BurnCapability, MintCapability}; + use aptos_framework::fungible_asset::{BurnRef, MintRef}; + use aptos_framework::system_addresses; + #[test_only] + use aptos_framework::account; + #[test_only] + use aptos_framework::aptos_coin; + #[test_only] + use aptos_framework::timestamp; + + friend aptos_framework::atomic_bridge_counterparty; + friend aptos_framework::atomic_bridge_initiator; + friend aptos_framework::genesis; + + const EATOMIC_BRIDGE_NOT_ENABLED : u64 = 0x1; + + struct AptosCoinBurnCapability has key { + burn_cap: BurnCapability, + } + + struct AptosCoinMintCapability has key { + mint_cap: MintCapability, + } + + struct AptosFABurnCapabilities has key { + burn_ref: BurnRef, + } + + struct AptosFAMintCapabilities has key { + burn_ref: MintRef, + } + + /// Initializes the atomic bridge by setting up necessary configurations. + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize(aptos_framework: &signer) { + atomic_bridge_configuration::initialize(aptos_framework); + atomic_bridge_store::initialize(aptos_framework); + } + + #[test_only] + /// Initializes the atomic bridge for testing purposes, including setting up accounts and timestamps. + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize_for_test(aptos_framework: &signer) { + timestamp::set_time_has_started_for_testing(aptos_framework); + account::create_account_for_test(@aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + initialize(aptos_framework); + + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(aptos_framework); + + store_aptos_coin_mint_cap(aptos_framework, mint_cap); + store_aptos_coin_burn_cap(aptos_framework, burn_cap); + } + + /// Stores the burn capability for AptosCoin, converting to a fungible asset reference if the feature is enabled. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param burn_cap The burn capability for AptosCoin. + public fun store_aptos_coin_burn_cap(aptos_framework: &signer, burn_cap: BurnCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + if (features::operations_default_to_fa_apt_store_enabled()) { + let burn_ref = coin::convert_and_take_paired_burn_ref(burn_cap); + move_to(aptos_framework, AptosFABurnCapabilities { burn_ref }); + } else { + move_to(aptos_framework, AptosCoinBurnCapability { burn_cap }) + } + } + + /// Stores the mint capability for AptosCoin. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param mint_cap The mint capability for AptosCoin. + public fun store_aptos_coin_mint_cap(aptos_framework: &signer, mint_cap: MintCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, AptosCoinMintCapability { mint_cap }) + } + + /// Mints a specified amount of AptosCoin to a recipient's address. + /// + /// @param recipient The address of the recipient to mint coins to. + /// @param amount The amount of AptosCoin to mint. + /// @abort If the mint capability is not available. + public(friend) fun mint(recipient: address, amount: u64) acquires AptosCoinMintCapability { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + coin::deposit(recipient, coin::mint( + amount, + &borrow_global(@aptos_framework).mint_cap + )); + } + + /// Burns a specified amount of AptosCoin from an address. + /// + /// @param from The address from which to burn AptosCoin. + /// @param amount The amount of AptosCoin to burn. + /// @abort If the burn capability is not available. + public(friend) fun burn(from: address, amount: u64) acquires AptosCoinBurnCapability { + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + + coin::burn_from( + from, + amount, + &borrow_global(@aptos_framework).burn_cap, + ); + } +} + +module aptos_framework::atomic_bridge_counterparty { + use aptos_framework::account; + use aptos_framework::atomic_bridge; + use aptos_framework::atomic_bridge_configuration; + use aptos_framework::atomic_bridge_store; + use aptos_framework::atomic_bridge_store::create_hashlock; + use aptos_framework::ethereum; + use aptos_framework::ethereum::EthereumAddress; + use aptos_framework::event::{Self, EventHandle}; + #[test_only] + use aptos_framework::aptos_account; + #[test_only] + use aptos_framework::atomic_bridge::initialize_for_test; + #[test_only] + use aptos_framework::atomic_bridge_store::{valid_bridge_transfer_id, valid_hash_lock, plain_secret}; + #[test_only] + use aptos_framework::ethereum::valid_eip55; + #[test_only] + use aptos_framework::signer; + #[test_only] + use aptos_framework::timestamp; + + #[event] + /// An event triggered upon locking assets for a bridge transfer + struct BridgeTransferLockedEvent has store, drop { + bridge_transfer_id: vector, + initiator: vector, + recipient: address, + amount: u64, + hash_lock: vector, + time_lock: u64, + } + + #[event] + /// An event triggered upon completing a bridge transfer + struct BridgeTransferCompletedEvent has store, drop { + bridge_transfer_id: vector, + pre_image: vector, + } + + #[event] + /// An event triggered upon cancelling a bridge transfer + struct BridgeTransferCancelledEvent has store, drop { + bridge_transfer_id: vector, + } + + /// This struct will store the event handles for bridge events. + struct BridgeCounterpartyEvents has key, store { + bridge_transfer_locked_events: EventHandle, + bridge_transfer_completed_events: EventHandle, + bridge_transfer_cancelled_events: EventHandle, + } + + /// Initializes the module and stores the `EventHandle`s in the resource. + public fun initialize(aptos_framework: &signer) { + move_to(aptos_framework, BridgeCounterpartyEvents { + bridge_transfer_locked_events: account::new_event_handle(aptos_framework), + bridge_transfer_completed_events: account::new_event_handle(aptos_framework), + bridge_transfer_cancelled_events: account::new_event_handle(aptos_framework), + }); + } + + /// Locks assets for a bridge transfer by the initiator. + /// + /// @param caller The signer representing the bridge operator. + /// @param initiator The initiator's Ethereum address as a vector of bytes. + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @param hash_lock The hash lock for securing the transfer. + /// @param time_lock The time lock duration for the transfer. + /// @param recipient The address of the recipient on the Aptos blockchain. + /// @param amount The amount of assets to be locked. + /// @abort If the caller is not the bridge operator. + public entry fun lock_bridge_transfer_assets ( + caller: &signer, + initiator: vector, + bridge_transfer_id: vector, + hash_lock: vector, + recipient: address, + amount: u64 + ) acquires BridgeCounterpartyEvents { + atomic_bridge_configuration::assert_is_caller_operator(caller); + let ethereum_address = ethereum::ethereum_address_no_eip55(initiator); + let time_lock = atomic_bridge_configuration::counterparty_timelock_duration(); + let details = atomic_bridge_store::create_details( + ethereum_address, + recipient, + amount, + hash_lock, + time_lock + ); + + // bridge_store::add_counterparty(bridge_transfer_id, details); + atomic_bridge_store::add(bridge_transfer_id, details); + + let bridge_events = borrow_global_mut(@aptos_framework); + + event::emit_event( + &mut bridge_events.bridge_transfer_locked_events, + BridgeTransferLockedEvent { + bridge_transfer_id, + initiator, + recipient, + amount, + hash_lock, + time_lock, + }, + ); + } + + /// Completes a bridge transfer by revealing the pre-image. + /// + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @param pre_image The pre-image that matches the hash lock to complete the transfer. + /// @abort If the caller is not the bridge operator or the hash lock validation fails. + public entry fun complete_bridge_transfer ( + bridge_transfer_id: vector, + pre_image: vector, + ) acquires BridgeCounterpartyEvents { + let (recipient, amount) = atomic_bridge_store::complete_transfer( + bridge_transfer_id, + create_hashlock(pre_image) + ); + + // Mint, fails silently + atomic_bridge::mint(recipient, amount); + + let bridge_counterparty_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_counterparty_events.bridge_transfer_completed_events, + BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image, + }, + ); + } + + /// Aborts a bridge transfer if the time lock has expired. + /// + /// @param caller The signer representing the bridge operator. + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @abort If the caller is not the bridge operator or if the time lock has not expired. + public entry fun abort_bridge_transfer ( + caller: &signer, + bridge_transfer_id: vector + ) acquires BridgeCounterpartyEvents { + atomic_bridge_configuration::assert_is_caller_operator(caller); + + atomic_bridge_store::cancel_transfer(bridge_transfer_id); + + let bridge_counterparty_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_counterparty_events.bridge_transfer_cancelled_events, + BridgeTransferCancelledEvent { + bridge_transfer_id, + }, + ); + } + + #[test(aptos_framework = @aptos_framework)] + fun test_lock_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + let bridge_counterparty_events = borrow_global(signer::address_of(aptos_framework)); + let lock_events = event::emitted_events_by_handle(&bridge_counterparty_events.bridge_transfer_locked_events); + + // Assert that the event was emitted + let expected_event = BridgeTransferLockedEvent { + bridge_transfer_id, + initiator, + recipient, + amount, + hash_lock, + time_lock: atomic_bridge_configuration::counterparty_timelock_duration(), + }; + assert!(std::vector::contains(&lock_events, &expected_event), 0); + + } + + #[test(aptos_framework = @aptos_framework)] + fun test_abort_transfer_of_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + timestamp::fast_forward_seconds(atomic_bridge_configuration::counterparty_timelock_duration() + 1); + abort_bridge_transfer(aptos_framework, bridge_transfer_id); + + let bridge_counterparty_events = borrow_global(signer::address_of(aptos_framework)); + let cancel_events = event::emitted_events_by_handle(&bridge_counterparty_events.bridge_transfer_cancelled_events); + let expected_event = BridgeTransferCancelledEvent { bridge_transfer_id }; + assert!(std::vector::contains(&cancel_events, &expected_event), 0); + } + + #[test(aptos_framework = @aptos_framework)] + fun test_complete_transfer_of_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + // Create an account for our recipient + aptos_account::create_account(recipient); + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + complete_bridge_transfer(bridge_transfer_id, plain_secret()); + + let bridge_counterparty_events = borrow_global(signer::address_of(aptos_framework)); + let complete_events = event::emitted_events_by_handle(&bridge_counterparty_events.bridge_transfer_completed_events); + let expected_event = BridgeTransferCompletedEvent { + bridge_transfer_id, + pre_image: plain_secret(), + }; + assert!(std::vector::contains(&complete_events, &expected_event), 0); + + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x1, location = atomic_bridge_store)] + fun test_failing_complete_transfer_of_assets(aptos_framework: &signer) acquires BridgeCounterpartyEvents { + initialize_for_test(aptos_framework); + initialize(aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + let initiator = valid_eip55(); + let bridge_transfer_id = valid_bridge_transfer_id(); + let hash_lock = valid_hash_lock(); + let recipient = @0xcafe; + let amount = 1; + + lock_bridge_transfer_assets(aptos_framework, + initiator, + bridge_transfer_id, + hash_lock, + recipient, + amount); + + complete_bridge_transfer(bridge_transfer_id, b"not the secret"); + } +} + diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/block.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/block.move new file mode 100644 index 000000000..589948131 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/block.move @@ -0,0 +1,394 @@ +/// This module defines a struct storing the metadata of the block and new block events. +module aptos_framework::block { + use std::error; + use std::features; + use std::vector; + use std::option; + use aptos_std::table_with_length::{Self, TableWithLength}; + use std::option::Option; + use aptos_framework::randomness; + + use aptos_framework::account; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::reconfiguration; + use aptos_framework::reconfiguration_with_dkg; + use aptos_framework::stake; + use aptos_framework::state_storage; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + use aptos_framework::transaction_fee; + + friend aptos_framework::genesis; + + const MAX_U64: u64 = 18446744073709551615; + + /// Should be in-sync with BlockResource rust struct in new_block.rs + struct BlockResource has key { + /// Height of the current block + height: u64, + /// Time period between epochs. + epoch_interval: u64, + /// Handle where events with the time of new blocks are emitted + new_block_events: EventHandle, + update_epoch_interval_events: EventHandle, + } + + /// Store new block events as a move resource, internally using a circular buffer. + struct CommitHistory has key { + max_capacity: u32, + next_idx: u32, + table: TableWithLength, + } + + /// Should be in-sync with NewBlockEvent rust struct in new_block.rs + struct NewBlockEvent has copy, drop, store { + hash: address, + epoch: u64, + round: u64, + height: u64, + previous_block_votes_bitvec: vector, + proposer: address, + failed_proposer_indices: vector, + /// On-chain time during the block at the given height + time_microseconds: u64, + } + + /// Event emitted when a proposal is created. + struct UpdateEpochIntervalEvent has drop, store { + old_epoch_interval: u64, + new_epoch_interval: u64, + } + + #[event] + /// Should be in-sync with NewBlockEvent rust struct in new_block.rs + struct NewBlock has drop, store { + hash: address, + epoch: u64, + round: u64, + height: u64, + previous_block_votes_bitvec: vector, + proposer: address, + failed_proposer_indices: vector, + /// On-chain time during the block at the given height + time_microseconds: u64, + } + + #[event] + /// Event emitted when a proposal is created. + struct UpdateEpochInterval has drop, store { + old_epoch_interval: u64, + new_epoch_interval: u64, + } + + /// The number of new block events does not equal the current block height. + const ENUM_NEW_BLOCK_EVENTS_DOES_NOT_MATCH_BLOCK_HEIGHT: u64 = 1; + /// An invalid proposer was provided. Expected the proposer to be the VM or an active validator. + const EINVALID_PROPOSER: u64 = 2; + /// Epoch interval cannot be 0. + const EZERO_EPOCH_INTERVAL: u64 = 3; + /// The maximum capacity of the commit history cannot be 0. + const EZERO_MAX_CAPACITY: u64 = 3; + + /// This can only be called during Genesis. + public(friend) fun initialize(aptos_framework: &signer, epoch_interval_microsecs: u64) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(epoch_interval_microsecs > 0, error::invalid_argument(EZERO_EPOCH_INTERVAL)); + + move_to(aptos_framework, CommitHistory { + max_capacity: 2000, + next_idx: 0, + table: table_with_length::new(), + }); + + move_to( + aptos_framework, + BlockResource { + height: 0, + epoch_interval: epoch_interval_microsecs, + new_block_events: account::new_event_handle(aptos_framework), + update_epoch_interval_events: account::new_event_handle(aptos_framework), + } + ); + } + + /// Initialize the commit history resource if it's not in genesis. + public fun initialize_commit_history(fx: &signer, max_capacity: u32) { + assert!(max_capacity > 0, error::invalid_argument(EZERO_MAX_CAPACITY)); + move_to(fx, CommitHistory { + max_capacity, + next_idx: 0, + table: table_with_length::new(), + }); + } + + /// Update the epoch interval. + /// Can only be called as part of the Aptos governance proposal process established by the AptosGovernance module. + public fun update_epoch_interval_microsecs( + aptos_framework: &signer, + new_epoch_interval: u64, + ) acquires BlockResource { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(new_epoch_interval > 0, error::invalid_argument(EZERO_EPOCH_INTERVAL)); + + let block_resource = borrow_global_mut(@aptos_framework); + let old_epoch_interval = block_resource.epoch_interval; + block_resource.epoch_interval = new_epoch_interval; + + if (std::features::module_event_migration_enabled()) { + event::emit( + UpdateEpochInterval { old_epoch_interval, new_epoch_interval }, + ); + }; + event::emit_event( + &mut block_resource.update_epoch_interval_events, + UpdateEpochIntervalEvent { old_epoch_interval, new_epoch_interval }, + ); + } + + #[view] + /// Return epoch interval in seconds. + public fun get_epoch_interval_secs(): u64 acquires BlockResource { + borrow_global(@aptos_framework).epoch_interval / 1000000 + } + + + fun block_prologue_common( + vm: &signer, + hash: address, + epoch: u64, + round: u64, + proposer: address, + failed_proposer_indices: vector, + previous_block_votes_bitvec: vector, + timestamp: u64 + ): u64 acquires BlockResource, CommitHistory { + // Operational constraint: can only be invoked by the VM. + system_addresses::assert_vm(vm); + + // Blocks can only be produced by a valid proposer or by the VM itself for Nil blocks (no user txs). + assert!( + proposer == @vm_reserved || stake::is_current_epoch_validator(proposer), + error::permission_denied(EINVALID_PROPOSER), + ); + + let proposer_index = option::none(); + if (proposer != @vm_reserved) { + proposer_index = option::some(stake::get_validator_index(proposer)); + }; + + let block_metadata_ref = borrow_global_mut(@aptos_framework); + block_metadata_ref.height = event::counter(&block_metadata_ref.new_block_events); + + // Emit both event v1 and v2 for compatibility. Eventually only module events will be kept. + let new_block_event = NewBlockEvent { + hash, + epoch, + round, + height: block_metadata_ref.height, + previous_block_votes_bitvec, + proposer, + failed_proposer_indices, + time_microseconds: timestamp, + }; + let new_block_event_v2 = NewBlock { + hash, + epoch, + round, + height: block_metadata_ref.height, + previous_block_votes_bitvec, + proposer, + failed_proposer_indices, + time_microseconds: timestamp, + }; + emit_new_block_event(vm, &mut block_metadata_ref.new_block_events, new_block_event, new_block_event_v2); + + if (features::collect_and_distribute_gas_fees()) { + // Assign the fees collected from the previous block to the previous block proposer. + // If for any reason the fees cannot be assigned, this function burns the collected coins. + transaction_fee::process_collected_fees(); + // Set the proposer of this block as the receiver of the fees, so that the fees for this + // block are assigned to the right account. + transaction_fee::register_proposer_for_fee_collection(proposer); + }; + + // Performance scores have to be updated before the epoch transition as the transaction that triggers the + // transition is the last block in the previous epoch. + stake::update_performance_statistics(proposer_index, failed_proposer_indices); + state_storage::on_new_block(reconfiguration::current_epoch()); + + block_metadata_ref.epoch_interval + } + + /// Set the metadata for the current block. + /// The runtime always runs this before executing the transactions in a block. + fun block_prologue( + vm: signer, + hash: address, + epoch: u64, + round: u64, + proposer: address, + failed_proposer_indices: vector, + previous_block_votes_bitvec: vector, + timestamp: u64 + ) acquires BlockResource, CommitHistory { + let epoch_interval = block_prologue_common(&vm, hash, epoch, round, proposer, failed_proposer_indices, previous_block_votes_bitvec, timestamp); + randomness::on_new_block(&vm, epoch, round, option::none()); + if (timestamp - reconfiguration::last_reconfiguration_time() >= epoch_interval) { + reconfiguration::reconfigure(); + }; + } + + /// `block_prologue()` but trigger reconfiguration with DKG after epoch timed out. + fun block_prologue_ext( + vm: signer, + hash: address, + epoch: u64, + round: u64, + proposer: address, + failed_proposer_indices: vector, + previous_block_votes_bitvec: vector, + timestamp: u64, + randomness_seed: Option>, + ) acquires BlockResource, CommitHistory { + let epoch_interval = block_prologue_common( + &vm, + hash, + epoch, + round, + proposer, + failed_proposer_indices, + previous_block_votes_bitvec, + timestamp + ); + randomness::on_new_block(&vm, epoch, round, randomness_seed); + + if (timestamp - reconfiguration::last_reconfiguration_time() >= epoch_interval) { + reconfiguration_with_dkg::try_start(); + }; + } + + #[view] + /// Get the current block height + public fun get_current_block_height(): u64 acquires BlockResource { + borrow_global(@aptos_framework).height + } + + /// Emit the event and update height and global timestamp + fun emit_new_block_event( + vm: &signer, + event_handle: &mut EventHandle, + new_block_event: NewBlockEvent, + new_block_event_v2: NewBlock + ) acquires CommitHistory { + if (exists(@aptos_framework)) { + let commit_history_ref = borrow_global_mut(@aptos_framework); + let idx = commit_history_ref.next_idx; + if (table_with_length::contains(&commit_history_ref.table, idx)) { + table_with_length::remove(&mut commit_history_ref.table, idx); + }; + table_with_length::add(&mut commit_history_ref.table, idx, copy new_block_event); + spec { + assume idx + 1 <= MAX_U32; + }; + commit_history_ref.next_idx = (idx + 1) % commit_history_ref.max_capacity; + }; + timestamp::update_global_time(vm, new_block_event.proposer, new_block_event.time_microseconds); + assert!( + event::counter(event_handle) == new_block_event.height, + error::invalid_argument(ENUM_NEW_BLOCK_EVENTS_DOES_NOT_MATCH_BLOCK_HEIGHT), + ); + if (std::features::module_event_migration_enabled()) { + event::emit(new_block_event_v2); + }; + event::emit_event(event_handle, new_block_event); + } + + /// Emit a `NewBlockEvent` event. This function will be invoked by genesis directly to generate the very first + /// reconfiguration event. + fun emit_genesis_block_event(vm: signer) acquires BlockResource, CommitHistory { + let block_metadata_ref = borrow_global_mut(@aptos_framework); + let genesis_id = @0x0; + emit_new_block_event( + &vm, + &mut block_metadata_ref.new_block_events, + NewBlockEvent { + hash: genesis_id, + epoch: 0, + round: 0, + height: 0, + previous_block_votes_bitvec: vector::empty(), + proposer: @vm_reserved, + failed_proposer_indices: vector::empty(), + time_microseconds: 0, + }, + NewBlock { + hash: genesis_id, + epoch: 0, + round: 0, + height: 0, + previous_block_votes_bitvec: vector::empty(), + proposer: @vm_reserved, + failed_proposer_indices: vector::empty(), + time_microseconds: 0, + } + ); + } + + /// Emit a `NewBlockEvent` event. This function will be invoked by write set script directly to generate the + /// new block event for WriteSetPayload. + public fun emit_writeset_block_event(vm_signer: &signer, fake_block_hash: address) acquires BlockResource, CommitHistory { + system_addresses::assert_vm(vm_signer); + let block_metadata_ref = borrow_global_mut(@aptos_framework); + block_metadata_ref.height = event::counter(&block_metadata_ref.new_block_events); + + emit_new_block_event( + vm_signer, + &mut block_metadata_ref.new_block_events, + NewBlockEvent { + hash: fake_block_hash, + epoch: reconfiguration::current_epoch(), + round: MAX_U64, + height: block_metadata_ref.height, + previous_block_votes_bitvec: vector::empty(), + proposer: @vm_reserved, + failed_proposer_indices: vector::empty(), + time_microseconds: timestamp::now_microseconds(), + }, + NewBlock { + hash: fake_block_hash, + epoch: reconfiguration::current_epoch(), + round: MAX_U64, + height: block_metadata_ref.height, + previous_block_votes_bitvec: vector::empty(), + proposer: @vm_reserved, + failed_proposer_indices: vector::empty(), + time_microseconds: timestamp::now_microseconds(), + } + ); + } + + #[test_only] + public fun initialize_for_test(account: &signer, epoch_interval_microsecs: u64) { + initialize(account, epoch_interval_microsecs); + } + + #[test(aptos_framework = @aptos_framework)] + public entry fun test_update_epoch_interval(aptos_framework: signer) acquires BlockResource { + account::create_account_for_test(@aptos_framework); + initialize(&aptos_framework, 1); + assert!(borrow_global(@aptos_framework).epoch_interval == 1, 0); + update_epoch_interval_microsecs(&aptos_framework, 2); + assert!(borrow_global(@aptos_framework).epoch_interval == 2, 1); + } + + #[test(aptos_framework = @aptos_framework, account = @0x123)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + public entry fun test_update_epoch_interval_unauthorized_should_fail( + aptos_framework: signer, + account: signer, + ) acquires BlockResource { + account::create_account_for_test(@aptos_framework); + initialize(&aptos_framework, 1); + update_epoch_interval_microsecs(&account, 2); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/chain_id.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/chain_id.move new file mode 100644 index 000000000..c71109744 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/chain_id.move @@ -0,0 +1,41 @@ +/// The chain id distinguishes between different chains (e.g., testnet and the main network). +/// One important role is to prevent transactions intended for one chain from being executed on another. +/// This code provides a container for storing a chain id and functions to initialize and get it. +module aptos_framework::chain_id { + use aptos_framework::system_addresses; + + friend aptos_framework::genesis; + + struct ChainId has key { + id: u8 + } + + /// Only called during genesis. + /// Publish the chain ID `id` of this instance under the SystemAddresses address + public(friend) fun initialize(aptos_framework: &signer, id: u8) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, ChainId { id }) + } + + #[view] + /// Return the chain ID of this instance. + public fun get(): u8 acquires ChainId { + borrow_global(@aptos_framework).id + } + + #[test_only] + use std::signer; + + #[test_only] + public fun initialize_for_test(aptos_framework: &signer, id: u8) { + if (!exists(signer::address_of(aptos_framework))) { + initialize(aptos_framework, id); + } + } + + #[test(aptos_framework = @0x1)] + fun test_get(aptos_framework: &signer) acquires ChainId { + initialize_for_test(aptos_framework, 1u8); + assert!(get() == 1u8, 1); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/chain_status.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/chain_status.move new file mode 100644 index 000000000..a2ddd72de --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/chain_status.move @@ -0,0 +1,48 @@ +/// This module code to assert that it is running in genesis (`Self::assert_genesis`) or after +/// genesis (`Self::assert_operating`). These are essentially distinct states of the system. Specifically, +/// if `Self::assert_operating` succeeds, assumptions about invariants over the global state can be made +/// which reflect that the system has been successfully initialized. +module aptos_framework::chain_status { + use aptos_framework::system_addresses; + use std::error; + + friend aptos_framework::genesis; + + /// Marker to publish at the end of genesis. + struct GenesisEndMarker has key {} + + /// The blockchain is not in the operating status. + const ENOT_OPERATING: u64 = 1; + /// The blockchain is not in the genesis status. + const ENOT_GENESIS: u64 = 2; + + /// Marks that genesis has finished. + public(friend) fun set_genesis_end(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, GenesisEndMarker {}); + } + + #[view] + /// Helper function to determine if Aptos is in genesis state. + public fun is_genesis(): bool { + !exists(@aptos_framework) + } + + #[view] + /// Helper function to determine if Aptos is operating. This is + /// the same as `!is_genesis()` and is provided for convenience. + /// Testing `is_operating()` is more frequent than `is_genesis()`. + public fun is_operating(): bool { + exists(@aptos_framework) + } + + /// Helper function to assert operating (not genesis) state. + public fun assert_operating() { + assert!(is_operating(), error::invalid_state(ENOT_OPERATING)); + } + + /// Helper function to assert genesis state. + public fun assert_genesis() { + assert!(is_genesis(), error::invalid_state(ENOT_GENESIS)); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/code.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/code.move new file mode 100644 index 000000000..181c12b94 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/code.move @@ -0,0 +1,359 @@ +/// This module supports functionality related to code management. +module aptos_framework::code { + use std::string::String; + use std::error; + use std::signer; + use std::vector; + use std::features; + + use aptos_framework::util; + use aptos_framework::system_addresses; + use aptos_std::copyable_any::Any; + use std::option::Option; + use std::string; + use aptos_framework::event; + use aptos_framework::object::{Self, Object}; + + // ---------------------------------------------------------------------- + // Code Publishing + + /// The package registry at the given address. + struct PackageRegistry has key, store, drop { + /// Packages installed at this address. + packages: vector, + } + + /// Metadata for a package. All byte blobs are represented as base64-of-gzipped-bytes + struct PackageMetadata has store, drop { + /// Name of this package. + name: String, + /// The upgrade policy of this package. + upgrade_policy: UpgradePolicy, + /// The numbers of times this module has been upgraded. Also serves as the on-chain version. + /// This field will be automatically assigned on successful upgrade. + upgrade_number: u64, + /// The source digest of the sources in the package. This is constructed by first building the + /// sha256 of each individual source, than sorting them alphabetically, and sha256 them again. + source_digest: String, + /// The package manifest, in the Move.toml format. Gzipped text. + manifest: vector, + /// The list of modules installed by this package. + modules: vector, + /// Holds PackageDeps. + deps: vector, + /// For future extension + extension: Option + } + + /// A dependency to a package published at address + struct PackageDep has store, drop, copy { + account: address, + package_name: String + } + + /// Metadata about a module in a package. + struct ModuleMetadata has store, drop { + /// Name of the module. + name: String, + /// Source text, gzipped String. Empty if not provided. + source: vector, + /// Source map, in compressed BCS. Empty if not provided. + source_map: vector, + /// For future extensions. + extension: Option, + } + + /// Describes an upgrade policy + struct UpgradePolicy has store, copy, drop { + policy: u8 + } + + #[event] + /// Event emitted when code is published to an address. + struct PublishPackage has drop, store { + code_address: address, + is_upgrade: bool, + } + + /// Package contains duplicate module names with existing modules publised in other packages on this address + const EMODULE_NAME_CLASH: u64 = 0x1; + + /// Cannot upgrade an immutable package + const EUPGRADE_IMMUTABLE: u64 = 0x2; + + /// Cannot downgrade a package's upgradability policy + const EUPGRADE_WEAKER_POLICY: u64 = 0x3; + + /// Cannot delete a module that was published in the same package + const EMODULE_MISSING: u64 = 0x4; + + /// Dependency could not be resolved to any published package. + const EPACKAGE_DEP_MISSING: u64 = 0x5; + + /// A dependency cannot have a weaker upgrade policy. + const EDEP_WEAKER_POLICY: u64 = 0x6; + + /// A dependency to an `arbitrary` package must be on the same address. + const EDEP_ARBITRARY_NOT_SAME_ADDRESS: u64 = 0x7; + + /// Creating a package with incompatible upgrade policy is disabled. + const EINCOMPATIBLE_POLICY_DISABLED: u64 = 0x8; + + /// Not the owner of the package registry. + const ENOT_PACKAGE_OWNER: u64 = 0x9; + + /// `code_object` does not exist. + const ECODE_OBJECT_DOES_NOT_EXIST: u64 = 0xA; + + /// Whether unconditional code upgrade with no compatibility check is allowed. This + /// publication mode should only be used for modules which aren't shared with user others. + /// The developer is responsible for not breaking memory layout of any resources he already + /// stored on chain. + public fun upgrade_policy_arbitrary(): UpgradePolicy { + UpgradePolicy { policy: 0 } + } + + /// Whether a compatibility check should be performed for upgrades. The check only passes if + /// a new module has (a) the same public functions (b) for existing resources, no layout change. + public fun upgrade_policy_compat(): UpgradePolicy { + UpgradePolicy { policy: 1 } + } + + /// Whether the modules in the package are immutable and cannot be upgraded. + public fun upgrade_policy_immutable(): UpgradePolicy { + UpgradePolicy { policy: 2 } + } + + /// Whether the upgrade policy can be changed. In general, the policy can be only + /// strengthened but not weakened. + public fun can_change_upgrade_policy_to(from: UpgradePolicy, to: UpgradePolicy): bool { + from.policy <= to.policy + } + + /// Initialize package metadata for Genesis. + fun initialize(aptos_framework: &signer, package_owner: &signer, metadata: PackageMetadata) + acquires PackageRegistry { + system_addresses::assert_aptos_framework(aptos_framework); + let addr = signer::address_of(package_owner); + if (!exists(addr)) { + move_to(package_owner, PackageRegistry { packages: vector[metadata] }) + } else { + vector::push_back(&mut borrow_global_mut(addr).packages, metadata) + } + } + + /// Publishes a package at the given signer's address. The caller must provide package metadata describing the + /// package. + public fun publish_package(owner: &signer, pack: PackageMetadata, code: vector>) acquires PackageRegistry { + // Disallow incompatible upgrade mode. Governance can decide later if this should be reconsidered. + assert!( + pack.upgrade_policy.policy > upgrade_policy_arbitrary().policy, + error::invalid_argument(EINCOMPATIBLE_POLICY_DISABLED), + ); + + let addr = signer::address_of(owner); + if (!exists(addr)) { + move_to(owner, PackageRegistry { packages: vector::empty() }) + }; + + // Checks for valid dependencies to other packages + let allowed_deps = check_dependencies(addr, &pack); + + // Check package against conflicts + // To avoid prover compiler error on spec + // the package need to be an immutable variable + let module_names = get_module_names(&pack); + let package_immutable = &borrow_global(addr).packages; + let len = vector::length(package_immutable); + let index = len; + let upgrade_number = 0; + vector::enumerate_ref(package_immutable + , |i, old| { + let old: &PackageMetadata = old; + if (old.name == pack.name) { + upgrade_number = old.upgrade_number + 1; + check_upgradability(old, &pack, &module_names); + index = i; + } else { + check_coexistence(old, &module_names) + }; + }); + + // Assign the upgrade counter. + pack.upgrade_number = upgrade_number; + + let packages = &mut borrow_global_mut(addr).packages; + // Update registry + let policy = pack.upgrade_policy; + if (index < len) { + *vector::borrow_mut(packages, index) = pack + } else { + vector::push_back(packages, pack) + }; + + event::emit(PublishPackage { + code_address: addr, + is_upgrade: upgrade_number > 0 + }); + + // Request publish + if (features::code_dependency_check_enabled()) + request_publish_with_allowed_deps(addr, module_names, allowed_deps, code, policy.policy) + else + // The new `request_publish_with_allowed_deps` has not yet rolled out, so call downwards + // compatible code. + request_publish(addr, module_names, code, policy.policy) + } + + public fun freeze_code_object(publisher: &signer, code_object: Object) acquires PackageRegistry { + let code_object_addr = object::object_address(&code_object); + assert!(exists(code_object_addr), error::not_found(ECODE_OBJECT_DOES_NOT_EXIST)); + assert!( + object::is_owner(code_object, signer::address_of(publisher)), + error::permission_denied(ENOT_PACKAGE_OWNER) + ); + + let registry = borrow_global_mut(code_object_addr); + vector::for_each_mut(&mut registry.packages, |pack| { + let package: &mut PackageMetadata = pack; + package.upgrade_policy = upgrade_policy_immutable(); + }); + } + + /// Same as `publish_package` but as an entry function which can be called as a transaction. Because + /// of current restrictions for txn parameters, the metadata needs to be passed in serialized form. + public entry fun publish_package_txn(owner: &signer, metadata_serialized: vector, code: vector>) + acquires PackageRegistry { + publish_package(owner, util::from_bytes(metadata_serialized), code) + } + + // Helpers + // ------- + + /// Checks whether the given package is upgradable, and returns true if a compatibility check is needed. + fun check_upgradability( + old_pack: &PackageMetadata, new_pack: &PackageMetadata, new_modules: &vector) { + assert!(old_pack.upgrade_policy.policy < upgrade_policy_immutable().policy, + error::invalid_argument(EUPGRADE_IMMUTABLE)); + assert!(can_change_upgrade_policy_to(old_pack.upgrade_policy, new_pack.upgrade_policy), + error::invalid_argument(EUPGRADE_WEAKER_POLICY)); + let old_modules = get_module_names(old_pack); + + vector::for_each_ref(&old_modules, |old_module| { + assert!( + vector::contains(new_modules, old_module), + EMODULE_MISSING + ); + }); + } + + /// Checks whether a new package with given names can co-exist with old package. + fun check_coexistence(old_pack: &PackageMetadata, new_modules: &vector) { + // The modules introduced by each package must not overlap with `names`. + vector::for_each_ref(&old_pack.modules, |old_mod| { + let old_mod: &ModuleMetadata = old_mod; + let j = 0; + while (j < vector::length(new_modules)) { + let name = vector::borrow(new_modules, j); + assert!(&old_mod.name != name, error::already_exists(EMODULE_NAME_CLASH)); + j = j + 1; + }; + }); + } + + /// Check that the upgrade policies of all packages are equal or higher quality than this package. Also + /// compute the list of module dependencies which are allowed by the package metadata. The later + /// is passed on to the native layer to verify that bytecode dependencies are actually what is pretended here. + fun check_dependencies(publish_address: address, pack: &PackageMetadata): vector + acquires PackageRegistry { + let allowed_module_deps = vector::empty(); + let deps = &pack.deps; + vector::for_each_ref(deps, |dep| { + let dep: &PackageDep = dep; + assert!(exists(dep.account), error::not_found(EPACKAGE_DEP_MISSING)); + if (is_policy_exempted_address(dep.account)) { + // Allow all modules from this address, by using "" as a wildcard in the AllowedDep + let account: address = dep.account; + let module_name = string::utf8(b""); + vector::push_back(&mut allowed_module_deps, AllowedDep { account, module_name }); + } else { + let registry = borrow_global(dep.account); + let found = vector::any(®istry.packages, |dep_pack| { + let dep_pack: &PackageMetadata = dep_pack; + if (dep_pack.name == dep.package_name) { + // Check policy + assert!( + dep_pack.upgrade_policy.policy >= pack.upgrade_policy.policy, + error::invalid_argument(EDEP_WEAKER_POLICY) + ); + if (dep_pack.upgrade_policy == upgrade_policy_arbitrary()) { + assert!( + dep.account == publish_address, + error::invalid_argument(EDEP_ARBITRARY_NOT_SAME_ADDRESS) + ) + }; + // Add allowed deps + let account = dep.account; + let k = 0; + let r = vector::length(&dep_pack.modules); + while (k < r) { + let module_name = vector::borrow(&dep_pack.modules, k).name; + vector::push_back(&mut allowed_module_deps, AllowedDep { account, module_name }); + k = k + 1; + }; + true + } else { + false + } + }); + assert!(found, error::not_found(EPACKAGE_DEP_MISSING)); + }; + }); + allowed_module_deps + } + + /// Core addresses which are exempted from the check that their policy matches the referring package. Without + /// this exemption, it would not be possible to define an immutable package based on the core system, which + /// requires to be upgradable for maintenance and evolution, and is configured to be `compatible`. + fun is_policy_exempted_address(addr: address): bool { + addr == @1 || addr == @2 || addr == @3 || addr == @4 || addr == @5 || + addr == @6 || addr == @7 || addr == @8 || addr == @9 || addr == @10 + } + + /// Get the names of the modules in a package. + fun get_module_names(pack: &PackageMetadata): vector { + let module_names = vector::empty(); + vector::for_each_ref(&pack.modules, |pack_module| { + let pack_module: &ModuleMetadata = pack_module; + vector::push_back(&mut module_names, pack_module.name); + }); + module_names + } + + /// Native function to initiate module loading + native fun request_publish( + owner: address, + expected_modules: vector, + bundle: vector>, + policy: u8 + ); + + /// A helper type for request_publish_with_allowed_deps + struct AllowedDep has drop { + /// Address of the module. + account: address, + /// Name of the module. If this is the empty string, then this serves as a wildcard for + /// all modules from this address. This is used for speeding up dependency checking for packages from + /// well-known framework addresses, where we can assume that there are no malicious packages. + module_name: String + } + + /// Native function to initiate module loading, including a list of allowed dependencies. + native fun request_publish_with_allowed_deps( + owner: address, + expected_modules: vector, + allowed_deps: vector, + bundle: vector>, + policy: u8 + ); +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/coin.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/coin.move new file mode 100644 index 000000000..d4e9d1207 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/coin.move @@ -0,0 +1,2259 @@ +/// This module provides the foundation for typesafe Coins. +module aptos_framework::coin { + use std::error; + use std::features; + use std::option::{Self, Option}; + use std::signer; + use std::string::{Self, String}; + use aptos_std::table::{Self, Table}; + + use aptos_framework::account; + use aptos_framework::aggregator_factory; + use aptos_framework::aggregator::{Self, Aggregator}; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::guid; + use aptos_framework::optional_aggregator::{Self, OptionalAggregator}; + use aptos_framework::system_addresses; + + use aptos_framework::fungible_asset::{Self, FungibleAsset, Metadata, MintRef, TransferRef, BurnRef}; + use aptos_framework::object::{Self, Object, object_address}; + use aptos_framework::primary_fungible_store; + use aptos_std::type_info::{Self, TypeInfo, type_name}; + use aptos_framework::create_signer; + + friend aptos_framework::aptos_coin; + friend aptos_framework::genesis; + friend aptos_framework::transaction_fee; + friend aptos_framework::governed_gas_pool; + + // + // Errors. + // + + /// Address of account which is used to initialize a coin `CoinType` doesn't match the deployer of module + const ECOIN_INFO_ADDRESS_MISMATCH: u64 = 1; + + /// `CoinType` is already initialized as a coin + const ECOIN_INFO_ALREADY_PUBLISHED: u64 = 2; + + /// `CoinType` hasn't been initialized as a coin + const ECOIN_INFO_NOT_PUBLISHED: u64 = 3; + + /// Deprecated. Account already has `CoinStore` registered for `CoinType` + const ECOIN_STORE_ALREADY_PUBLISHED: u64 = 4; + + /// Account hasn't registered `CoinStore` for `CoinType` + const ECOIN_STORE_NOT_PUBLISHED: u64 = 5; + + /// Not enough coins to complete transaction + const EINSUFFICIENT_BALANCE: u64 = 6; + + /// Cannot destroy non-zero coins + const EDESTRUCTION_OF_NONZERO_TOKEN: u64 = 7; + + /// CoinStore is frozen. Coins cannot be deposited or withdrawn + const EFROZEN: u64 = 10; + + /// Cannot upgrade the total supply of coins to different implementation. + const ECOIN_SUPPLY_UPGRADE_NOT_SUPPORTED: u64 = 11; + + /// Name of the coin is too long + const ECOIN_NAME_TOO_LONG: u64 = 12; + + /// Symbol of the coin is too long + const ECOIN_SYMBOL_TOO_LONG: u64 = 13; + + /// The value of aggregatable coin used for transaction fees redistribution does not fit in u64. + const EAGGREGATABLE_COIN_VALUE_TOO_LARGE: u64 = 14; + + /// Error regarding paired coin type of the fungible asset metadata. + const EPAIRED_COIN: u64 = 15; + + /// Error regarding paired fungible asset metadata of a coin type. + const EPAIRED_FUNGIBLE_ASSET: u64 = 16; + + /// The coin type from the map does not match the calling function type argument. + const ECOIN_TYPE_MISMATCH: u64 = 17; + + /// The feature of migration from coin to fungible asset is not enabled. + const ECOIN_TO_FUNGIBLE_ASSET_FEATURE_NOT_ENABLED: u64 = 18; + + /// PairedFungibleAssetRefs resource does not exist. + const EPAIRED_FUNGIBLE_ASSET_REFS_NOT_FOUND: u64 = 19; + + /// The MintRefReceipt does not match the MintRef to be returned. + const EMINT_REF_RECEIPT_MISMATCH: u64 = 20; + + /// The MintRef does not exist. + const EMINT_REF_NOT_FOUND: u64 = 21; + + /// The TransferRefReceipt does not match the TransferRef to be returned. + const ETRANSFER_REF_RECEIPT_MISMATCH: u64 = 22; + + /// The TransferRef does not exist. + const ETRANSFER_REF_NOT_FOUND: u64 = 23; + + /// The BurnRefReceipt does not match the BurnRef to be returned. + const EBURN_REF_RECEIPT_MISMATCH: u64 = 24; + + /// The BurnRef does not exist. + const EBURN_REF_NOT_FOUND: u64 = 25; + + /// The migration process from coin to fungible asset is not enabled yet. + const EMIGRATION_FRAMEWORK_NOT_ENABLED: u64 = 26; + + /// The coin converison map is not created yet. + const ECOIN_CONVERSION_MAP_NOT_FOUND: u64 = 27; + + /// APT pairing is not eanbled yet. + const EAPT_PAIRING_IS_NOT_ENABLED: u64 = 28; + + // + // Constants + // + + const MAX_COIN_NAME_LENGTH: u64 = 32; + const MAX_COIN_SYMBOL_LENGTH: u64 = 10; + + /// Core data structures + + /// Main structure representing a coin/token in an account's custody. + struct Coin has store { + /// Amount of coin this address has. + value: u64, + } + + /// Represents a coin with aggregator as its value. This allows to update + /// the coin in every transaction avoiding read-modify-write conflicts. Only + /// used for gas fees distribution by Aptos Framework (0x1). + struct AggregatableCoin has store { + /// Amount of aggregatable coin this address has. + value: Aggregator, + } + + /// Maximum possible aggregatable coin value. + const MAX_U64: u128 = 18446744073709551615; + + /// A holder of a specific coin types and associated event handles. + /// These are kept in a single resource to ensure locality of data. + struct CoinStore has key { + coin: Coin, + frozen: bool, + deposit_events: EventHandle, + withdraw_events: EventHandle, + } + + /// Maximum possible coin supply. + const MAX_U128: u128 = 340282366920938463463374607431768211455; + + /// Configuration that controls the behavior of total coin supply. If the field + /// is set, coin creators are allowed to upgrade to parallelizable implementations. + struct SupplyConfig has key { + allow_upgrades: bool, + } + + /// Information about a specific coin type. Stored on the creator of the coin's account. + struct CoinInfo has key { + name: String, + /// Symbol of the coin, usually a shorter version of the name. + /// For example, Singapore Dollar is SGD. + symbol: String, + /// Number of decimals used to get its user representation. + /// For example, if `decimals` equals `2`, a balance of `505` coins should + /// be displayed to a user as `5.05` (`505 / 10 ** 2`). + decimals: u8, + /// Amount of this coin type in existence. + supply: Option, + } + + + #[event] + /// Module event emitted when some amount of a coin is deposited into an account. + struct CoinDeposit has drop, store { + coin_type: String, + account: address, + amount: u64, + } + + #[event] + /// Module event emitted when some amount of a coin is withdrawn from an account. + struct CoinWithdraw has drop, store { + coin_type: String, + account: address, + amount: u64, + } + + // DEPRECATED, NEVER USED + #[deprecated] + #[event] + struct Deposit has drop, store { + account: address, + amount: u64, + } + + // DEPRECATED, NEVER USED + #[deprecated] + #[event] + struct Withdraw has drop, store { + account: address, + amount: u64, + } + + /// Event emitted when some amount of a coin is deposited into an account. + struct DepositEvent has drop, store { + amount: u64, + } + + /// Event emitted when some amount of a coin is withdrawn from an account. + struct WithdrawEvent has drop, store { + amount: u64, + } + + + #[event] + /// Module event emitted when the event handles related to coin store is deleted. + struct CoinEventHandleDeletion has drop, store { + event_handle_creation_address: address, + deleted_deposit_event_handle_creation_number: u64, + deleted_withdraw_event_handle_creation_number: u64, + } + + #[event] + /// Module event emitted when a new pair of coin and fungible asset is created. + struct PairCreation has drop, store { + coin_type: TypeInfo, + fungible_asset_metadata_address: address, + } + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// The flag the existence of which indicates the primary fungible store is created by the migration from CoinStore. + struct MigrationFlag has key {} + + /// Capability required to mint coins. + struct MintCapability has copy, store {} + + /// Capability required to freeze a coin store. + struct FreezeCapability has copy, store {} + + /// Capability required to burn coins. + struct BurnCapability has copy, store {} + + /// The mapping between coin and fungible asset. + struct CoinConversionMap has key { + coin_to_fungible_asset_map: Table>, + } + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// The paired coin type info stored in fungible asset metadata object. + struct PairedCoinType has key { + type: TypeInfo, + } + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// The refs of the paired fungible asset. + struct PairedFungibleAssetRefs has key { + mint_ref_opt: Option, + transfer_ref_opt: Option, + burn_ref_opt: Option, + } + + /// The hot potato receipt for flash borrowing MintRef. + struct MintRefReceipt { + metadata: Object, + } + + /// The hot potato receipt for flash borrowing TransferRef. + struct TransferRefReceipt { + metadata: Object, + } + + /// The hot potato receipt for flash borrowing BurnRef. + struct BurnRefReceipt { + metadata: Object, + } + + #[view] + /// Get the paired fungible asset metadata object of a coin type. If not exist, return option::none(). + public fun paired_metadata(): Option> acquires CoinConversionMap { + if (exists(@aptos_framework) && features::coin_to_fungible_asset_migration_feature_enabled( + )) { + let map = &borrow_global(@aptos_framework).coin_to_fungible_asset_map; + let type = type_info::type_of(); + if (table::contains(map, type)) { + return option::some(*table::borrow(map, type)) + } + }; + option::none() + } + + public entry fun create_coin_conversion_map(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + if (!exists(@aptos_framework)) { + move_to(aptos_framework, CoinConversionMap { + coin_to_fungible_asset_map: table::new(), + }) + }; + } + + /// Create APT pairing by passing `AptosCoin`. + public entry fun create_pairing( + aptos_framework: &signer + ) acquires CoinConversionMap, CoinInfo { + system_addresses::assert_aptos_framework(aptos_framework); + create_and_return_paired_metadata_if_not_exist(true); + } + + inline fun is_apt(): bool { + type_info::type_name() == string::utf8(b"0x1::aptos_coin::AptosCoin") + } + + inline fun create_and_return_paired_metadata_if_not_exist(allow_apt_creation: bool): Object { + assert!( + features::coin_to_fungible_asset_migration_feature_enabled(), + error::invalid_state(EMIGRATION_FRAMEWORK_NOT_ENABLED) + ); + assert!(exists(@aptos_framework), error::not_found(ECOIN_CONVERSION_MAP_NOT_FOUND)); + let map = borrow_global_mut(@aptos_framework); + let type = type_info::type_of(); + if (!table::contains(&map.coin_to_fungible_asset_map, type)) { + let is_apt = is_apt(); + assert!(!is_apt || allow_apt_creation, error::invalid_state(EAPT_PAIRING_IS_NOT_ENABLED)); + let metadata_object_cref = + if (is_apt) { + object::create_sticky_object_at_address(@aptos_framework, @aptos_fungible_asset) + } else { + object::create_named_object( + &create_signer::create_signer(@aptos_fungible_asset), + *string::bytes(&type_info::type_name()) + ) + }; + primary_fungible_store::create_primary_store_enabled_fungible_asset( + &metadata_object_cref, + option::map(coin_supply(), |_| MAX_U128), + name(), + symbol(), + decimals(), + string::utf8(b""), + string::utf8(b""), + ); + + let metadata_object_signer = &object::generate_signer(&metadata_object_cref); + let type = type_info::type_of(); + move_to(metadata_object_signer, PairedCoinType { type }); + let metadata_obj = object::object_from_constructor_ref(&metadata_object_cref); + + table::add(&mut map.coin_to_fungible_asset_map, type, metadata_obj); + event::emit(PairCreation { + coin_type: type, + fungible_asset_metadata_address: object_address(&metadata_obj) + }); + + // Generates all three refs + let mint_ref = fungible_asset::generate_mint_ref(&metadata_object_cref); + let transfer_ref = fungible_asset::generate_transfer_ref(&metadata_object_cref); + let burn_ref = fungible_asset::generate_burn_ref(&metadata_object_cref); + move_to(metadata_object_signer, + PairedFungibleAssetRefs { + mint_ref_opt: option::some(mint_ref), + transfer_ref_opt: option::some(transfer_ref), + burn_ref_opt: option::some(burn_ref), + } + ); + }; + *table::borrow(&map.coin_to_fungible_asset_map, type) + } + + /// Get the paired fungible asset metadata object of a coin type, create if not exist. + public(friend) fun ensure_paired_metadata(): Object acquires CoinConversionMap, CoinInfo { + create_and_return_paired_metadata_if_not_exist(false) + } + + #[view] + /// Get the paired coin type of a fungible asset metadata object. + public fun paired_coin(metadata: Object): Option acquires PairedCoinType { + let metadata_addr = object::object_address(&metadata); + if (exists(metadata_addr)) { + option::some(borrow_global(metadata_addr).type) + } else { + option::none() + } + } + + /// Conversion from coin to fungible asset + public fun coin_to_fungible_asset( + coin: Coin + ): FungibleAsset acquires CoinConversionMap, CoinInfo { + let metadata = ensure_paired_metadata(); + let amount = burn_internal(coin); + fungible_asset::mint_internal(metadata, amount) + } + + /// Conversion from fungible asset to coin. Not public to push the migration to FA. + fun fungible_asset_to_coin( + fungible_asset: FungibleAsset + ): Coin acquires CoinInfo, PairedCoinType { + let metadata_addr = object::object_address(&fungible_asset::metadata_from_asset(&fungible_asset)); + assert!( + object::object_exists(metadata_addr), + error::not_found(EPAIRED_COIN) + ); + let coin_type_info = borrow_global(metadata_addr).type; + assert!(coin_type_info == type_info::type_of(), error::invalid_argument(ECOIN_TYPE_MISMATCH)); + let amount = fungible_asset::burn_internal(fungible_asset); + mint_internal(amount) + } + + inline fun assert_paired_metadata_exists(): Object { + let metadata_opt = paired_metadata(); + assert!(option::is_some(&metadata_opt), error::not_found(EPAIRED_FUNGIBLE_ASSET)); + option::destroy_some(metadata_opt) + } + + #[view] + /// Check whether `MintRef` has not been taken. + public fun paired_mint_ref_exists(): bool acquires CoinConversionMap, PairedFungibleAssetRefs { + let metadata = assert_paired_metadata_exists(); + let metadata_addr = object_address(&metadata); + assert!(exists(metadata_addr), error::internal(EPAIRED_FUNGIBLE_ASSET_REFS_NOT_FOUND)); + option::is_some(&borrow_global(metadata_addr).mint_ref_opt) + } + + /// Get the `MintRef` of paired fungible asset of a coin type from `MintCapability`. + public fun get_paired_mint_ref( + _: &MintCapability + ): (MintRef, MintRefReceipt) acquires CoinConversionMap, PairedFungibleAssetRefs { + let metadata = assert_paired_metadata_exists(); + let metadata_addr = object_address(&metadata); + assert!(exists(metadata_addr), error::internal(EPAIRED_FUNGIBLE_ASSET_REFS_NOT_FOUND)); + let mint_ref_opt = &mut borrow_global_mut(metadata_addr).mint_ref_opt; + assert!(option::is_some(mint_ref_opt), error::not_found(EMINT_REF_NOT_FOUND)); + (option::extract(mint_ref_opt), MintRefReceipt { metadata }) + } + + /// Return the `MintRef` with the hot potato receipt. + public fun return_paired_mint_ref(mint_ref: MintRef, receipt: MintRefReceipt) acquires PairedFungibleAssetRefs { + let MintRefReceipt { metadata } = receipt; + assert!( + fungible_asset::mint_ref_metadata(&mint_ref) == metadata, + error::invalid_argument(EMINT_REF_RECEIPT_MISMATCH) + ); + let metadata_addr = object_address(&metadata); + let mint_ref_opt = &mut borrow_global_mut(metadata_addr).mint_ref_opt; + option::fill(mint_ref_opt, mint_ref); + } + + #[view] + /// Check whether `TransferRef` still exists. + public fun paired_transfer_ref_exists(): bool acquires CoinConversionMap, PairedFungibleAssetRefs { + let metadata = assert_paired_metadata_exists(); + let metadata_addr = object_address(&metadata); + assert!(exists(metadata_addr), error::internal(EPAIRED_FUNGIBLE_ASSET_REFS_NOT_FOUND)); + option::is_some(&borrow_global(metadata_addr).transfer_ref_opt) + } + + /// Get the TransferRef of paired fungible asset of a coin type from `FreezeCapability`. + public fun get_paired_transfer_ref( + _: &FreezeCapability + ): (TransferRef, TransferRefReceipt) acquires CoinConversionMap, PairedFungibleAssetRefs { + let metadata = assert_paired_metadata_exists(); + let metadata_addr = object_address(&metadata); + assert!(exists(metadata_addr), error::internal(EPAIRED_FUNGIBLE_ASSET_REFS_NOT_FOUND)); + let transfer_ref_opt = &mut borrow_global_mut(metadata_addr).transfer_ref_opt; + assert!(option::is_some(transfer_ref_opt), error::not_found(ETRANSFER_REF_NOT_FOUND)); + (option::extract(transfer_ref_opt), TransferRefReceipt { metadata }) + } + + /// Return the `TransferRef` with the hot potato receipt. + public fun return_paired_transfer_ref( + transfer_ref: TransferRef, + receipt: TransferRefReceipt + ) acquires PairedFungibleAssetRefs { + let TransferRefReceipt { metadata } = receipt; + assert!( + fungible_asset::transfer_ref_metadata(&transfer_ref) == metadata, + error::invalid_argument(ETRANSFER_REF_RECEIPT_MISMATCH) + ); + let metadata_addr = object_address(&metadata); + let transfer_ref_opt = &mut borrow_global_mut(metadata_addr).transfer_ref_opt; + option::fill(transfer_ref_opt, transfer_ref); + } + + #[view] + /// Check whether `BurnRef` has not been taken. + public fun paired_burn_ref_exists(): bool acquires CoinConversionMap, PairedFungibleAssetRefs { + let metadata = assert_paired_metadata_exists(); + let metadata_addr = object_address(&metadata); + assert!(exists(metadata_addr), error::internal(EPAIRED_FUNGIBLE_ASSET_REFS_NOT_FOUND)); + option::is_some(&borrow_global(metadata_addr).burn_ref_opt) + } + + /// Get the `BurnRef` of paired fungible asset of a coin type from `BurnCapability`. + public fun get_paired_burn_ref( + _: &BurnCapability + ): (BurnRef, BurnRefReceipt) acquires CoinConversionMap, PairedFungibleAssetRefs { + let metadata = assert_paired_metadata_exists(); + let metadata_addr = object_address(&metadata); + assert!(exists(metadata_addr), error::internal(EPAIRED_FUNGIBLE_ASSET_REFS_NOT_FOUND)); + let burn_ref_opt = &mut borrow_global_mut(metadata_addr).burn_ref_opt; + assert!(option::is_some(burn_ref_opt), error::not_found(EBURN_REF_NOT_FOUND)); + (option::extract(burn_ref_opt), BurnRefReceipt { metadata }) + } + + // Permanently convert to BurnRef, and take it from the pairing. + // (i.e. future calls to borrow/convert BurnRef will fail) + public fun convert_and_take_paired_burn_ref( + burn_cap: BurnCapability + ): BurnRef acquires CoinConversionMap, PairedFungibleAssetRefs { + destroy_burn_cap(burn_cap); + let metadata = assert_paired_metadata_exists(); + let metadata_addr = object_address(&metadata); + assert!(exists(metadata_addr), error::internal(EPAIRED_FUNGIBLE_ASSET_REFS_NOT_FOUND)); + let burn_ref_opt = &mut borrow_global_mut(metadata_addr).burn_ref_opt; + assert!(option::is_some(burn_ref_opt), error::not_found(EBURN_REF_NOT_FOUND)); + option::extract(burn_ref_opt) + } + + /// Return the `BurnRef` with the hot potato receipt. + public fun return_paired_burn_ref( + burn_ref: BurnRef, + receipt: BurnRefReceipt + ) acquires PairedFungibleAssetRefs { + let BurnRefReceipt { metadata } = receipt; + assert!( + fungible_asset::burn_ref_metadata(&burn_ref) == metadata, + error::invalid_argument(EBURN_REF_RECEIPT_MISMATCH) + ); + let metadata_addr = object_address(&metadata); + let burn_ref_opt = &mut borrow_global_mut(metadata_addr).burn_ref_opt; + option::fill(burn_ref_opt, burn_ref); + } + + inline fun borrow_paired_burn_ref( + _: &BurnCapability + ): &BurnRef acquires CoinConversionMap, PairedFungibleAssetRefs { + let metadata = assert_paired_metadata_exists(); + let metadata_addr = object_address(&metadata); + assert!(exists(metadata_addr), error::internal(EPAIRED_FUNGIBLE_ASSET_REFS_NOT_FOUND)); + let burn_ref_opt = &mut borrow_global_mut(metadata_addr).burn_ref_opt; + assert!(option::is_some(burn_ref_opt), error::not_found(EBURN_REF_NOT_FOUND)); + option::borrow(burn_ref_opt) + } + + // + // Total supply config + // + + /// Publishes supply configuration. Initially, upgrading is not allowed. + public(friend) fun initialize_supply_config(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, SupplyConfig { allow_upgrades: false }); + } + + /// This should be called by on-chain governance to update the config and allow + /// or disallow upgradability of total supply. + public fun allow_supply_upgrades(aptos_framework: &signer, allowed: bool) acquires SupplyConfig { + system_addresses::assert_aptos_framework(aptos_framework); + let allow_upgrades = &mut borrow_global_mut(@aptos_framework).allow_upgrades; + *allow_upgrades = allowed; + } + + // + // Aggregatable coin functions + // + + /// Creates a new aggregatable coin with value overflowing on `limit`. Note that this function can + /// only be called by Aptos Framework (0x1) account for now because of `create_aggregator`. + public(friend) fun initialize_aggregatable_coin(aptos_framework: &signer): AggregatableCoin { + let aggregator = aggregator_factory::create_aggregator(aptos_framework, MAX_U64); + AggregatableCoin { + value: aggregator, + } + } + + /// Returns true if the value of aggregatable coin is zero. + public(friend) fun is_aggregatable_coin_zero(coin: &AggregatableCoin): bool { + let amount = aggregator::read(&coin.value); + amount == 0 + } + + /// Drains the aggregatable coin, setting it to zero and returning a standard coin. + public(friend) fun drain_aggregatable_coin(coin: &mut AggregatableCoin): Coin { + spec { + // TODO: The data invariant is not properly assumed from CollectedFeesPerBlock. + assume aggregator::spec_get_limit(coin.value) == MAX_U64; + }; + let amount = aggregator::read(&coin.value); + assert!(amount <= MAX_U64, error::out_of_range(EAGGREGATABLE_COIN_VALUE_TOO_LARGE)); + spec { + update aggregate_supply = aggregate_supply - amount; + }; + aggregator::sub(&mut coin.value, amount); + spec { + update supply = supply + amount; + }; + Coin { + value: (amount as u64), + } + } + + /// Merges `coin` into aggregatable coin (`dst_coin`). + public(friend) fun merge_aggregatable_coin( + dst_coin: &mut AggregatableCoin, + coin: Coin + ) { + spec { + update supply = supply - coin.value; + }; + let Coin { value } = coin; + let amount = (value as u128); + spec { + update aggregate_supply = aggregate_supply + amount; + }; + aggregator::add(&mut dst_coin.value, amount); + } + + /// Collects a specified amount of coin form an account into aggregatable coin. + public(friend) fun collect_into_aggregatable_coin( + account_addr: address, + amount: u64, + dst_coin: &mut AggregatableCoin, + ) acquires CoinStore, CoinConversionMap, CoinInfo, PairedCoinType { + // Skip collecting if amount is zero. + if (amount == 0) { + return + }; + + let (coin_amount_to_collect, fa_amount_to_collect) = calculate_amount_to_withdraw( + account_addr, + amount + ); + let coin = if (coin_amount_to_collect > 0) { + let coin_store = borrow_global_mut>(account_addr); + extract(&mut coin_store.coin, coin_amount_to_collect) + } else { + zero() + }; + if (fa_amount_to_collect > 0) { + let store_addr = primary_fungible_store::primary_store_address( + account_addr, + option::destroy_some(paired_metadata()) + ); + let fa = fungible_asset::withdraw_internal(store_addr, fa_amount_to_collect); + merge(&mut coin, fungible_asset_to_coin(fa)); + }; + merge_aggregatable_coin(dst_coin, coin); + } + + inline fun calculate_amount_to_withdraw( + account_addr: address, + amount: u64 + ): (u64, u64) { + let coin_balance = coin_balance(account_addr); + if (coin_balance >= amount) { + (amount, 0) + } else { + let metadata = paired_metadata(); + if (option::is_some(&metadata) && primary_fungible_store::primary_store_exists( + account_addr, + option::destroy_some(metadata) + )) + (coin_balance, amount - coin_balance) + else + abort error::invalid_argument(EINSUFFICIENT_BALANCE) + } + } + + fun maybe_convert_to_fungible_store(account: address) acquires CoinStore, CoinConversionMap, CoinInfo { + if (!features::coin_to_fungible_asset_migration_feature_enabled()) { + abort error::unavailable(ECOIN_TO_FUNGIBLE_ASSET_FEATURE_NOT_ENABLED) + }; + assert!(is_coin_initialized(), error::invalid_argument(ECOIN_INFO_NOT_PUBLISHED)); + + let metadata = ensure_paired_metadata(); + let store = primary_fungible_store::ensure_primary_store_exists(account, metadata); + let store_address = object::object_address(&store); + if (exists>(account)) { + let CoinStore { coin, frozen, deposit_events, withdraw_events } = move_from>( + account + ); + event::emit( + CoinEventHandleDeletion { + event_handle_creation_address: guid::creator_address( + event::guid(&deposit_events) + ), + deleted_deposit_event_handle_creation_number: guid::creation_num(event::guid(&deposit_events)), + deleted_withdraw_event_handle_creation_number: guid::creation_num(event::guid(&withdraw_events)) + } + ); + event::destroy_handle(deposit_events); + event::destroy_handle(withdraw_events); + if (coin.value == 0) { + destroy_zero(coin); + } else { + fungible_asset::deposit(store, coin_to_fungible_asset(coin)); + }; + // Note: + // It is possible the primary fungible store may already exist before this function call. + // In this case, if the account owns a frozen CoinStore and an unfrozen primary fungible store, this + // function would convert and deposit the rest coin into the primary store and freeze it to make the + // `frozen` semantic as consistent as possible. + if (frozen != fungible_asset::is_frozen(store)) { + fungible_asset::set_frozen_flag_internal(store, frozen); + } + }; + if (!exists(store_address)) { + move_to(&create_signer::create_signer(store_address), MigrationFlag {}); + } + } + + /// Voluntarily migrate to fungible store for `CoinType` if not yet. + public entry fun migrate_to_fungible_store( + account: &signer + ) acquires CoinStore, CoinConversionMap, CoinInfo { + maybe_convert_to_fungible_store(signer::address_of(account)); + } + + // + // Getter functions + // + + /// A helper function that returns the address of CoinType. + fun coin_address(): address { + let type_info = type_info::type_of(); + type_info::account_address(&type_info) + } + + #[view] + /// Returns the balance of `owner` for provided `CoinType` and its paired FA if exists. + public fun balance(owner: address): u64 acquires CoinConversionMap, CoinStore { + let paired_metadata = paired_metadata(); + coin_balance(owner) + if (option::is_some(&paired_metadata)) { + primary_fungible_store::balance( + owner, + option::extract(&mut paired_metadata) + ) + } else { 0 } + } + + #[view] + /// Returns whether the balance of `owner` for provided `CoinType` and its paired FA is >= `amount`. + public fun is_balance_at_least(owner: address, amount: u64): bool acquires CoinConversionMap, CoinStore { + let coin_balance = coin_balance(owner); + if (coin_balance >= amount) { + return true + }; + + let paired_metadata = paired_metadata(); + let left_amount = amount - coin_balance; + if (option::is_some(&paired_metadata)) { + primary_fungible_store::is_balance_at_least( + owner, + option::extract(&mut paired_metadata), + left_amount + ) + } else { false } + } + + inline fun coin_balance(owner: address): u64 { + if (exists>(owner)) { + borrow_global>(owner).coin.value + } else { + 0 + } + } + + #[view] + /// Returns `true` if the type `CoinType` is an initialized coin. + public fun is_coin_initialized(): bool { + exists>(coin_address()) + } + + #[view] + /// Returns `true` is account_addr has frozen the CoinStore or if it's not registered at all + public fun is_coin_store_frozen( + account_addr: address + ): bool acquires CoinStore, CoinConversionMap { + if (!is_account_registered(account_addr)) { + return true + }; + + let coin_store = borrow_global>(account_addr); + coin_store.frozen + } + + #[view] + /// Returns `true` if `account_addr` is registered to receive `CoinType`. + public fun is_account_registered(account_addr: address): bool acquires CoinConversionMap { + assert!(is_coin_initialized(), error::invalid_argument(ECOIN_INFO_NOT_PUBLISHED)); + if (exists>(account_addr)) { + true + } else { + let paired_metadata_opt = paired_metadata(); + (option::is_some( + &paired_metadata_opt + ) && migrated_primary_fungible_store_exists(account_addr, option::destroy_some(paired_metadata_opt))) + } + } + + #[view] + /// Returns the name of the coin. + public fun name(): string::String acquires CoinInfo { + borrow_global>(coin_address()).name + } + + #[view] + /// Returns the symbol of the coin, usually a shorter version of the name. + public fun symbol(): string::String acquires CoinInfo { + borrow_global>(coin_address()).symbol + } + + #[view] + /// Returns the number of decimals used to get its user representation. + /// For example, if `decimals` equals `2`, a balance of `505` coins should + /// be displayed to a user as `5.05` (`505 / 10 ** 2`). + public fun decimals(): u8 acquires CoinInfo { + borrow_global>(coin_address()).decimals + } + + #[view] + /// Returns the amount of coin in existence. + public fun supply(): Option acquires CoinInfo, CoinConversionMap { + let coin_supply = coin_supply(); + let metadata = paired_metadata(); + if (option::is_some(&metadata)) { + let fungible_asset_supply = fungible_asset::supply(option::extract(&mut metadata)); + if (option::is_some(&coin_supply)) { + let supply = option::borrow_mut(&mut coin_supply); + *supply = *supply + option::destroy_some(fungible_asset_supply); + }; + }; + coin_supply + } + + #[view] + /// Returns the amount of coin in existence. + public fun coin_supply(): Option acquires CoinInfo { + let maybe_supply = &borrow_global>(coin_address()).supply; + if (option::is_some(maybe_supply)) { + // We do track supply, in this case read from optional aggregator. + let supply = option::borrow(maybe_supply); + let value = optional_aggregator::read(supply); + option::some(value) + } else { + option::none() + } + } + // + // Public functions + // + + /// Burn `coin` with capability. + /// The capability `_cap` should be passed as a reference to `BurnCapability`. + public fun burn(coin: Coin, _cap: &BurnCapability) acquires CoinInfo { + burn_internal(coin); + } + + /// Burn `coin` from the specified `account` with capability. + /// The capability `burn_cap` should be passed as a reference to `BurnCapability`. + /// This function shouldn't fail as it's called as part of transaction fee burning. + /// + /// Note: This bypasses CoinStore::frozen -- coins within a frozen CoinStore can be burned. + public fun burn_from( + account_addr: address, + amount: u64, + burn_cap: &BurnCapability, + ) acquires CoinInfo, CoinStore, CoinConversionMap, PairedFungibleAssetRefs { + // Skip burning if amount is zero. This shouldn't error out as it's called as part of transaction fee burning. + if (amount == 0) { + return + }; + + let (coin_amount_to_burn, fa_amount_to_burn) = calculate_amount_to_withdraw( + account_addr, + amount + ); + if (coin_amount_to_burn > 0) { + let coin_store = borrow_global_mut>(account_addr); + let coin_to_burn = extract(&mut coin_store.coin, coin_amount_to_burn); + burn(coin_to_burn, burn_cap); + }; + if (fa_amount_to_burn > 0) { + fungible_asset::burn_from( + borrow_paired_burn_ref(burn_cap), + primary_fungible_store::primary_store(account_addr, option::destroy_some(paired_metadata())), + fa_amount_to_burn + ); + }; + } + + /// Deposit the coin balance into the recipient's account and emit an event. + public fun deposit( + account_addr: address, + coin: Coin + ) acquires CoinStore, CoinConversionMap, CoinInfo { + if (exists>(account_addr)) { + let coin_store = borrow_global_mut>(account_addr); + assert!( + !coin_store.frozen, + error::permission_denied(EFROZEN), + ); + if (std::features::module_event_migration_enabled()) { + event::emit( + CoinDeposit { coin_type: type_name(), account: account_addr, amount: coin.value } + ); + }; + event::emit_event( + &mut coin_store.deposit_events, + DepositEvent { amount: coin.value }, + ); + merge(&mut coin_store.coin, coin); + } else { + let metadata = paired_metadata(); + if (option::is_some(&metadata) && migrated_primary_fungible_store_exists( + account_addr, + option::destroy_some(metadata) + )) { + primary_fungible_store::deposit(account_addr, coin_to_fungible_asset(coin)); + } else { + abort error::not_found(ECOIN_STORE_NOT_PUBLISHED) + }; + } + } + + inline fun migrated_primary_fungible_store_exists( + account_address: address, + metadata: Object + ): bool { + let primary_store_address = primary_fungible_store::primary_store_address(account_address, metadata); + fungible_asset::store_exists(primary_store_address) && ( + // migration flag is needed, until we start defaulting new accounts to APT PFS + features::new_accounts_default_to_fa_apt_store_enabled() || exists(primary_store_address) + ) + } + + /// Deposit the coin balance into the recipient's account without checking if the account is frozen. + /// This is for internal use only and doesn't emit an DepositEvent. + public(friend) fun force_deposit( + account_addr: address, + coin: Coin + ) acquires CoinStore, CoinConversionMap, CoinInfo { + if (exists>(account_addr)) { + let coin_store = borrow_global_mut>(account_addr); + merge(&mut coin_store.coin, coin); + } else { + let metadata = paired_metadata(); + if (option::is_some(&metadata) && migrated_primary_fungible_store_exists( + account_addr, + option::destroy_some(metadata) + )) { + let fa = coin_to_fungible_asset(coin); + let metadata = fungible_asset::asset_metadata(&fa); + let store = primary_fungible_store::primary_store(account_addr, metadata); + fungible_asset::deposit_internal(object::object_address(&store), fa); + } else { + abort error::not_found(ECOIN_STORE_NOT_PUBLISHED) + } + } + } + + /// Destroys a zero-value coin. Calls will fail if the `value` in the passed-in `token` is non-zero + /// so it is impossible to "burn" any non-zero amount of `Coin` without having + /// a `BurnCapability` for the specific `CoinType`. + public fun destroy_zero(zero_coin: Coin) { + spec { + update supply = supply - zero_coin.value; + }; + let Coin { value } = zero_coin; + assert!(value == 0, error::invalid_argument(EDESTRUCTION_OF_NONZERO_TOKEN)) + } + + /// Extracts `amount` from the passed-in `coin`, where the original token is modified in place. + public fun extract(coin: &mut Coin, amount: u64): Coin { + assert!(coin.value >= amount, error::invalid_argument(EINSUFFICIENT_BALANCE)); + spec { + update supply = supply - amount; + }; + coin.value = coin.value - amount; + spec { + update supply = supply + amount; + }; + Coin { value: amount } + } + + /// Extracts the entire amount from the passed-in `coin`, where the original token is modified in place. + public fun extract_all(coin: &mut Coin): Coin { + let total_value = coin.value; + spec { + update supply = supply - coin.value; + }; + coin.value = 0; + spec { + update supply = supply + total_value; + }; + Coin { value: total_value } + } + + #[legacy_entry_fun] + /// Freeze a CoinStore to prevent transfers + public entry fun freeze_coin_store( + account_addr: address, + _freeze_cap: &FreezeCapability, + ) acquires CoinStore { + let coin_store = borrow_global_mut>(account_addr); + coin_store.frozen = true; + } + + #[legacy_entry_fun] + /// Unfreeze a CoinStore to allow transfers + public entry fun unfreeze_coin_store( + account_addr: address, + _freeze_cap: &FreezeCapability, + ) acquires CoinStore { + let coin_store = borrow_global_mut>(account_addr); + coin_store.frozen = false; + } + + /// Upgrade total supply to use a parallelizable implementation if it is + /// available. + public entry fun upgrade_supply(account: &signer) acquires CoinInfo, SupplyConfig { + let account_addr = signer::address_of(account); + + // Only coin creators can upgrade total supply. + assert!( + coin_address() == account_addr, + error::invalid_argument(ECOIN_INFO_ADDRESS_MISMATCH), + ); + + // Can only succeed once on-chain governance agreed on the upgrade. + assert!( + borrow_global_mut(@aptos_framework).allow_upgrades, + error::permission_denied(ECOIN_SUPPLY_UPGRADE_NOT_SUPPORTED) + ); + + let maybe_supply = &mut borrow_global_mut>(account_addr).supply; + if (option::is_some(maybe_supply)) { + let supply = option::borrow_mut(maybe_supply); + + // If supply is tracked and the current implementation uses an integer - upgrade. + if (!optional_aggregator::is_parallelizable(supply)) { + optional_aggregator::switch(supply); + } + } + } + + /// Creates a new Coin with given `CoinType` and returns minting/freezing/burning capabilities. + /// The given signer also becomes the account hosting the information about the coin + /// (name, supply, etc.). Supply is initialized as non-parallelizable integer. + public fun initialize( + account: &signer, + name: string::String, + symbol: string::String, + decimals: u8, + monitor_supply: bool, + ): (BurnCapability, FreezeCapability, MintCapability) { + initialize_internal(account, name, symbol, decimals, monitor_supply, false) + } + + /// Same as `initialize` but supply can be initialized to parallelizable aggregator. + public(friend) fun initialize_with_parallelizable_supply( + account: &signer, + name: string::String, + symbol: string::String, + decimals: u8, + monitor_supply: bool, + ): (BurnCapability, FreezeCapability, MintCapability) { + system_addresses::assert_aptos_framework(account); + initialize_internal(account, name, symbol, decimals, monitor_supply, true) + } + + fun initialize_internal( + account: &signer, + name: string::String, + symbol: string::String, + decimals: u8, + monitor_supply: bool, + parallelizable: bool, + ): (BurnCapability, FreezeCapability, MintCapability) { + let account_addr = signer::address_of(account); + + assert!( + coin_address() == account_addr, + error::invalid_argument(ECOIN_INFO_ADDRESS_MISMATCH), + ); + + assert!( + !exists>(account_addr), + error::already_exists(ECOIN_INFO_ALREADY_PUBLISHED), + ); + + assert!(string::length(&name) <= MAX_COIN_NAME_LENGTH, error::invalid_argument(ECOIN_NAME_TOO_LONG)); + assert!(string::length(&symbol) <= MAX_COIN_SYMBOL_LENGTH, error::invalid_argument(ECOIN_SYMBOL_TOO_LONG)); + + let coin_info = CoinInfo { + name, + symbol, + decimals, + supply: if (monitor_supply) { + option::some( + optional_aggregator::new(MAX_U128, parallelizable) + ) + } else { option::none() }, + }; + move_to(account, coin_info); + + (BurnCapability {}, FreezeCapability {}, MintCapability {}) + } + + /// "Merges" the two given coins. The coin passed in as `dst_coin` will have a value equal + /// to the sum of the two tokens (`dst_coin` and `source_coin`). + public fun merge(dst_coin: &mut Coin, source_coin: Coin) { + spec { + assume dst_coin.value + source_coin.value <= MAX_U64; + }; + spec { + update supply = supply - source_coin.value; + }; + let Coin { value } = source_coin; + spec { + update supply = supply + value; + }; + dst_coin.value = dst_coin.value + value; + } + + /// Mint new `Coin` with capability. + /// The capability `_cap` should be passed as reference to `MintCapability`. + /// Returns minted `Coin`. + public fun mint( + amount: u64, + _cap: &MintCapability, + ): Coin acquires CoinInfo { + mint_internal(amount) + } + + public fun register(account: &signer) acquires CoinConversionMap { + let account_addr = signer::address_of(account); + // Short-circuit and do nothing if account is already registered for CoinType. + if (is_account_registered(account_addr)) { + return + }; + + account::register_coin(account_addr); + let coin_store = CoinStore { + coin: Coin { value: 0 }, + frozen: false, + deposit_events: account::new_event_handle(account), + withdraw_events: account::new_event_handle(account), + }; + move_to(account, coin_store); + } + + /// Transfers `amount` of coins `CoinType` from `from` to `to`. + public entry fun transfer( + from: &signer, + to: address, + amount: u64, + ) acquires CoinStore, CoinConversionMap, CoinInfo, PairedCoinType { + let coin = withdraw(from, amount); + deposit(to, coin); + } + + /// Returns the `value` passed in `coin`. + public fun value(coin: &Coin): u64 { + coin.value + } + + /// Withdraws a specifed `amount` of coin `CoinType` from the specified `account`. + /// @param account The account from which to withdraw the coin. + /// @param amount The amount of coin to withdraw. + public(friend) fun withdraw_from( + account_addr: address, + amount: u64 + ): Coin acquires CoinStore, CoinConversionMap, CoinInfo, PairedCoinType { + + let (coin_amount_to_withdraw, fa_amount_to_withdraw) = calculate_amount_to_withdraw( + account_addr, + amount + ); + let withdrawn_coin = if (coin_amount_to_withdraw > 0) { + let coin_store = borrow_global_mut>(account_addr); + assert!( + !coin_store.frozen, + error::permission_denied(EFROZEN), + ); + if (std::features::module_event_migration_enabled()) { + event::emit( + CoinWithdraw { + coin_type: type_name(), account: account_addr, amount: coin_amount_to_withdraw + } + ); + }; + event::emit_event( + &mut coin_store.withdraw_events, + WithdrawEvent { amount: coin_amount_to_withdraw }, + ); + extract(&mut coin_store.coin, coin_amount_to_withdraw) + } else { + zero() + }; + if (fa_amount_to_withdraw > 0) { + let store_addr = primary_fungible_store::primary_store_address( + account_addr, + option::destroy_some(paired_metadata()) + ); + let fa = fungible_asset::withdraw_internal(store_addr, fa_amount_to_withdraw); + merge(&mut withdrawn_coin, fungible_asset_to_coin(fa)); + }; + + withdrawn_coin + } + + /// Withdraw specified `amount` of coin `CoinType` from the signing account. + public fun withdraw( + account: &signer, + amount: u64, + ): Coin acquires CoinStore, CoinConversionMap, CoinInfo, PairedCoinType { + let account_addr = signer::address_of(account); + + let (coin_amount_to_withdraw, fa_amount_to_withdraw) = calculate_amount_to_withdraw( + account_addr, + amount + ); + let withdrawn_coin = if (coin_amount_to_withdraw > 0) { + let coin_store = borrow_global_mut>(account_addr); + assert!( + !coin_store.frozen, + error::permission_denied(EFROZEN), + ); + if (std::features::module_event_migration_enabled()) { + event::emit( + CoinWithdraw { + coin_type: type_name(), account: account_addr, amount: coin_amount_to_withdraw + } + ); + }; + event::emit_event( + &mut coin_store.withdraw_events, + WithdrawEvent { amount: coin_amount_to_withdraw }, + ); + extract(&mut coin_store.coin, coin_amount_to_withdraw) + } else { + zero() + }; + if (fa_amount_to_withdraw > 0) { + let fa = primary_fungible_store::withdraw( + account, + option::destroy_some(paired_metadata()), + fa_amount_to_withdraw + ); + merge(&mut withdrawn_coin, fungible_asset_to_coin(fa)); + }; + withdrawn_coin + } + + /// Create a new `Coin` with a value of `0`. + public fun zero(): Coin { + spec { + update supply = supply + 0; + }; + Coin { + value: 0 + } + } + + /// Destroy a freeze capability. Freeze capability is dangerous and therefore should be destroyed if not used. + public fun destroy_freeze_cap(freeze_cap: FreezeCapability) { + let FreezeCapability {} = freeze_cap; + } + + /// Destroy a mint capability. + public fun destroy_mint_cap(mint_cap: MintCapability) { + let MintCapability {} = mint_cap; + } + + /// Destroy a burn capability. + public fun destroy_burn_cap(burn_cap: BurnCapability) { + let BurnCapability {} = burn_cap; + } + + fun mint_internal(amount: u64): Coin acquires CoinInfo { + if (amount == 0) { + return Coin { + value: 0 + } + }; + + let maybe_supply = &mut borrow_global_mut>(coin_address()).supply; + if (option::is_some(maybe_supply)) { + let supply = option::borrow_mut(maybe_supply); + spec { + use aptos_framework::optional_aggregator; + use aptos_framework::aggregator; + assume optional_aggregator::is_parallelizable(supply) ==> (aggregator::spec_aggregator_get_val( + option::borrow(supply.aggregator) + ) + + amount <= aggregator::spec_get_limit(option::borrow(supply.aggregator))); + assume !optional_aggregator::is_parallelizable(supply) ==> + (option::borrow(supply.integer).value + amount <= option::borrow(supply.integer).limit); + }; + optional_aggregator::add(supply, (amount as u128)); + }; + spec { + update supply = supply + amount; + }; + Coin { value: amount } + } + + fun burn_internal(coin: Coin): u64 acquires CoinInfo { + spec { + update supply = supply - coin.value; + }; + let Coin { value: amount } = coin; + if (amount != 0) { + let maybe_supply = &mut borrow_global_mut>(coin_address()).supply; + if (option::is_some(maybe_supply)) { + let supply = option::borrow_mut(maybe_supply); + optional_aggregator::sub(supply, (amount as u128)); + }; + }; + amount + } + + #[test_only] + struct FakeMoney {} + + #[test_only] + struct FakeMoneyCapabilities has key { + burn_cap: BurnCapability, + freeze_cap: FreezeCapability, + mint_cap: MintCapability, + } + + #[test_only] + struct FakeMoneyRefs has key { + mint_ref: MintRef, + transfer_ref: TransferRef, + burn_ref: BurnRef, + } + + #[test_only] + fun create_coin_store(account: &signer) { + assert!(is_coin_initialized(), error::invalid_argument(ECOIN_INFO_NOT_PUBLISHED)); + if (!exists>(signer::address_of(account))) { + let coin_store = CoinStore { + coin: Coin { value: 0 }, + frozen: false, + deposit_events: account::new_event_handle(account), + withdraw_events: account::new_event_handle(account), + }; + move_to(account, coin_store); + } + } + + #[test_only] + fun coin_store_exists(account: address): bool { + exists>(account) + } + + #[test_only] + fun initialize_fake_money( + account: &signer, + decimals: u8, + monitor_supply: bool, + ): (BurnCapability, FreezeCapability, MintCapability) { + aggregator_factory::initialize_aggregator_factory_for_test(account); + initialize( + account, + string::utf8(b"Fake money"), + string::utf8(b"FMD"), + decimals, + monitor_supply + ) + } + + #[test_only] + public fun initialize_and_register_fake_money( + account: &signer, + decimals: u8, + monitor_supply: bool, + ): (BurnCapability, FreezeCapability, MintCapability) { + let (burn_cap, freeze_cap, mint_cap) = initialize_fake_money( + account, + decimals, + monitor_supply + ); + create_coin_store(account); + create_coin_conversion_map(account); + (burn_cap, freeze_cap, mint_cap) + } + + #[test_only] + public entry fun create_fake_money( + source: &signer, + destination: &signer, + amount: u64 + ) acquires CoinInfo, CoinStore, CoinConversionMap { + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(source, 18, true); + + create_coin_store(destination); + let coins_minted = mint(amount, &mint_cap); + deposit(signer::address_of(source), coins_minted); + move_to(source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x1, destination = @0x2)] + public entry fun end_to_end( + source: signer, + destination: signer, + ) acquires CoinInfo, CoinStore, CoinConversionMap, PairedCoinType { + let source_addr = signer::address_of(&source); + account::create_account_for_test(source_addr); + let destination_addr = signer::address_of(&destination); + account::create_account_for_test(destination_addr); + + let name = string::utf8(b"Fake money"); + let symbol = string::utf8(b"FMD"); + + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money( + &source, + 18, + true + ); + register(&source); + register(&destination); + assert!(*option::borrow(&supply()) == 0, 0); + + assert!(name() == name, 1); + assert!(symbol() == symbol, 2); + assert!(decimals() == 18, 3); + + let coins_minted = mint(100, &mint_cap); + deposit(source_addr, coins_minted); + maybe_convert_to_fungible_store(source_addr); + assert!(!coin_store_exists(source_addr), 0); + assert!(coin_store_exists(destination_addr), 0); + + transfer(&source, destination_addr, 50); + maybe_convert_to_fungible_store(destination_addr); + assert!(!coin_store_exists(destination_addr), 0); + + assert!(balance(source_addr) == 50, 4); + assert!(balance(destination_addr) == 50, 5); + assert!(*option::borrow(&supply()) == 100, 6); + + let coin = withdraw(&source, 10); + assert!(value(&coin) == 10, 7); + burn(coin, &burn_cap); + assert!(*option::borrow(&supply()) == 90, 8); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x1, destination = @0x2)] + public entry fun end_to_end_no_supply( + source: signer, + destination: signer, + ) acquires CoinInfo, CoinStore, CoinConversionMap, PairedCoinType { + let source_addr = signer::address_of(&source); + account::create_account_for_test(source_addr); + let destination_addr = signer::address_of(&destination); + account::create_account_for_test(destination_addr); + + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&source, 1, false); + + register(&destination); + assert!(option::is_none(&supply()), 0); + + let coins_minted = mint(100, &mint_cap); + deposit(source_addr, coins_minted); + transfer(&source, destination_addr, 50); + + assert!(balance(source_addr) == 50, 1); + assert!(balance(destination_addr) == 50, 2); + assert!(option::is_none(&supply()), 3); + + let coin = withdraw(&source, 10); + burn(coin, &burn_cap); + assert!(option::is_none(&supply()), 4); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x2, framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10001, location = Self)] + public fun fail_initialize(source: signer, framework: signer) { + aggregator_factory::initialize_aggregator_factory_for_test(&framework); + let (burn_cap, freeze_cap, mint_cap) = initialize( + &source, + string::utf8(b"Fake money"), + string::utf8(b"FMD"), + 1, + true, + ); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x1, destination = @0x2)] + public entry fun transfer_to_migrated_destination( + source: signer, + destination: signer, + ) acquires CoinInfo, CoinStore, CoinConversionMap, PairedCoinType { + let source_addr = signer::address_of(&source); + account::create_account_for_test(source_addr); + let destination_addr = signer::address_of(&destination); + account::create_account_for_test(destination_addr); + + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&source, 1, true); + assert!(*option::borrow(&supply()) == 0, 0); + + let coins_minted = mint(100, &mint_cap); + deposit(source_addr, coins_minted); + maybe_convert_to_fungible_store(source_addr); + assert!(!coin_store_exists(source_addr), 0); + maybe_convert_to_fungible_store(destination_addr); + transfer(&source, destination_addr, 50); + assert!(balance(destination_addr) == 50, 2); + assert!(!coin_store_exists(destination_addr), 0); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x1)] + public entry fun test_burn_from_with_capability( + source: signer, + ) acquires CoinInfo, CoinStore, CoinConversionMap, PairedFungibleAssetRefs { + let source_addr = signer::address_of(&source); + account::create_account_for_test(source_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&source, 1, true); + + let coins_minted = mint(100, &mint_cap); + deposit(source_addr, coins_minted); + let fa_minted = coin_to_fungible_asset(mint(200, &mint_cap)); + primary_fungible_store::deposit(source_addr, fa_minted); + + // Burn coin only with both stores + burn_from(source_addr, 50, &burn_cap); + assert!(balance(source_addr) == 250, 0); + assert!(coin_balance(source_addr) == 50, 0); + + // Burn coin and fa with both stores + burn_from(source_addr, 100, &burn_cap); + assert!(balance(source_addr) == 150, 0); + assert!(primary_fungible_store::balance(source_addr, ensure_paired_metadata()) == 150, 0); + + // Burn fa only with both stores + burn_from(source_addr, 100, &burn_cap); + assert!(balance(source_addr) == 50, 0); + assert!(primary_fungible_store::balance(source_addr, ensure_paired_metadata()) == 50, 0); + + // Burn fa only with only fungible store + let coins_minted = mint(50, &mint_cap); + deposit(source_addr, coins_minted); + maybe_convert_to_fungible_store(source_addr); + assert!(!coin_store_exists(source_addr), 0); + assert!(balance(source_addr) == 100, 0); + assert!(*option::borrow(&supply()) == 100, 1); + + burn_from(source_addr, 10, &burn_cap); + assert!(balance(source_addr) == 90, 2); + assert!(*option::borrow(&supply()) == 90, 3); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x1)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public fun test_destroy_non_zero( + source: signer, + ) acquires CoinInfo { + account::create_account_for_test(signer::address_of(&source)); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&source, 1, true); + let coins_minted = mint(100, &mint_cap); + destroy_zero(coins_minted); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x1)] + public entry fun test_extract( + source: signer, + ) acquires CoinInfo, CoinStore, CoinConversionMap { + let source_addr = signer::address_of(&source); + account::create_account_for_test(source_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&source, 1, true); + + let coins_minted = mint(100, &mint_cap); + + let extracted = extract(&mut coins_minted, 25); + assert!(value(&coins_minted) == 75, 0); + assert!(value(&extracted) == 25, 1); + + deposit(source_addr, coins_minted); + deposit(source_addr, extracted); + + assert!(balance(source_addr) == 100, 2); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(source = @0x1)] + public fun test_is_coin_initialized(source: signer) { + assert!(!is_coin_initialized(), 0); + + let (burn_cap, freeze_cap, mint_cap) = initialize_fake_money(&source, 1, true); + assert!(is_coin_initialized(), 1); + + move_to(&source, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(account = @0x1)] + public fun test_is_coin_store_frozen(account: signer) acquires CoinStore, CoinConversionMap, CoinInfo { + let account_addr = signer::address_of(&account); + account::create_account_for_test(account_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&account, 18, true); + assert!(coin_store_exists(account_addr), 1); + assert!(!is_coin_store_frozen(account_addr), 1); + maybe_convert_to_fungible_store(account_addr); + assert!(!coin_store_exists(account_addr), 1); + + move_to(&account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test] + fun test_zero() { + let zero = zero(); + assert!(value(&zero) == 0, 1); + destroy_zero(zero); + } + + #[test(account = @0x1)] + public entry fun burn_frozen( + account: signer + ) acquires CoinInfo, CoinStore, CoinConversionMap, PairedFungibleAssetRefs { + let account_addr = signer::address_of(&account); + account::create_account_for_test(account_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&account, 18, true); + + let coins_minted = mint(100, &mint_cap); + deposit(account_addr, coins_minted); + + freeze_coin_store(account_addr, &freeze_cap); + burn_from(account_addr, 90, &burn_cap); + maybe_convert_to_fungible_store(account_addr); + assert!(primary_fungible_store::is_frozen(account_addr, ensure_paired_metadata()), 1); + assert!(primary_fungible_store::balance(account_addr, ensure_paired_metadata()) == 10, 1); + + move_to(&account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(account = @0x1)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::fungible_asset)] + public entry fun withdraw_frozen(account: signer) acquires CoinInfo, CoinStore, CoinConversionMap, PairedCoinType { + let account_addr = signer::address_of(&account); + account::create_account_for_test(account_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&account, 18, true); + let coins_minted = mint(100, &mint_cap); + deposit(account_addr, coins_minted); + + freeze_coin_store(account_addr, &freeze_cap); + maybe_convert_to_fungible_store(account_addr); + let coin = withdraw(&account, 90); + burn(coin, &burn_cap); + + move_to(&account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(account = @0x1)] + #[expected_failure(abort_code = 0x5000A, location = Self)] + public entry fun deposit_frozen(account: signer) acquires CoinInfo, CoinStore, CoinConversionMap { + let account_addr = signer::address_of(&account); + account::create_account_for_test(account_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&account, 18, true); + + let coins_minted = mint(100, &mint_cap); + freeze_coin_store(account_addr, &freeze_cap); + deposit(account_addr, coins_minted); + + move_to(&account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(account = @0x1)] + public entry fun deposit_withdraw_unfrozen( + account: signer + ) acquires CoinInfo, CoinStore, CoinConversionMap, PairedCoinType { + let account_addr = signer::address_of(&account); + account::create_account_for_test(account_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&account, 18, true); + + let coins_minted = mint(100, &mint_cap); + freeze_coin_store(account_addr, &freeze_cap); + unfreeze_coin_store(account_addr, &freeze_cap); + deposit(account_addr, coins_minted); + + freeze_coin_store(account_addr, &freeze_cap); + unfreeze_coin_store(account_addr, &freeze_cap); + let coin = withdraw(&account, 10); + burn(coin, &burn_cap); + + move_to(&account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test_only] + fun initialize_with_aggregator(account: &signer) { + let (burn_cap, freeze_cap, mint_cap) = initialize_with_parallelizable_supply( + account, + string::utf8(b"Fake money"), + string::utf8(b"FMD"), + 1, + true + ); + move_to(account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test_only] + fun initialize_with_integer(account: &signer) { + let (burn_cap, freeze_cap, mint_cap) = initialize( + account, + string::utf8(b"Fake money"), + string::utf8(b"FMD"), + 1, + true + ); + move_to(account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + + #[test(framework = @aptos_framework, other = @0x123)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + fun test_supply_initialize_fails(framework: signer, other: signer) { + aggregator_factory::initialize_aggregator_factory_for_test(&framework); + initialize_with_aggregator(&other); + } + + #[test(other = @0x123)] + #[expected_failure(abort_code = 0x10003, location = Self)] + fun test_create_coin_store_with_non_coin_type(other: signer) acquires CoinConversionMap { + register(&other); + } + + #[test(other = @0x123)] + #[expected_failure(abort_code = 0x10003, location = Self)] + fun test_migration_coin_store_with_non_coin_type(other: signer) acquires CoinConversionMap, CoinStore, CoinInfo { + migrate_to_fungible_store(&other); + } + + #[test(framework = @aptos_framework)] + fun test_supply_initialize(framework: signer) acquires CoinInfo { + aggregator_factory::initialize_aggregator_factory_for_test(&framework); + initialize_with_aggregator(&framework); + + let maybe_supply = &mut borrow_global_mut>(coin_address()).supply; + let supply = option::borrow_mut(maybe_supply); + + // Supply should be parallelizable. + assert!(optional_aggregator::is_parallelizable(supply), 0); + + optional_aggregator::add(supply, 100); + optional_aggregator::sub(supply, 50); + optional_aggregator::add(supply, 950); + assert!(optional_aggregator::read(supply) == 1000, 0); + } + + #[test(framework = @aptos_framework)] + #[expected_failure(abort_code = 0x20001, location = aptos_framework::aggregator)] + fun test_supply_overflow(framework: signer) acquires CoinInfo { + aggregator_factory::initialize_aggregator_factory_for_test(&framework); + initialize_with_aggregator(&framework); + + let maybe_supply = &mut borrow_global_mut>(coin_address()).supply; + let supply = option::borrow_mut(maybe_supply); + + optional_aggregator::add(supply, MAX_U128); + optional_aggregator::add(supply, 1); + optional_aggregator::sub(supply, 1); + } + + #[test(framework = @aptos_framework)] + #[expected_failure(abort_code = 0x5000B, location = aptos_framework::coin)] + fun test_supply_upgrade_fails(framework: signer) acquires CoinInfo, SupplyConfig { + initialize_supply_config(&framework); + aggregator_factory::initialize_aggregator_factory_for_test(&framework); + initialize_with_integer(&framework); + + let maybe_supply = &mut borrow_global_mut>(coin_address()).supply; + let supply = option::borrow_mut(maybe_supply); + + // Supply should be non-parallelizable. + assert!(!optional_aggregator::is_parallelizable(supply), 0); + + optional_aggregator::add(supply, 100); + optional_aggregator::sub(supply, 50); + optional_aggregator::add(supply, 950); + assert!(optional_aggregator::read(supply) == 1000, 0); + + upgrade_supply(&framework); + } + + #[test(framework = @aptos_framework)] + fun test_supply_upgrade(framework: signer) acquires CoinInfo, SupplyConfig { + initialize_supply_config(&framework); + aggregator_factory::initialize_aggregator_factory_for_test(&framework); + initialize_with_integer(&framework); + + // Ensure we have a non-parellelizable non-zero supply. + let maybe_supply = &mut borrow_global_mut>(coin_address()).supply; + let supply = option::borrow_mut(maybe_supply); + assert!(!optional_aggregator::is_parallelizable(supply), 0); + optional_aggregator::add(supply, 100); + + // Upgrade. + allow_supply_upgrades(&framework, true); + upgrade_supply(&framework); + + // Check supply again. + let maybe_supply = &mut borrow_global_mut>(coin_address()).supply; + let supply = option::borrow_mut(maybe_supply); + assert!(optional_aggregator::is_parallelizable(supply), 0); + assert!(optional_aggregator::read(supply) == 100, 0); + } + + #[test_only] + fun destroy_aggregatable_coin_for_test(aggregatable_coin: AggregatableCoin) { + let AggregatableCoin { value } = aggregatable_coin; + aggregator::destroy(value); + } + + #[test(framework = @aptos_framework)] + public entry fun test_collect_from_and_drain( + framework: signer, + ) acquires CoinInfo, CoinStore, CoinConversionMap, PairedCoinType { + let framework_addr = signer::address_of(&framework); + account::create_account_for_test(framework_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(&framework, 1, true); + + // Collect from coin store only. + let coins_minted = mint(100, &mint_cap); + deposit(framework_addr, coins_minted); + let aggregatable_coin = initialize_aggregatable_coin(&framework); + collect_into_aggregatable_coin(framework_addr, 50, &mut aggregatable_coin); + + let fa_minted = coin_to_fungible_asset(mint(100, &mint_cap)); + primary_fungible_store::deposit(framework_addr, fa_minted); + assert!(balance(framework_addr) == 150, 0); + assert!(*option::borrow(&supply()) == 200, 0); + + // Collect from coin store and fungible store. + collect_into_aggregatable_coin(framework_addr, 100, &mut aggregatable_coin); + + assert!(balance(framework_addr) == 50, 0); + maybe_convert_to_fungible_store(framework_addr); + // Collect from fungible store only. + collect_into_aggregatable_coin(framework_addr, 30, &mut aggregatable_coin); + + // Check that aggregatable coin has the right amount. + let collected_coin = drain_aggregatable_coin(&mut aggregatable_coin); + assert!(is_aggregatable_coin_zero(&aggregatable_coin), 0); + assert!(value(&collected_coin) == 180, 0); + + // Supply of coins should be unchanged, but the balance on the account should decrease. + assert!(balance(framework_addr) == 20, 0); + assert!(*option::borrow(&supply()) == 200, 0); + + burn(collected_coin, &burn_cap); + destroy_aggregatable_coin_for_test(aggregatable_coin); + move_to(&framework, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test_only] + fun deposit_to_coin_store(account_addr: address, coin: Coin) acquires CoinStore { + assert!( + coin_store_exists(account_addr), + error::not_found(ECOIN_STORE_NOT_PUBLISHED), + ); + + let coin_store = borrow_global_mut>(account_addr); + assert!( + !coin_store.frozen, + error::permission_denied(EFROZEN), + ); + + event::emit_event( + &mut coin_store.deposit_events, + DepositEvent { amount: coin.value }, + ); + + merge(&mut coin_store.coin, coin); + } + + #[test(account = @aptos_framework)] + fun test_conversion_basic( + account: &signer + ) acquires CoinConversionMap, CoinInfo, CoinStore, PairedCoinType, PairedFungibleAssetRefs { + let account_addr = signer::address_of(account); + account::create_account_for_test(account_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(account, 1, true); + + assert!(fungible_asset::name(ensure_paired_metadata()) == name(), 0); + assert!(fungible_asset::symbol(ensure_paired_metadata()) == symbol(), 0); + assert!(fungible_asset::decimals(ensure_paired_metadata()) == decimals(), 0); + + let minted_coin = mint(100, &mint_cap); + let converted_fa = coin_to_fungible_asset(minted_coin); + + // check and get refs + assert!(paired_mint_ref_exists(), 0); + assert!(paired_transfer_ref_exists(), 0); + assert!(paired_burn_ref_exists(), 0); + let (mint_ref, mint_ref_receipt) = get_paired_mint_ref(&mint_cap); + let (transfer_ref, transfer_ref_receipt) = get_paired_transfer_ref(&freeze_cap); + let (burn_ref, burn_ref_receipt) = get_paired_burn_ref(&burn_cap); + assert!(!paired_mint_ref_exists(), 0); + assert!(!paired_transfer_ref_exists(), 0); + assert!(!paired_burn_ref_exists(), 0); + + let minted_fa = fungible_asset::mint(&mint_ref, 100); + assert!(&converted_fa == &minted_fa, 0); + + let coin = fungible_asset_to_coin(converted_fa); + assert!(value(&coin) == 100, 0); + + deposit_to_coin_store(account_addr, coin); + assert!(coin_store_exists(account_addr), 0); + primary_fungible_store::deposit(account_addr, minted_fa); + assert!(balance(account_addr) == 200, 0); + + let withdrawn_coin = withdraw(account, 1); + maybe_convert_to_fungible_store(account_addr); + assert!(!coin_store_exists(account_addr), 0); + assert!(balance(account_addr) == 199, 0); + assert!(primary_fungible_store::balance(account_addr, ensure_paired_metadata()) == 199, 0); + + let fa = coin_to_fungible_asset(withdrawn_coin); + fungible_asset::burn(&burn_ref, fa); + + // Return and check the refs + return_paired_mint_ref(mint_ref, mint_ref_receipt); + return_paired_transfer_ref(transfer_ref, transfer_ref_receipt); + return_paired_burn_ref(burn_ref, burn_ref_receipt); + assert!(paired_mint_ref_exists(), 0); + assert!(paired_transfer_ref_exists(), 0); + assert!(paired_burn_ref_exists(), 0); + + move_to(account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(account = @aptos_framework, aaron = @0xcafe)] + fun test_balance_with_both_stores( + account: &signer, + aaron: &signer + ) acquires CoinConversionMap, CoinInfo, CoinStore { + let account_addr = signer::address_of(account); + let aaron_addr = signer::address_of(aaron); + account::create_account_for_test(account_addr); + account::create_account_for_test(aaron_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(account, 1, true); + create_coin_store(aaron); + let coin = mint(100, &mint_cap); + let fa = coin_to_fungible_asset(mint(100, &mint_cap)); + primary_fungible_store::deposit(aaron_addr, fa); + deposit_to_coin_store(aaron_addr, coin); + assert!(coin_balance(aaron_addr) == 100, 0); + assert!(balance(aaron_addr) == 200, 0); + maybe_convert_to_fungible_store(aaron_addr); + assert!(balance(aaron_addr) == 200, 0); + assert!(coin_balance(aaron_addr) == 0, 0); + + move_to(account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(account = @aptos_framework)] + fun test_deposit( + account: &signer, + ) acquires CoinConversionMap, CoinInfo, CoinStore { + let account_addr = signer::address_of(account); + account::create_account_for_test(account_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(account, 1, true); + let coin = mint(100, &mint_cap); + deposit(account_addr, coin); + assert!(coin_store_exists(account_addr), 0); + assert!(primary_fungible_store::balance(account_addr, ensure_paired_metadata()) == 0, 0); + assert!(balance(account_addr) == 100, 0); + + maybe_convert_to_fungible_store(account_addr); + let coin = mint(100, &mint_cap); + deposit(account_addr, coin); + assert!(!coin_store_exists(account_addr), 0); + assert!(balance(account_addr) == 200, 0); + assert!(primary_fungible_store::balance(account_addr, ensure_paired_metadata()) == 200, 0); + + move_to(account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(account = @aptos_framework)] + fun test_withdraw( + account: &signer, + ) acquires CoinConversionMap, CoinInfo, CoinStore, PairedCoinType { + let account_addr = signer::address_of(account); + account::create_account_for_test(account_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(account, 1, true); + let coin = mint(200, &mint_cap); + deposit_to_coin_store(account_addr, coin); + assert!(coin_balance(account_addr) == 200, 0); + assert!(balance(account_addr) == 200, 0); + + // Withdraw from coin store only. + let coin = withdraw(account, 100); + assert!(coin_balance(account_addr) == 100, 0); + assert!(balance(account_addr) == 100, 0); + + let fa = coin_to_fungible_asset(coin); + primary_fungible_store::deposit(account_addr, fa); + assert!(coin_store_exists(account_addr), 0); + assert!(primary_fungible_store::balance(account_addr, ensure_paired_metadata()) == 100, 0); + assert!(balance(account_addr) == 200, 0); + + // Withdraw from both coin store and fungible store. + let coin = withdraw(account, 150); + assert!(coin_balance(account_addr) == 0, 0); + assert!(primary_fungible_store::balance(account_addr, ensure_paired_metadata()) == 50, 0); + + deposit_to_coin_store(account_addr, coin); + maybe_convert_to_fungible_store(account_addr); + assert!(!coin_store_exists(account_addr), 0); + assert!(balance(account_addr) == 200, 0); + assert!(primary_fungible_store::balance(account_addr, ensure_paired_metadata()) == 200, 0); + + // Withdraw from fungible store only. + let coin = withdraw(account, 150); + assert!(balance(account_addr) == 50, 0); + burn(coin, &burn_cap); + + move_to(account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(account = @aptos_framework)] + fun test_supply( + account: &signer, + ) acquires CoinConversionMap, CoinInfo, PairedCoinType, PairedFungibleAssetRefs { + account::create_account_for_test(signer::address_of(account)); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(account, 1, true); + let coin = mint(100, &mint_cap); + ensure_paired_metadata(); + let (mint_ref, mint_ref_receipt) = get_paired_mint_ref(&mint_cap); + let (burn_ref, burn_ref_receipt) = get_paired_burn_ref(&burn_cap); + let fungible_asset = fungible_asset::mint(&mint_ref, 50); + assert!(supply() == option::some(150), 0); + assert!(coin_supply() == option::some(100), 0); + assert!(fungible_asset::supply(ensure_paired_metadata()) == option::some(50), 0); + let fa_from_coin = coin_to_fungible_asset(coin); + assert!(supply() == option::some(150), 0); + assert!(coin_supply() == option::some(0), 0); + assert!(fungible_asset::supply(ensure_paired_metadata()) == option::some(150), 0); + + let coin_from_fa = fungible_asset_to_coin(fungible_asset); + assert!(supply() == option::some(150), 0); + assert!(coin_supply() == option::some(50), 0); + assert!(fungible_asset::supply(ensure_paired_metadata()) == option::some(100), 0); + burn(coin_from_fa, &burn_cap); + fungible_asset::burn(&burn_ref, fa_from_coin); + assert!(supply() == option::some(0), 0); + return_paired_mint_ref(mint_ref, mint_ref_receipt); + return_paired_burn_ref(burn_ref, burn_ref_receipt); + move_to(account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(account = @aptos_framework, aaron = @0xaa10, bob = @0xb0b)] + #[expected_failure(abort_code = 0x60005, location = Self)] + fun test_force_deposit( + account: &signer, + aaron: &signer, + bob: &signer + ) acquires CoinConversionMap, CoinInfo, CoinStore { + let account_addr = signer::address_of(account); + let aaron_addr = signer::address_of(aaron); + let bob_addr = signer::address_of(bob); + account::create_account_for_test(account_addr); + account::create_account_for_test(aaron_addr); + account::create_account_for_test(bob_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(account, 1, true); + maybe_convert_to_fungible_store(aaron_addr); + deposit(aaron_addr, mint(1, &mint_cap)); + + force_deposit(account_addr, mint(100, &mint_cap)); + force_deposit(aaron_addr, mint(50, &mint_cap)); + assert!( + primary_fungible_store::balance(aaron_addr, option::extract(&mut paired_metadata())) == 51, + 0 + ); + assert!(coin_balance(account_addr) == 100, 0); + force_deposit(bob_addr, mint(1, &mint_cap)); + move_to(account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(account = @aptos_framework, aaron = @0xaa10, bob = @0xb0b)] + fun test_is_account_registered( + account: &signer, + aaron: &signer, + bob: &signer, + ) acquires CoinConversionMap, CoinInfo, CoinStore { + let account_addr = signer::address_of(account); + let aaron_addr = signer::address_of(aaron); + let bob_addr = signer::address_of(bob); + account::create_account_for_test(account_addr); + account::create_account_for_test(aaron_addr); + account::create_account_for_test(bob_addr); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(account, 1, true); + + assert!(coin_store_exists(account_addr), 0); + assert!(is_account_registered(account_addr), 0); + + assert!(!coin_store_exists(aaron_addr), 0); + assert!(!is_account_registered(aaron_addr), 0); + + maybe_convert_to_fungible_store(aaron_addr); + let coin = mint(100, &mint_cap); + deposit(aaron_addr, coin); + + assert!(!coin_store_exists(aaron_addr), 0); + assert!(is_account_registered(aaron_addr), 0); + + maybe_convert_to_fungible_store(account_addr); + assert!(!coin_store_exists(account_addr), 0); + assert!(is_account_registered(account_addr), 0); + + // Deposit FA to bob to created primary fungible store without `MigrationFlag`. + primary_fungible_store::deposit(bob_addr, coin_to_fungible_asset(mint(100, &mint_cap))); + assert!(!coin_store_exists(bob_addr), 0); + register(bob); + assert!(coin_store_exists(bob_addr), 0); + maybe_convert_to_fungible_store(bob_addr); + assert!(!coin_store_exists(bob_addr), 0); + register(bob); + assert!(!coin_store_exists(bob_addr), 0); + + move_to(account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + #[test(account = @aptos_framework, aaron = @0xaa10)] + fun test_migration_with_existing_primary_fungible_store( + account: &signer, + ) acquires CoinConversionMap, CoinInfo, CoinStore, PairedCoinType { + account::create_account_for_test(signer::address_of(account)); + let account_addr = signer::address_of(account); + let (burn_cap, freeze_cap, mint_cap) = initialize_and_register_fake_money(account, 1, true); + + let coin = mint(100, &mint_cap); + primary_fungible_store::deposit(account_addr, coin_to_fungible_asset(coin)); + assert!(coin_balance(account_addr) == 0, 0); + assert!(balance(account_addr) == 100, 0); + let coin = withdraw(account, 50); + assert!(!migrated_primary_fungible_store_exists(account_addr, ensure_paired_metadata()), 0); + maybe_convert_to_fungible_store(account_addr); + assert!(migrated_primary_fungible_store_exists(account_addr, ensure_paired_metadata()), 0); + deposit(account_addr, coin); + assert!(coin_balance(account_addr) == 0, 0); + assert!(balance(account_addr) == 100, 0); + + move_to(account, FakeMoneyCapabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/config_buffer.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/config_buffer.move new file mode 100644 index 000000000..bbcba8426 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/config_buffer.move @@ -0,0 +1,101 @@ +/// This wrapper helps store an on-chain config for the next epoch. +/// +/// Once reconfigure with DKG is introduced, every on-chain config `C` should do the following. +/// - Support async update when DKG is enabled. This is typically done by 3 steps below. +/// - Implement `C::set_for_next_epoch()` using `upsert()` function in this module. +/// - Implement `C::on_new_epoch()` using `extract()` function in this module. +/// - Update `0x1::reconfiguration_with_dkg::finish()` to call `C::on_new_epoch()`. +/// - Support sychronous update when DKG is disabled. +/// This is typically done by implementing `C::set()` to update the config resource directly. +/// +/// NOTE: on-chain config `0x1::state::ValidatorSet` implemented its own buffer. +module aptos_framework::config_buffer { + use std::string::String; + use aptos_std::any; + use aptos_std::any::Any; + use aptos_std::simple_map; + use aptos_std::simple_map::SimpleMap; + use aptos_std::type_info; + use aptos_framework::system_addresses; + + friend aptos_framework::consensus_config; + friend aptos_framework::execution_config; + friend aptos_framework::gas_schedule; + friend aptos_framework::jwks; + friend aptos_framework::jwk_consensus_config; + friend aptos_framework::keyless_account; + friend aptos_framework::randomness_api_v0_config; + friend aptos_framework::randomness_config; + friend aptos_framework::randomness_config_seqnum; + friend aptos_framework::version; + + /// Config buffer operations failed with permission denied. + const ESTD_SIGNER_NEEDED: u64 = 1; + + struct PendingConfigs has key { + configs: SimpleMap, + } + + public fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + if (!exists(@aptos_framework)) { + move_to(aptos_framework, PendingConfigs { + configs: simple_map::new(), + }) + } + } + + /// Check whether there is a pending config payload for `T`. + public fun does_exist(): bool acquires PendingConfigs { + if (exists(@aptos_framework)) { + let config = borrow_global(@aptos_framework); + simple_map::contains_key(&config.configs, &type_info::type_name()) + } else { + false + } + } + + /// Upsert an on-chain config to the buffer for the next epoch. + /// + /// Typically used in `X::set_for_next_epoch()` where X is an on-chain config. + public(friend) fun upsert(config: T) acquires PendingConfigs { + let configs = borrow_global_mut(@aptos_framework); + let key = type_info::type_name(); + let value = any::pack(config); + simple_map::upsert(&mut configs.configs, key, value); + } + + /// Take the buffered config `T` out (buffer cleared). Abort if the buffer is empty. + /// Should only be used at the end of a reconfiguration. + /// + /// Typically used in `X::on_new_epoch()` where X is an on-chaon config. + public fun extract(): T acquires PendingConfigs { + let configs = borrow_global_mut(@aptos_framework); + let key = type_info::type_name(); + let (_, value_packed) = simple_map::remove(&mut configs.configs, &key); + any::unpack(value_packed) + } + + #[test_only] + struct DummyConfig has drop, store { + data: u64, + } + + #[test(fx = @std)] + fun test_config_buffer_basic(fx: &signer) acquires PendingConfigs { + initialize(fx); + // Initially nothing in the buffer. + assert!(!does_exist(), 1); + + // Insert should work. + upsert(DummyConfig { data: 888 }); + assert!(does_exist(), 1); + + // Update and extract should work. + upsert(DummyConfig { data: 999 }); + assert!(does_exist(), 1); + let config = extract(); + assert!(config == DummyConfig { data: 999 }, 1); + assert!(!does_exist(), 1); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/consensus_config.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/consensus_config.move new file mode 100644 index 000000000..e81049477 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/consensus_config.move @@ -0,0 +1,77 @@ +/// Maintains the consensus config for the blockchain. The config is stored in a +/// Reconfiguration, and may be updated by root. +module aptos_framework::consensus_config { + use std::error; + use std::vector; + use aptos_framework::chain_status; + use aptos_framework::config_buffer; + + use aptos_framework::reconfiguration; + use aptos_framework::system_addresses; + + friend aptos_framework::genesis; + friend aptos_framework::reconfiguration_with_dkg; + + struct ConsensusConfig has drop, key, store { + config: vector, + } + + /// The provided on chain config bytes are empty or invalid + const EINVALID_CONFIG: u64 = 1; + + /// Publishes the ConsensusConfig config. + public(friend) fun initialize(aptos_framework: &signer, config: vector) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG)); + move_to(aptos_framework, ConsensusConfig { config }); + } + + /// Deprecated by `set_for_next_epoch()`. + /// + /// WARNING: calling this while randomness is enabled will trigger a new epoch without randomness! + /// + /// TODO: update all the tests that reference this function, then disable this function. + public fun set(account: &signer, config: vector) acquires ConsensusConfig { + system_addresses::assert_aptos_framework(account); + chain_status::assert_genesis(); + assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG)); + + let config_ref = &mut borrow_global_mut(@aptos_framework).config; + *config_ref = config; + + // Need to trigger reconfiguration so validator nodes can sync on the updated configs. + reconfiguration::reconfigure(); + } + + /// This can be called by on-chain governance to update on-chain consensus configs for the next epoch. + /// Example usage: + /// ``` + /// aptos_framework::consensus_config::set_for_next_epoch(&framework_signer, some_config_bytes); + /// aptos_framework::aptos_governance::reconfigure(&framework_signer); + /// ``` + public fun set_for_next_epoch(account: &signer, config: vector) { + system_addresses::assert_aptos_framework(account); + assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG)); + std::config_buffer::upsert(ConsensusConfig {config}); + } + + /// Only used in reconfigurations to apply the pending `ConsensusConfig`, if there is any. + public(friend) fun on_new_epoch(framework: &signer) acquires ConsensusConfig { + system_addresses::assert_aptos_framework(framework); + if (config_buffer::does_exist()) { + let new_config = config_buffer::extract(); + if (exists(@aptos_framework)) { + *borrow_global_mut(@aptos_framework) = new_config; + } else { + move_to(framework, new_config); + }; + } + } + + public fun validator_txn_enabled(): bool acquires ConsensusConfig { + let config_bytes = borrow_global(@aptos_framework).config; + validator_txn_enabled_internal(config_bytes) + } + + native fun validator_txn_enabled_internal(config_bytes: vector): bool; +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/create_signer.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/create_signer.move new file mode 100644 index 000000000..3da0c50c9 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/create_signer.move @@ -0,0 +1,21 @@ +/// Provides a common place for exporting `create_signer` across the Aptos Framework. +/// +/// To use create_signer, add the module below, such that: +/// `friend aptos_framework::friend_wants_create_signer` +/// where `friend_wants_create_signer` is the module that needs `create_signer`. +/// +/// Note, that this is only available within the Aptos Framework. +/// +/// This exists to make auditing straight forward and to limit the need to depend +/// on account to have access to this. +module aptos_framework::create_signer { + friend aptos_framework::account; + friend aptos_framework::aptos_account; + friend aptos_framework::coin; + friend aptos_framework::fungible_asset; + friend aptos_framework::genesis; + friend aptos_framework::multisig_account; + friend aptos_framework::object; + + public(friend) native fun create_signer(addr: address): signer; +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/delegation_pool.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/delegation_pool.move new file mode 100644 index 000000000..be1643ca6 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/delegation_pool.move @@ -0,0 +1,5568 @@ +/** +Allow multiple delegators to participate in the same stake pool in order to collect the minimum +stake required to join the validator set. Delegators are rewarded out of the validator rewards +proportionally to their stake and provided the same stake-management API as the stake pool owner. + +The main accounting logic in the delegation pool contract handles the following: +1. Tracks how much stake each delegator owns, privately deposited as well as earned. +Accounting individual delegator stakes is achieved through the shares-based pool defined at +aptos_std::pool_u64, hence delegators own shares rather than absolute stakes into the delegation pool. +2. Tracks rewards earned by the stake pool, implicitly by the delegation one, in the meantime +and distribute them accordingly. +3. Tracks lockup cycles on the stake pool in order to separate inactive stake (not earning rewards) +from pending_inactive stake (earning rewards) and allow its delegators to withdraw the former. +4. Tracks how much commission fee has to be paid to the operator out of incoming rewards before +distributing them to the internal pool_u64 pools. + +In order to distinguish between stakes in different states and route rewards accordingly, +separate pool_u64 pools are used for individual stake states: +1. one of active + pending_active stake +2. one of inactive stake FOR each past observed lockup cycle (OLC) on the stake pool +3. one of pending_inactive stake scheduled during this ongoing OLC + +As stake-state transitions and rewards are computed only at the stake pool level, the delegation pool +gets outdated. To mitigate this, at any interaction with the delegation pool, a process of synchronization +to the underlying stake pool is executed before the requested operation itself. + +At synchronization: + - stake deviations between the two pools are actually the rewards produced in the meantime. + - the commission fee is extracted from the rewards, the remaining stake is distributed to the internal +pool_u64 pools and then the commission stake used to buy shares for operator. + - if detecting that the lockup expired on the stake pool, the delegation pool will isolate its +pending_inactive stake (now inactive) and create a new pool_u64 to host future pending_inactive stake +scheduled this newly started lockup. +Detecting a lockup expiration on the stake pool resumes to detecting new inactive stake. + +Accounting main invariants: + - each stake-management operation (add/unlock/reactivate/withdraw) and operator change triggers +the synchronization process before executing its own function. + - each OLC maps to one or more real lockups on the stake pool, but not the opposite. Actually, only a real +lockup with 'activity' (which inactivated some unlocking stake) triggers the creation of a new OLC. + - unlocking and/or unlocked stake originating from different real lockups are never mixed together into +the same pool_u64. This invalidates the accounting of which rewards belong to whom. + - no delegator can have unlocking and/or unlocked stake (pending withdrawals) in different OLCs. This ensures +delegators do not have to keep track of the OLCs when they unlocked. When creating a new pending withdrawal, +the existing one is executed (withdrawn) if is already inactive. + - add_stake fees are always refunded, but only after the epoch when they have been charged ends. + - withdrawing pending_inactive stake (when validator had gone inactive before its lockup expired) +does not inactivate any stake additional to the requested one to ensure OLC would not advance indefinitely. + - the pending withdrawal exists at an OLC iff delegator owns some shares within the shares pool of that OLC. + +Example flow: +
    +
  1. A node operator creates a delegation pool by calling +initialize_delegation_pool and sets +its commission fee to 0% (for simplicity). A stake pool is created with no initial stake and owned by +a resource account controlled by the delegation pool.
  2. +
  3. Delegator A adds 100 stake which is converted to 100 shares into the active pool_u64
  4. +
  5. Operator joins the validator set as the stake pool has now the minimum stake
  6. +
  7. The stake pool earned rewards and now has 200 active stake. A's active shares are worth 200 coins as +the commission fee is 0%.
  8. +
  9. +
      +
    1. A requests unlock for 100 stake
    2. +
    3. Synchronization detects 200 - 100 active rewards which are entirely (0% commission) added to the active pool.
    4. +
    5. 100 coins = (100 * 100) / 200 = 50 shares are redeemed from the active pool and exchanged for 100 shares +into the pending_inactive one on A's behalf
    6. +
    +
  10. Delegator B adds 200 stake which is converted to (200 * 50) / 100 = 100 shares into the active pool
  11. +
  12. The stake pool earned rewards and now has 600 active and 200 pending_inactive stake.
  13. +
  14. +
      +
    1. A requests reactivate_stake for 100 stake
    2. +
    3. + Synchronization detects 600 - 300 active and 200 - 100 pending_inactive rewards which are both entirely + distributed to their corresponding pools +
    4. +
    5. + 100 coins = (100 * 100) / 200 = 50 shares are redeemed from the pending_inactive pool and exchanged for + (100 * 150) / 600 = 25 shares into the active one on A's behalf +
    6. +
    +
  15. The lockup expires on the stake pool, inactivating the entire pending_inactive stake
  16. +
  17. +
      +
    1. B requests unlock for 100 stake
    2. +
    3. + Synchronization detects no active or pending_inactive rewards, but 0 -> 100 inactive stake on the stake pool, + so it advances the observed lockup cycle and creates a pool_u64 for the new lockup, hence allowing previous + pending_inactive shares to be redeemed
    4. +
    5. + 100 coins = (100 * 175) / 700 = 25 shares are redeemed from the active pool and exchanged for 100 shares + into the new pending_inactive one on B's behalf +
    6. +
    +
  18. The stake pool earned rewards and now has some pending_inactive rewards.
  19. +
  20. +
      +
    1. A requests withdraw for its entire inactive stake
    2. +
    3. + Synchronization detects no new inactive stake, but some pending_inactive rewards which are distributed + to the (2nd) pending_inactive pool +
    4. +
    5. + A's 50 shares = (50 * 100) / 50 = 100 coins are redeemed from the (1st) inactive pool and 100 stake is + transferred to A +
    6. +
    +
+ */ +module aptos_framework::delegation_pool { + use std::error; + use std::features; + use std::signer; + use std::vector; + + use aptos_std::math64; + use aptos_std::pool_u64_unbound::{Self as pool_u64, total_coins}; + use aptos_std::table::{Self, Table}; + use aptos_std::smart_table::{Self, SmartTable}; + + use aptos_framework::account; + use aptos_framework::aptos_account; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::aptos_governance; + use aptos_framework::coin; + use aptos_framework::event::{Self, EventHandle, emit}; + use aptos_framework::stake; + use aptos_framework::stake::get_operator; + use aptos_framework::staking_config; + use aptos_framework::timestamp; + + const MODULE_SALT: vector = b"aptos_framework::delegation_pool"; + + /// Delegation pool owner capability does not exist at the provided account. + const EOWNER_CAP_NOT_FOUND: u64 = 1; + + /// Account is already owning a delegation pool. + const EOWNER_CAP_ALREADY_EXISTS: u64 = 2; + + /// Delegation pool does not exist at the provided pool address. + const EDELEGATION_POOL_DOES_NOT_EXIST: u64 = 3; + + /// There is a pending withdrawal to be executed before `unlock`ing any new stake. + const EPENDING_WITHDRAWAL_EXISTS: u64 = 4; + + /// Commission percentage has to be between 0 and `MAX_FEE` - 100%. + const EINVALID_COMMISSION_PERCENTAGE: u64 = 5; + + /// There is not enough `active` stake on the stake pool to `unlock`. + const ENOT_ENOUGH_ACTIVE_STAKE_TO_UNLOCK: u64 = 6; + + /// Slashing (if implemented) should not be applied to already `inactive` stake. + /// Not only it invalidates the accounting of past observed lockup cycles (OLC), + /// but is also unfair to delegators whose stake has been inactive before validator started misbehaving. + /// Additionally, the inactive stake does not count on the voting power of validator. + const ESLASHED_INACTIVE_STAKE_ON_PAST_OLC: u64 = 7; + + /// Delegator's active balance cannot be less than `MIN_COINS_ON_SHARES_POOL`. + const EDELEGATOR_ACTIVE_BALANCE_TOO_LOW: u64 = 8; + + /// Delegator's pending_inactive balance cannot be less than `MIN_COINS_ON_SHARES_POOL`. + const EDELEGATOR_PENDING_INACTIVE_BALANCE_TOO_LOW: u64 = 9; + + /// Creating delegation pools is not enabled yet. + const EDELEGATION_POOLS_DISABLED: u64 = 10; + + /// Cannot request to withdraw zero stake. + const EWITHDRAW_ZERO_STAKE: u64 = 11; + + /// Function is deprecated. + const EDEPRECATED_FUNCTION: u64 = 12; + + /// The function is disabled or hasn't been enabled. + const EDISABLED_FUNCTION: u64 = 13; + + /// Partial governance voting hasn't been enabled on this delegation pool. + const EPARTIAL_GOVERNANCE_VOTING_NOT_ENABLED: u64 = 14; + + /// The voter does not have sufficient stake to create a proposal. + const EINSUFFICIENT_PROPOSER_STAKE: u64 = 15; + + /// The voter does not have any voting power on this proposal. + const ENO_VOTING_POWER: u64 = 16; + + /// The stake pool has already voted on the proposal before enabling partial governance voting on this delegation pool. + const EALREADY_VOTED_BEFORE_ENABLE_PARTIAL_VOTING: u64 = 17; + + /// The account is not the operator of the stake pool. + const ENOT_OPERATOR: u64 = 18; + + /// Changing beneficiaries for operators is not supported. + const EOPERATOR_BENEFICIARY_CHANGE_NOT_SUPPORTED: u64 = 19; + + /// Commission percentage increase is too large. + const ETOO_LARGE_COMMISSION_INCREASE: u64 = 20; + + /// Commission percentage change is too late in this lockup period, and should be done at least a quarter (1/4) of the lockup duration before the lockup cycle ends. + const ETOO_LATE_COMMISSION_CHANGE: u64 = 21; + + /// Changing operator commission rate in delegation pool is not supported. + const ECOMMISSION_RATE_CHANGE_NOT_SUPPORTED: u64 = 22; + + /// Delegators allowlisting is not supported. + const EDELEGATORS_ALLOWLISTING_NOT_SUPPORTED: u64 = 23; + + /// Delegators allowlisting should be enabled to perform this operation. + const EDELEGATORS_ALLOWLISTING_NOT_ENABLED: u64 = 24; + + /// Cannot add/reactivate stake unless being allowlisted by the pool owner. + const EDELEGATOR_NOT_ALLOWLISTED: u64 = 25; + + /// Cannot evict an allowlisted delegator, should remove them from the allowlist first. + const ECANNOT_EVICT_ALLOWLISTED_DELEGATOR: u64 = 26; + + /// Cannot unlock the accumulated active stake of NULL_SHAREHOLDER(0x0). + const ECANNOT_UNLOCK_NULL_SHAREHOLDER: u64 = 27; + + const MAX_U64: u64 = 18446744073709551615; + + /// Maximum operator percentage fee(of double digit precision): 22.85% is represented as 2285 + const MAX_FEE: u64 = 10000; + + const VALIDATOR_STATUS_INACTIVE: u64 = 4; + + /// Special shareholder temporarily owning the `add_stake` fees charged during this epoch. + /// On each `add_stake` operation any resulted fee is used to buy active shares for this shareholder. + /// First synchronization after this epoch ends will distribute accumulated fees to the rest of the pool as refunds. + const NULL_SHAREHOLDER: address = @0x0; + + /// Minimum coins to exist on a shares pool at all times. + /// Enforced per delegator for both active and pending_inactive pools. + /// This constraint ensures the share price cannot overly increase and lead to + /// substantial losses when buying shares (can lose at most 1 share which may + /// be worth a lot if current share price is high). + /// This constraint is not enforced on inactive pools as they only allow redeems + /// (can lose at most 1 coin regardless of current share price). + const MIN_COINS_ON_SHARES_POOL: u64 = 1000000000; + + /// Scaling factor of shares pools used within the delegation pool + const SHARES_SCALING_FACTOR: u64 = 10000000000000000; + + /// Maximum commission percentage increase per lockup cycle. 10% is represented as 1000. + const MAX_COMMISSION_INCREASE: u64 = 1000; + + /// Capability that represents ownership over privileged operations on the underlying stake pool. + struct DelegationPoolOwnership has key, store { + /// equal to address of the resource account owning the stake pool + pool_address: address, + } + + struct ObservedLockupCycle has copy, drop, store { + index: u64, + } + + struct DelegationPool has key { + // Shares pool of `active` + `pending_active` stake + active_shares: pool_u64::Pool, + // Index of current observed lockup cycle on the delegation pool since its creation + observed_lockup_cycle: ObservedLockupCycle, + // Shares pools of `inactive` stake on each ended OLC and `pending_inactive` stake on the current one. + // Tracks shares of delegators who requested withdrawals in each OLC + inactive_shares: Table, + // Mapping from delegator address to the OLC of its pending withdrawal if having one + pending_withdrawals: Table, + // Signer capability of the resource account owning the stake pool + stake_pool_signer_cap: account::SignerCapability, + // Total (inactive) coins on the shares pools over all ended OLCs + total_coins_inactive: u64, + // Commission fee paid to the node operator out of pool rewards + operator_commission_percentage: u64, + + // The events emitted by stake-management operations on the delegation pool + add_stake_events: EventHandle, + reactivate_stake_events: EventHandle, + unlock_stake_events: EventHandle, + withdraw_stake_events: EventHandle, + distribute_commission_events: EventHandle, + } + + struct VotingRecordKey has copy, drop, store { + voter: address, + proposal_id: u64, + } + + /// Track delegated voter of each delegator. + struct VoteDelegation has copy, drop, store { + // The account who can vote on behalf of this delegator. + voter: address, + // The account that will become the voter in the next lockup period. Changing voter address needs 1 lockup + // period to take effects. + pending_voter: address, + // Tracks the last known lockup cycle end when the voter was updated. This will be used to determine when + // the new voter becomes effective. + // If != last_locked_until_secs, it means that a lockup period has passed. + // This is slightly different from ObservedLockupCycle because ObservedLockupCycle cannot detect if a lockup + // period is passed when there is no unlocking during the lockup period. + last_locked_until_secs: u64, + } + + /// Track total voting power of each voter. + struct DelegatedVotes has copy, drop, store { + // The total number of active shares delegated to this voter by all delegators. + active_shares: u128, + // The total number of pending inactive shares delegated to this voter by all delegators + pending_inactive_shares: u128, + // Total active shares delegated to this voter in the next lockup cycle. + // `active_shares_next_lockup` might be different `active_shares` when some delegators change their voter. + active_shares_next_lockup: u128, + // Tracks the last known lockup cycle end when the voter was updated. This will be used to determine when + // the new voter becomes effective. + // If != last_locked_until_secs, it means that a lockup period has passed. + // This is slightly different from ObservedLockupCycle because ObservedLockupCycle cannot detect if a lockup + // period is passed when there is no unlocking during the lockup period. + last_locked_until_secs: u64, + } + + /// Track governance information of a delegation(e.g. voter delegation/voting power calculation). + /// This struct should be stored in the delegation pool resource account. + struct GovernanceRecords has key { + // `votes` tracks voting power usage of each voter on each proposal. + votes: SmartTable, + // `votes_per_proposal` tracks voting power usage of this stake pool on each proposal. Key is proposal_id. + votes_per_proposal: SmartTable, + vote_delegation: SmartTable, + delegated_votes: SmartTable, + vote_events: EventHandle, + create_proposal_events: EventHandle, + // Note: a DelegateVotingPowerEvent event only means that the delegator tries to change its voter. The change + // won't take effect until the next lockup period. + delegate_voting_power_events: EventHandle, + } + + struct BeneficiaryForOperator has key { + beneficiary_for_operator: address, + } + + struct NextCommissionPercentage has key { + commission_percentage_next_lockup_cycle: u64, + effective_after_secs: u64, + } + + /// Tracks a delegation pool's allowlist of delegators. + /// If allowlisting is enabled, existing delegators are not implicitly allowlisted and they can be individually + /// evicted later by the pool owner. + struct DelegationPoolAllowlisting has key { + allowlist: SmartTable, + } + + #[event] + struct AddStake has drop, store { + pool_address: address, + delegator_address: address, + amount_added: u64, + add_stake_fee: u64, + } + + struct AddStakeEvent has drop, store { + pool_address: address, + delegator_address: address, + amount_added: u64, + add_stake_fee: u64, + } + + #[event] + struct ReactivateStake has drop, store { + pool_address: address, + delegator_address: address, + amount_reactivated: u64, + } + + struct ReactivateStakeEvent has drop, store { + pool_address: address, + delegator_address: address, + amount_reactivated: u64, + } + + #[event] + struct UnlockStake has drop, store { + pool_address: address, + delegator_address: address, + amount_unlocked: u64, + } + + struct UnlockStakeEvent has drop, store { + pool_address: address, + delegator_address: address, + amount_unlocked: u64, + } + + #[event] + struct WithdrawStake has drop, store { + pool_address: address, + delegator_address: address, + amount_withdrawn: u64, + } + + struct WithdrawStakeEvent has drop, store { + pool_address: address, + delegator_address: address, + amount_withdrawn: u64, + } + + #[event] + struct DistributeCommissionEvent has drop, store { + pool_address: address, + operator: address, + commission_active: u64, + commission_pending_inactive: u64, + } + + #[event] + struct DistributeCommission has drop, store { + pool_address: address, + operator: address, + beneficiary: address, + commission_active: u64, + commission_pending_inactive: u64, + } + + #[event] + struct Vote has drop, store { + voter: address, + proposal_id: u64, + delegation_pool: address, + num_votes: u64, + should_pass: bool, + } + + struct VoteEvent has drop, store { + voter: address, + proposal_id: u64, + delegation_pool: address, + num_votes: u64, + should_pass: bool, + } + + #[event] + struct CreateProposal has drop, store { + proposal_id: u64, + voter: address, + delegation_pool: address, + } + + struct CreateProposalEvent has drop, store { + proposal_id: u64, + voter: address, + delegation_pool: address, + } + + #[event] + struct DelegateVotingPower has drop, store { + pool_address: address, + delegator: address, + voter: address, + } + + struct DelegateVotingPowerEvent has drop, store { + pool_address: address, + delegator: address, + voter: address, + } + + #[event] + struct SetBeneficiaryForOperator has drop, store { + operator: address, + old_beneficiary: address, + new_beneficiary: address, + } + + #[event] + struct CommissionPercentageChange has drop, store { + pool_address: address, + owner: address, + commission_percentage_next_lockup_cycle: u64, + } + + #[event] + struct EnableDelegatorsAllowlisting has drop, store { + pool_address: address, + } + + #[event] + struct DisableDelegatorsAllowlisting has drop, store { + pool_address: address, + } + + #[event] + struct AllowlistDelegator has drop, store { + pool_address: address, + delegator_address: address, + } + + #[event] + struct RemoveDelegatorFromAllowlist has drop, store { + pool_address: address, + delegator_address: address, + } + + #[event] + struct EvictDelegator has drop, store { + pool_address: address, + delegator_address: address, + } + + #[view] + /// Return whether supplied address `addr` is owner of a delegation pool. + public fun owner_cap_exists(addr: address): bool { + exists(addr) + } + + #[view] + /// Return address of the delegation pool owned by `owner` or fail if there is none. + public fun get_owned_pool_address(owner: address): address acquires DelegationPoolOwnership { + assert_owner_cap_exists(owner); + borrow_global(owner).pool_address + } + + #[view] + /// Return whether a delegation pool exists at supplied address `addr`. + public fun delegation_pool_exists(addr: address): bool { + exists(addr) + } + + #[view] + /// Return whether a delegation pool has already enabled partial governance voting. + public fun partial_governance_voting_enabled(pool_address: address): bool { + exists(pool_address) && stake::get_delegated_voter(pool_address) == pool_address + } + + #[view] + /// Return the index of current observed lockup cycle on delegation pool `pool_address`. + public fun observed_lockup_cycle(pool_address: address): u64 acquires DelegationPool { + assert_delegation_pool_exists(pool_address); + borrow_global(pool_address).observed_lockup_cycle.index + } + + #[view] + /// Return whether the commission percentage for the next lockup cycle is effective. + public fun is_next_commission_percentage_effective(pool_address: address): bool acquires NextCommissionPercentage { + exists(pool_address) && + timestamp::now_seconds() >= borrow_global(pool_address).effective_after_secs + } + + #[view] + /// Return the operator commission percentage set on the delegation pool `pool_address`. + public fun operator_commission_percentage( + pool_address: address + ): u64 acquires DelegationPool, NextCommissionPercentage { + assert_delegation_pool_exists(pool_address); + if (is_next_commission_percentage_effective(pool_address)) { + operator_commission_percentage_next_lockup_cycle(pool_address) + } else { + borrow_global(pool_address).operator_commission_percentage + } + } + + #[view] + /// Return the operator commission percentage for the next lockup cycle. + public fun operator_commission_percentage_next_lockup_cycle( + pool_address: address + ): u64 acquires DelegationPool, NextCommissionPercentage { + assert_delegation_pool_exists(pool_address); + if (exists(pool_address)) { + borrow_global(pool_address).commission_percentage_next_lockup_cycle + } else { + borrow_global(pool_address).operator_commission_percentage + } + } + + #[view] + /// Return the number of delegators owning active stake within `pool_address`. + public fun shareholders_count_active_pool(pool_address: address): u64 acquires DelegationPool { + assert_delegation_pool_exists(pool_address); + pool_u64::shareholders_count(&borrow_global(pool_address).active_shares) + } + + #[view] + /// Return the stake amounts on `pool_address` in the different states: + /// (`active`,`inactive`,`pending_active`,`pending_inactive`) + public fun get_delegation_pool_stake(pool_address: address): (u64, u64, u64, u64) { + assert_delegation_pool_exists(pool_address); + stake::get_stake(pool_address) + } + + #[view] + /// Return whether the given delegator has any withdrawable stake. If they recently requested to unlock + /// some stake and the stake pool's lockup cycle has not ended, their coins are not withdrawable yet. + public fun get_pending_withdrawal( + pool_address: address, + delegator_address: address + ): (bool, u64) acquires DelegationPool { + assert_delegation_pool_exists(pool_address); + let pool = borrow_global(pool_address); + let ( + lockup_cycle_ended, + _, + pending_inactive, + _, + commission_pending_inactive + ) = calculate_stake_pool_drift(pool); + + let (withdrawal_exists, withdrawal_olc) = pending_withdrawal_exists(pool, delegator_address); + if (!withdrawal_exists) { + // if no pending withdrawal, there is neither inactive nor pending_inactive stake + (false, 0) + } else { + // delegator has either inactive or pending_inactive stake due to automatic withdrawals + let inactive_shares = table::borrow(&pool.inactive_shares, withdrawal_olc); + if (withdrawal_olc.index < pool.observed_lockup_cycle.index) { + // if withdrawal's lockup cycle ended on delegation pool then it is inactive + (true, pool_u64::balance(inactive_shares, delegator_address)) + } else { + pending_inactive = pool_u64::shares_to_amount_with_total_coins( + inactive_shares, + pool_u64::shares(inactive_shares, delegator_address), + // exclude operator pending_inactive rewards not converted to shares yet + pending_inactive - commission_pending_inactive + ); + // if withdrawal's lockup cycle ended ONLY on stake pool then it is also inactive + (lockup_cycle_ended, pending_inactive) + } + } + } + + #[view] + /// Return total stake owned by `delegator_address` within delegation pool `pool_address` + /// in each of its individual states: (`active`,`inactive`,`pending_inactive`) + public fun get_stake( + pool_address: address, + delegator_address: address + ): (u64, u64, u64) acquires DelegationPool, BeneficiaryForOperator { + assert_delegation_pool_exists(pool_address); + let pool = borrow_global(pool_address); + let ( + lockup_cycle_ended, + active, + _, + commission_active, + commission_pending_inactive + ) = calculate_stake_pool_drift(pool); + + let total_active_shares = pool_u64::total_shares(&pool.active_shares); + let delegator_active_shares = pool_u64::shares(&pool.active_shares, delegator_address); + + let (_, _, pending_active, _) = stake::get_stake(pool_address); + if (pending_active == 0) { + // zero `pending_active` stake indicates that either there are no `add_stake` fees or + // previous epoch has ended and should identify shares owning these fees as released + total_active_shares = total_active_shares - pool_u64::shares(&pool.active_shares, NULL_SHAREHOLDER); + if (delegator_address == NULL_SHAREHOLDER) { + delegator_active_shares = 0 + } + }; + active = pool_u64::shares_to_amount_with_total_stats( + &pool.active_shares, + delegator_active_shares, + // exclude operator active rewards not converted to shares yet + active - commission_active, + total_active_shares + ); + + // get state and stake (0 if there is none) of the pending withdrawal + let (withdrawal_inactive, withdrawal_stake) = get_pending_withdrawal(pool_address, delegator_address); + // report non-active stakes accordingly to the state of the pending withdrawal + let (inactive, pending_inactive) = if (withdrawal_inactive) (withdrawal_stake, 0) else (0, withdrawal_stake); + + // should also include commission rewards in case of the operator account + // operator rewards are actually used to buy shares which is introducing + // some imprecision (received stake would be slightly less) + // but adding rewards onto the existing stake is still a good approximation + if (delegator_address == beneficiary_for_operator(get_operator(pool_address))) { + active = active + commission_active; + // in-flight pending_inactive commission can coexist with already inactive withdrawal + if (lockup_cycle_ended) { + inactive = inactive + commission_pending_inactive + } else { + pending_inactive = pending_inactive + commission_pending_inactive + } + }; + + (active, inactive, pending_inactive) + } + + #[view] + /// Return refundable stake to be extracted from added `amount` at `add_stake` operation on pool `pool_address`. + /// If the validator produces rewards this epoch, added stake goes directly to `pending_active` and + /// does not earn rewards. However, all shares within a pool appreciate uniformly and when this epoch ends: + /// - either added shares are still `pending_active` and steal from rewards of existing `active` stake + /// - or have moved to `pending_inactive` and get full rewards (they displaced `active` stake at `unlock`) + /// To mitigate this, some of the added stake is extracted and fed back into the pool as placeholder + /// for the rewards the remaining stake would have earned if active: + /// extracted-fee = (amount - extracted-fee) * reward-rate% * (100% - operator-commission%) + public fun get_add_stake_fee( + pool_address: address, + amount: u64 + ): u64 acquires DelegationPool, NextCommissionPercentage { + if (stake::is_current_epoch_validator(pool_address)) { + let (rewards_rate, rewards_rate_denominator) = staking_config::get_reward_rate(&staking_config::get()); + if (rewards_rate_denominator > 0) { + assert_delegation_pool_exists(pool_address); + + rewards_rate = rewards_rate * (MAX_FEE - operator_commission_percentage(pool_address)); + rewards_rate_denominator = rewards_rate_denominator * MAX_FEE; + ((((amount as u128) * (rewards_rate as u128)) / ((rewards_rate as u128) + (rewards_rate_denominator as u128))) as u64) + } else { 0 } + } else { 0 } + } + + #[view] + /// Return whether `pending_inactive` stake can be directly withdrawn from + /// the delegation pool, implicitly its stake pool, in the special case + /// the validator had gone inactive before its lockup expired. + public fun can_withdraw_pending_inactive(pool_address: address): bool { + stake::get_validator_state(pool_address) == VALIDATOR_STATUS_INACTIVE && + timestamp::now_seconds() >= stake::get_lockup_secs(pool_address) + } + + #[view] + /// Return the total voting power of a delegator in a delegation pool. This function syncs DelegationPool to the + /// latest state. + public fun calculate_and_update_voter_total_voting_power( + pool_address: address, + voter: address + ): u64 acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + assert_partial_governance_voting_enabled(pool_address); + // Delegation pool need to be synced to explain rewards(which could change the coin amount) and + // commission(which could cause share transfer). + synchronize_delegation_pool(pool_address); + let pool = borrow_global(pool_address); + let governance_records = borrow_global_mut(pool_address); + let latest_delegated_votes = update_and_borrow_mut_delegated_votes(pool, governance_records, voter); + calculate_total_voting_power(pool, latest_delegated_votes) + } + + #[view] + /// Return the remaining voting power of a delegator in a delegation pool on a proposal. This function syncs DelegationPool to the + /// latest state. + public fun calculate_and_update_remaining_voting_power( + pool_address: address, + voter_address: address, + proposal_id: u64 + ): u64 acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + assert_partial_governance_voting_enabled(pool_address); + // If the whole stake pool has no voting power(e.g. it has already voted before partial + // governance voting flag is enabled), the delegator also has no voting power. + if (aptos_governance::get_remaining_voting_power(pool_address, proposal_id) == 0) { + return 0 + }; + + let total_voting_power = calculate_and_update_voter_total_voting_power(pool_address, voter_address); + let governance_records = borrow_global(pool_address); + total_voting_power - get_used_voting_power(governance_records, voter_address, proposal_id) + } + + #[view] + /// Return the latest delegated voter of a delegator in a delegation pool. This function syncs DelegationPool to the + /// latest state. + public fun calculate_and_update_delegator_voter( + pool_address: address, + delegator_address: address + ): address acquires DelegationPool, GovernanceRecords { + assert_partial_governance_voting_enabled(pool_address); + calculate_and_update_delegator_voter_internal( + borrow_global(pool_address), + borrow_global_mut(pool_address), + delegator_address + ) + } + + #[view] + /// Return the current state of a voting delegation of a delegator in a delegation pool. + public fun calculate_and_update_voting_delegation( + pool_address: address, + delegator_address: address + ): (address, address, u64) acquires DelegationPool, GovernanceRecords { + assert_partial_governance_voting_enabled(pool_address); + let vote_delegation = update_and_borrow_mut_delegator_vote_delegation( + borrow_global(pool_address), + borrow_global_mut(pool_address), + delegator_address + ); + + (vote_delegation.voter, vote_delegation.pending_voter, vote_delegation.last_locked_until_secs) + } + + #[view] + /// Return the address of the stake pool to be created with the provided owner, and seed. + public fun get_expected_stake_pool_address(owner: address, delegation_pool_creation_seed: vector + ): address { + let seed = create_resource_account_seed(delegation_pool_creation_seed); + account::create_resource_address(&owner, seed) + } + + #[view] + /// Return the minimum remaining time in seconds for commission change, which is one fourth of the lockup duration. + public fun min_remaining_secs_for_commission_change(): u64 { + let config = staking_config::get(); + staking_config::get_recurring_lockup_duration(&config) / 4 + } + + #[view] + /// Return whether allowlisting is enabled for the provided delegation pool. + public fun allowlisting_enabled(pool_address: address): bool { + assert_delegation_pool_exists(pool_address); + exists(pool_address) + } + + #[view] + /// Return whether the provided delegator is allowlisted. + /// A delegator is allowlisted if: + /// - allowlisting is disabled on the pool + /// - delegator is part of the allowlist + public fun delegator_allowlisted( + pool_address: address, + delegator_address: address, + ): bool acquires DelegationPoolAllowlisting { + if (!allowlisting_enabled(pool_address)) { return true }; + smart_table::contains(freeze(borrow_mut_delegators_allowlist(pool_address)), delegator_address) + } + + #[view] + /// Return allowlist or revert if allowlisting is not enabled for the provided delegation pool. + public fun get_delegators_allowlist( + pool_address: address, + ): vector
acquires DelegationPoolAllowlisting { + assert_allowlisting_enabled(pool_address); + + let allowlist = vector[]; + smart_table::for_each_ref(freeze(borrow_mut_delegators_allowlist(pool_address)), |delegator, _v| { + vector::push_back(&mut allowlist, *delegator); + }); + allowlist + } + + /// Initialize a delegation pool of custom fixed `operator_commission_percentage`. + /// A resource account is created from `owner` signer and its supplied `delegation_pool_creation_seed` + /// to host the delegation pool resource and own the underlying stake pool. + /// Ownership over setting the operator/voter is granted to `owner` who has both roles initially. + public entry fun initialize_delegation_pool( + owner: &signer, + operator_commission_percentage: u64, + delegation_pool_creation_seed: vector, + ) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + assert!(features::delegation_pools_enabled(), error::invalid_state(EDELEGATION_POOLS_DISABLED)); + let owner_address = signer::address_of(owner); + assert!(!owner_cap_exists(owner_address), error::already_exists(EOWNER_CAP_ALREADY_EXISTS)); + assert!(operator_commission_percentage <= MAX_FEE, error::invalid_argument(EINVALID_COMMISSION_PERCENTAGE)); + + // generate a seed to be used to create the resource account hosting the delegation pool + let seed = create_resource_account_seed(delegation_pool_creation_seed); + + let (stake_pool_signer, stake_pool_signer_cap) = account::create_resource_account(owner, seed); + coin::register(&stake_pool_signer); + + // stake_pool_signer will be owner of the stake pool and have its `stake::OwnerCapability` + let pool_address = signer::address_of(&stake_pool_signer); + stake::initialize_stake_owner(&stake_pool_signer, 0, owner_address, owner_address); + + let inactive_shares = table::new(); + table::add( + &mut inactive_shares, + olc_with_index(0), + pool_u64::create_with_scaling_factor(SHARES_SCALING_FACTOR) + ); + + move_to(&stake_pool_signer, DelegationPool { + active_shares: pool_u64::create_with_scaling_factor(SHARES_SCALING_FACTOR), + observed_lockup_cycle: olc_with_index(0), + inactive_shares, + pending_withdrawals: table::new(), + stake_pool_signer_cap, + total_coins_inactive: 0, + operator_commission_percentage, + add_stake_events: account::new_event_handle(&stake_pool_signer), + reactivate_stake_events: account::new_event_handle(&stake_pool_signer), + unlock_stake_events: account::new_event_handle(&stake_pool_signer), + withdraw_stake_events: account::new_event_handle(&stake_pool_signer), + distribute_commission_events: account::new_event_handle(&stake_pool_signer), + }); + + // save delegation pool ownership and resource account address (inner stake pool address) on `owner` + move_to(owner, DelegationPoolOwnership { pool_address }); + + // All delegation pool enable partial governance voting by default once the feature flag is enabled. + if (features::partial_governance_voting_enabled( + ) && features::delegation_pool_partial_governance_voting_enabled()) { + enable_partial_governance_voting(pool_address); + } + } + + #[view] + /// Return the beneficiary address of the operator. + public fun beneficiary_for_operator(operator: address): address acquires BeneficiaryForOperator { + if (exists(operator)) { + return borrow_global(operator).beneficiary_for_operator + } else { + operator + } + } + + /// Enable partial governance voting on a stake pool. The voter of this stake pool will be managed by this module. + /// The existing voter will be replaced. The function is permissionless. + public entry fun enable_partial_governance_voting( + pool_address: address, + ) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + assert!(features::partial_governance_voting_enabled(), error::invalid_state(EDISABLED_FUNCTION)); + assert!( + features::delegation_pool_partial_governance_voting_enabled(), + error::invalid_state(EDISABLED_FUNCTION) + ); + assert_delegation_pool_exists(pool_address); + // synchronize delegation and stake pools before any user operation. + synchronize_delegation_pool(pool_address); + + let delegation_pool = borrow_global(pool_address); + let stake_pool_signer = retrieve_stake_pool_owner(delegation_pool); + // delegated_voter is managed by the stake pool itself, which signer capability is managed by DelegationPool. + // So voting power of this stake pool can only be used through this module. + stake::set_delegated_voter(&stake_pool_signer, signer::address_of(&stake_pool_signer)); + + move_to(&stake_pool_signer, GovernanceRecords { + votes: smart_table::new(), + votes_per_proposal: smart_table::new(), + vote_delegation: smart_table::new(), + delegated_votes: smart_table::new(), + vote_events: account::new_event_handle(&stake_pool_signer), + create_proposal_events: account::new_event_handle(&stake_pool_signer), + delegate_voting_power_events: account::new_event_handle(&stake_pool_signer), + }); + } + + /// Vote on a proposal with a voter's voting power. To successfully vote, the following conditions must be met: + /// 1. The voting period of the proposal hasn't ended. + /// 2. The delegation pool's lockup period ends after the voting period of the proposal. + /// 3. The voter still has spare voting power on this proposal. + /// 4. The delegation pool never votes on the proposal before enabling partial governance voting. + public entry fun vote( + voter: &signer, + pool_address: address, + proposal_id: u64, + voting_power: u64, + should_pass: bool + ) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + assert_partial_governance_voting_enabled(pool_address); + // synchronize delegation and stake pools before any user operation. + synchronize_delegation_pool(pool_address); + + let voter_address = signer::address_of(voter); + let remaining_voting_power = calculate_and_update_remaining_voting_power( + pool_address, + voter_address, + proposal_id + ); + if (voting_power > remaining_voting_power) { + voting_power = remaining_voting_power; + }; + assert!(voting_power > 0, error::invalid_argument(ENO_VOTING_POWER)); + + let governance_records = borrow_global_mut(pool_address); + // Check a edge case during the transient period of enabling partial governance voting. + assert_and_update_proposal_used_voting_power(governance_records, pool_address, proposal_id, voting_power); + let used_voting_power = borrow_mut_used_voting_power(governance_records, voter_address, proposal_id); + *used_voting_power = *used_voting_power + voting_power; + + let pool_signer = retrieve_stake_pool_owner(borrow_global(pool_address)); + aptos_governance::partial_vote(&pool_signer, pool_address, proposal_id, voting_power, should_pass); + + if (features::module_event_migration_enabled()) { + event::emit( + Vote { + voter: voter_address, + proposal_id, + delegation_pool: pool_address, + num_votes: voting_power, + should_pass, + } + ); + }; + + event::emit_event( + &mut governance_records.vote_events, + VoteEvent { + voter: voter_address, + proposal_id, + delegation_pool: pool_address, + num_votes: voting_power, + should_pass, + } + ); + } + + /// A voter could create a governance proposal by this function. To successfully create a proposal, the voter's + /// voting power in THIS delegation pool must be not less than the minimum required voting power specified in + /// `aptos_governance.move`. + public entry fun create_proposal( + voter: &signer, + pool_address: address, + execution_hash: vector, + metadata_location: vector, + metadata_hash: vector, + is_multi_step_proposal: bool, + ) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + assert_partial_governance_voting_enabled(pool_address); + + // synchronize delegation and stake pools before any user operation + synchronize_delegation_pool(pool_address); + + let voter_addr = signer::address_of(voter); + let pool = borrow_global(pool_address); + let governance_records = borrow_global_mut(pool_address); + let total_voting_power = calculate_and_update_delegated_votes(pool, governance_records, voter_addr); + assert!( + total_voting_power >= aptos_governance::get_required_proposer_stake(), + error::invalid_argument(EINSUFFICIENT_PROPOSER_STAKE)); + let pool_signer = retrieve_stake_pool_owner(borrow_global(pool_address)); + let proposal_id = aptos_governance::create_proposal_v2_impl( + &pool_signer, + pool_address, + execution_hash, + metadata_location, + metadata_hash, + is_multi_step_proposal, + ); + + let governance_records = borrow_global_mut(pool_address); + + if (features::module_event_migration_enabled()) { + event::emit( + CreateProposal { + proposal_id, + voter: voter_addr, + delegation_pool: pool_address, + } + ); + }; + + event::emit_event( + &mut governance_records.create_proposal_events, + CreateProposalEvent { + proposal_id, + voter: voter_addr, + delegation_pool: pool_address, + } + ); + } + + fun assert_owner_cap_exists(owner: address) { + assert!(owner_cap_exists(owner), error::not_found(EOWNER_CAP_NOT_FOUND)); + } + + fun assert_delegation_pool_exists(pool_address: address) { + assert!(delegation_pool_exists(pool_address), error::invalid_argument(EDELEGATION_POOL_DOES_NOT_EXIST)); + } + + fun assert_min_active_balance(pool: &DelegationPool, delegator_address: address) { + let balance = pool_u64::balance(&pool.active_shares, delegator_address); + assert!(balance >= MIN_COINS_ON_SHARES_POOL, error::invalid_argument(EDELEGATOR_ACTIVE_BALANCE_TOO_LOW)); + } + + fun assert_min_pending_inactive_balance(pool: &DelegationPool, delegator_address: address) { + let balance = pool_u64::balance(pending_inactive_shares_pool(pool), delegator_address); + assert!( + balance >= MIN_COINS_ON_SHARES_POOL, + error::invalid_argument(EDELEGATOR_PENDING_INACTIVE_BALANCE_TOO_LOW) + ); + } + + fun assert_partial_governance_voting_enabled(pool_address: address) { + assert_delegation_pool_exists(pool_address); + assert!( + partial_governance_voting_enabled(pool_address), + error::invalid_state(EPARTIAL_GOVERNANCE_VOTING_NOT_ENABLED) + ); + } + + fun assert_allowlisting_enabled(pool_address: address) { + assert!(allowlisting_enabled(pool_address), error::invalid_state(EDELEGATORS_ALLOWLISTING_NOT_ENABLED)); + } + + fun assert_delegator_allowlisted( + pool_address: address, + delegator_address: address, + ) acquires DelegationPoolAllowlisting { + assert!( + delegator_allowlisted(pool_address, delegator_address), + error::permission_denied(EDELEGATOR_NOT_ALLOWLISTED) + ); + } + + fun coins_to_redeem_to_ensure_min_stake( + src_shares_pool: &pool_u64::Pool, + shareholder: address, + amount: u64, + ): u64 { + // find how many coins would be redeemed if supplying `amount` + let redeemed_coins = pool_u64::shares_to_amount( + src_shares_pool, + amount_to_shares_to_redeem(src_shares_pool, shareholder, amount) + ); + // if balance drops under threshold then redeem it entirely + let src_balance = pool_u64::balance(src_shares_pool, shareholder); + if (src_balance - redeemed_coins < MIN_COINS_ON_SHARES_POOL) { + amount = src_balance; + }; + amount + } + + fun coins_to_transfer_to_ensure_min_stake( + src_shares_pool: &pool_u64::Pool, + dst_shares_pool: &pool_u64::Pool, + shareholder: address, + amount: u64, + ): u64 { + // find how many coins would be redeemed from source if supplying `amount` + let redeemed_coins = pool_u64::shares_to_amount( + src_shares_pool, + amount_to_shares_to_redeem(src_shares_pool, shareholder, amount) + ); + // if balance on destination would be less than threshold then redeem difference to threshold + let dst_balance = pool_u64::balance(dst_shares_pool, shareholder); + if (dst_balance + redeemed_coins < MIN_COINS_ON_SHARES_POOL) { + // `redeemed_coins` >= `amount` - 1 as redeem can lose at most 1 coin + amount = MIN_COINS_ON_SHARES_POOL - dst_balance + 1; + }; + // check if new `amount` drops balance on source under threshold and adjust + coins_to_redeem_to_ensure_min_stake(src_shares_pool, shareholder, amount) + } + + /// Retrieves the shared resource account owning the stake pool in order + /// to forward a stake-management operation to this underlying pool. + fun retrieve_stake_pool_owner(pool: &DelegationPool): signer { + account::create_signer_with_capability(&pool.stake_pool_signer_cap) + } + + /// Get the address of delegation pool reference `pool`. + fun get_pool_address(pool: &DelegationPool): address { + account::get_signer_capability_address(&pool.stake_pool_signer_cap) + } + + /// Get the active share amount of the delegator. + fun get_delegator_active_shares(pool: &DelegationPool, delegator: address): u128 { + pool_u64::shares(&pool.active_shares, delegator) + } + + /// Get the pending inactive share amount of the delegator. + fun get_delegator_pending_inactive_shares(pool: &DelegationPool, delegator: address): u128 { + pool_u64::shares(pending_inactive_shares_pool(pool), delegator) + } + + /// Get the used voting power of a voter on a proposal. + fun get_used_voting_power(governance_records: &GovernanceRecords, voter: address, proposal_id: u64): u64 { + let votes = &governance_records.votes; + let key = VotingRecordKey { + voter, + proposal_id, + }; + *smart_table::borrow_with_default(votes, key, &0) + } + + /// Create the seed to derive the resource account address. + fun create_resource_account_seed( + delegation_pool_creation_seed: vector, + ): vector { + let seed = vector::empty(); + // include module salt (before any subseeds) to avoid conflicts with other modules creating resource accounts + vector::append(&mut seed, MODULE_SALT); + // include an additional salt in case the same resource account has already been created + vector::append(&mut seed, delegation_pool_creation_seed); + seed + } + + /// Borrow the mutable used voting power of a voter on a proposal. + inline fun borrow_mut_used_voting_power( + governance_records: &mut GovernanceRecords, + voter: address, + proposal_id: u64 + ): &mut u64 { + let votes = &mut governance_records.votes; + let key = VotingRecordKey { + proposal_id, + voter, + }; + smart_table::borrow_mut_with_default(votes, key, 0) + } + + /// Update VoteDelegation of a delegator to up-to-date then borrow_mut it. + fun update_and_borrow_mut_delegator_vote_delegation( + pool: &DelegationPool, + governance_records: &mut GovernanceRecords, + delegator: address + ): &mut VoteDelegation { + let pool_address = get_pool_address(pool); + let locked_until_secs = stake::get_lockup_secs(pool_address); + + let vote_delegation_table = &mut governance_records.vote_delegation; + // By default, a delegator's delegated voter is itself. + // TODO: recycle storage when VoteDelegation equals to default value. + if (!smart_table::contains(vote_delegation_table, delegator)) { + return smart_table::borrow_mut_with_default(vote_delegation_table, delegator, VoteDelegation { + voter: delegator, + last_locked_until_secs: locked_until_secs, + pending_voter: delegator, + }) + }; + + let vote_delegation = smart_table::borrow_mut(vote_delegation_table, delegator); + // A lockup period has passed since last time `vote_delegation` was updated. Pending voter takes effect. + if (vote_delegation.last_locked_until_secs < locked_until_secs) { + vote_delegation.voter = vote_delegation.pending_voter; + vote_delegation.last_locked_until_secs = locked_until_secs; + }; + vote_delegation + } + + /// Update DelegatedVotes of a voter to up-to-date then borrow_mut it. + fun update_and_borrow_mut_delegated_votes( + pool: &DelegationPool, + governance_records: &mut GovernanceRecords, + voter: address + ): &mut DelegatedVotes { + let pool_address = get_pool_address(pool); + let locked_until_secs = stake::get_lockup_secs(pool_address); + + let delegated_votes_per_voter = &mut governance_records.delegated_votes; + // By default, a delegator's voter is itself. + // TODO: recycle storage when DelegatedVotes equals to default value. + if (!smart_table::contains(delegated_votes_per_voter, voter)) { + let active_shares = get_delegator_active_shares(pool, voter); + let inactive_shares = get_delegator_pending_inactive_shares(pool, voter); + return smart_table::borrow_mut_with_default(delegated_votes_per_voter, voter, DelegatedVotes { + active_shares, + pending_inactive_shares: inactive_shares, + active_shares_next_lockup: active_shares, + last_locked_until_secs: locked_until_secs, + }) + }; + + let delegated_votes = smart_table::borrow_mut(delegated_votes_per_voter, voter); + // A lockup period has passed since last time `delegated_votes` was updated. Pending voter takes effect. + if (delegated_votes.last_locked_until_secs < locked_until_secs) { + delegated_votes.active_shares = delegated_votes.active_shares_next_lockup; + delegated_votes.pending_inactive_shares = 0; + delegated_votes.last_locked_until_secs = locked_until_secs; + }; + delegated_votes + } + + fun olc_with_index(index: u64): ObservedLockupCycle { + ObservedLockupCycle { index } + } + + /// Given the amounts of shares in `active_shares` pool and `inactive_shares` pool, calculate the total voting + /// power, which equals to the sum of the coin amounts. + fun calculate_total_voting_power(delegation_pool: &DelegationPool, latest_delegated_votes: &DelegatedVotes): u64 { + let active_amount = pool_u64::shares_to_amount( + &delegation_pool.active_shares, + latest_delegated_votes.active_shares); + let pending_inactive_amount = pool_u64::shares_to_amount( + pending_inactive_shares_pool(delegation_pool), + latest_delegated_votes.pending_inactive_shares); + active_amount + pending_inactive_amount + } + + /// Update VoteDelegation of a delegator to up-to-date then return the latest voter. + fun calculate_and_update_delegator_voter_internal( + pool: &DelegationPool, + governance_records: &mut GovernanceRecords, + delegator: address + ): address { + let vote_delegation = update_and_borrow_mut_delegator_vote_delegation(pool, governance_records, delegator); + vote_delegation.voter + } + + /// Update DelegatedVotes of a voter to up-to-date then return the total voting power of this voter. + fun calculate_and_update_delegated_votes( + pool: &DelegationPool, + governance_records: &mut GovernanceRecords, + voter: address + ): u64 { + let delegated_votes = update_and_borrow_mut_delegated_votes(pool, governance_records, voter); + calculate_total_voting_power(pool, delegated_votes) + } + + inline fun borrow_mut_delegators_allowlist( + pool_address: address + ): &mut SmartTable acquires DelegationPoolAllowlisting { + &mut borrow_global_mut(pool_address).allowlist + } + + /// Allows an owner to change the operator of the underlying stake pool. + public entry fun set_operator( + owner: &signer, + new_operator: address + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + let pool_address = get_owned_pool_address(signer::address_of(owner)); + // synchronize delegation and stake pools before any user operation + // ensure the old operator is paid its uncommitted commission rewards + synchronize_delegation_pool(pool_address); + stake::set_operator(&retrieve_stake_pool_owner(borrow_global(pool_address)), new_operator); + } + + /// Allows an operator to change its beneficiary. Any existing unpaid commission rewards will be paid to the new + /// beneficiary. To ensure payment to the current beneficiary, one should first call `synchronize_delegation_pool` + /// before switching the beneficiary. An operator can set one beneficiary for delegation pools, not a separate + /// one for each pool. + public entry fun set_beneficiary_for_operator( + operator: &signer, + new_beneficiary: address + ) acquires BeneficiaryForOperator { + assert!(features::operator_beneficiary_change_enabled(), std::error::invalid_state( + EOPERATOR_BENEFICIARY_CHANGE_NOT_SUPPORTED + )); + // The beneficiay address of an operator is stored under the operator's address. + // So, the operator does not need to be validated with respect to a staking pool. + let operator_addr = signer::address_of(operator); + let old_beneficiary = beneficiary_for_operator(operator_addr); + if (exists(operator_addr)) { + borrow_global_mut(operator_addr).beneficiary_for_operator = new_beneficiary; + } else { + move_to(operator, BeneficiaryForOperator { beneficiary_for_operator: new_beneficiary }); + }; + + emit(SetBeneficiaryForOperator { + operator: operator_addr, + old_beneficiary, + new_beneficiary, + }); + } + + /// Allows an owner to update the commission percentage for the operator of the underlying stake pool. + public entry fun update_commission_percentage( + owner: &signer, + new_commission_percentage: u64 + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + assert!(features::commission_change_delegation_pool_enabled(), error::invalid_state( + ECOMMISSION_RATE_CHANGE_NOT_SUPPORTED + )); + assert!(new_commission_percentage <= MAX_FEE, error::invalid_argument(EINVALID_COMMISSION_PERCENTAGE)); + let owner_address = signer::address_of(owner); + let pool_address = get_owned_pool_address(owner_address); + assert!( + operator_commission_percentage(pool_address) + MAX_COMMISSION_INCREASE >= new_commission_percentage, + error::invalid_argument(ETOO_LARGE_COMMISSION_INCREASE) + ); + assert!( + stake::get_remaining_lockup_secs(pool_address) >= min_remaining_secs_for_commission_change(), + error::invalid_state(ETOO_LATE_COMMISSION_CHANGE) + ); + + // synchronize delegation and stake pools before any user operation. this ensures: + // (1) the operator is paid its uncommitted commission rewards with the old commission percentage, and + // (2) any pending commission percentage change is applied before the new commission percentage is set. + synchronize_delegation_pool(pool_address); + + if (exists(pool_address)) { + let commission_percentage = borrow_global_mut(pool_address); + commission_percentage.commission_percentage_next_lockup_cycle = new_commission_percentage; + commission_percentage.effective_after_secs = stake::get_lockup_secs(pool_address); + } else { + let delegation_pool = borrow_global(pool_address); + let pool_signer = account::create_signer_with_capability(&delegation_pool.stake_pool_signer_cap); + move_to(&pool_signer, NextCommissionPercentage { + commission_percentage_next_lockup_cycle: new_commission_percentage, + effective_after_secs: stake::get_lockup_secs(pool_address), + }); + }; + + event::emit(CommissionPercentageChange { + pool_address, + owner: owner_address, + commission_percentage_next_lockup_cycle: new_commission_percentage, + }); + } + + /// Allows an owner to change the delegated voter of the underlying stake pool. + public entry fun set_delegated_voter( + owner: &signer, + new_voter: address + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + // No one can change delegated_voter once the partial governance voting feature is enabled. + assert!( + !features::delegation_pool_partial_governance_voting_enabled(), + error::invalid_state(EDEPRECATED_FUNCTION) + ); + let pool_address = get_owned_pool_address(signer::address_of(owner)); + // synchronize delegation and stake pools before any user operation + synchronize_delegation_pool(pool_address); + stake::set_delegated_voter(&retrieve_stake_pool_owner(borrow_global(pool_address)), new_voter); + } + + /// Allows a delegator to delegate its voting power to a voter. If this delegator already has a delegated voter, + /// this change won't take effects until the next lockup period. + public entry fun delegate_voting_power( + delegator: &signer, + pool_address: address, + new_voter: address + ) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + assert_partial_governance_voting_enabled(pool_address); + + // synchronize delegation and stake pools before any user operation + synchronize_delegation_pool(pool_address); + + let delegator_address = signer::address_of(delegator); + let delegation_pool = borrow_global(pool_address); + let governance_records = borrow_global_mut(pool_address); + let delegator_vote_delegation = update_and_borrow_mut_delegator_vote_delegation( + delegation_pool, + governance_records, + delegator_address + ); + let pending_voter: address = delegator_vote_delegation.pending_voter; + + // No need to update if the voter doesn't really change. + if (pending_voter != new_voter) { + delegator_vote_delegation.pending_voter = new_voter; + let active_shares = get_delegator_active_shares(delegation_pool, delegator_address); + // of -= + // of += + let pending_delegated_votes = update_and_borrow_mut_delegated_votes( + delegation_pool, + governance_records, + pending_voter + ); + pending_delegated_votes.active_shares_next_lockup = + pending_delegated_votes.active_shares_next_lockup - active_shares; + + let new_delegated_votes = update_and_borrow_mut_delegated_votes( + delegation_pool, + governance_records, + new_voter + ); + new_delegated_votes.active_shares_next_lockup = + new_delegated_votes.active_shares_next_lockup + active_shares; + }; + + if (features::module_event_migration_enabled()) { + event::emit(DelegateVotingPower { + pool_address, + delegator: delegator_address, + voter: new_voter, + }) + }; + + event::emit_event(&mut governance_records.delegate_voting_power_events, DelegateVotingPowerEvent { + pool_address, + delegator: delegator_address, + voter: new_voter, + }); + } + + /// Enable delegators allowlisting as the pool owner. + public entry fun enable_delegators_allowlisting( + owner: &signer, + ) acquires DelegationPoolOwnership, DelegationPool { + assert!( + features::delegation_pool_allowlisting_enabled(), + error::invalid_state(EDELEGATORS_ALLOWLISTING_NOT_SUPPORTED) + ); + + let pool_address = get_owned_pool_address(signer::address_of(owner)); + if (allowlisting_enabled(pool_address)) { return }; + + let pool_signer = retrieve_stake_pool_owner(borrow_global(pool_address)); + move_to(&pool_signer, DelegationPoolAllowlisting { allowlist: smart_table::new() }); + + event::emit(EnableDelegatorsAllowlisting { pool_address }); + } + + /// Disable delegators allowlisting as the pool owner. The existing allowlist will be emptied. + public entry fun disable_delegators_allowlisting( + owner: &signer, + ) acquires DelegationPoolOwnership, DelegationPoolAllowlisting { + let pool_address = get_owned_pool_address(signer::address_of(owner)); + assert_allowlisting_enabled(pool_address); + + let DelegationPoolAllowlisting { allowlist } = move_from(pool_address); + // if the allowlist becomes too large, the owner can always remove some delegators + smart_table::destroy(allowlist); + + event::emit(DisableDelegatorsAllowlisting { pool_address }); + } + + /// Allowlist a delegator as the pool owner. + public entry fun allowlist_delegator( + owner: &signer, + delegator_address: address, + ) acquires DelegationPoolOwnership, DelegationPoolAllowlisting { + let pool_address = get_owned_pool_address(signer::address_of(owner)); + assert_allowlisting_enabled(pool_address); + + if (delegator_allowlisted(pool_address, delegator_address)) { return }; + + smart_table::add(borrow_mut_delegators_allowlist(pool_address), delegator_address, true); + + event::emit(AllowlistDelegator { pool_address, delegator_address }); + } + + /// Remove a delegator from the allowlist as the pool owner, but do not unlock their stake. + public entry fun remove_delegator_from_allowlist( + owner: &signer, + delegator_address: address, + ) acquires DelegationPoolOwnership, DelegationPoolAllowlisting { + let pool_address = get_owned_pool_address(signer::address_of(owner)); + assert_allowlisting_enabled(pool_address); + + if (!delegator_allowlisted(pool_address, delegator_address)) { return }; + + smart_table::remove(borrow_mut_delegators_allowlist(pool_address), delegator_address); + + event::emit(RemoveDelegatorFromAllowlist { pool_address, delegator_address }); + } + + /// Evict a delegator that is not allowlisted by unlocking their entire stake. + public entry fun evict_delegator( + owner: &signer, + delegator_address: address, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + let pool_address = get_owned_pool_address(signer::address_of(owner)); + assert_allowlisting_enabled(pool_address); + assert!( + !delegator_allowlisted(pool_address, delegator_address), + error::invalid_state(ECANNOT_EVICT_ALLOWLISTED_DELEGATOR) + ); + + // synchronize pool in order to query latest balance of delegator + synchronize_delegation_pool(pool_address); + + let pool = borrow_global(pool_address); + if (get_delegator_active_shares(pool, delegator_address) == 0) { return }; + + unlock_internal(delegator_address, pool_address, pool_u64::balance(&pool.active_shares, delegator_address)); + + event::emit(EvictDelegator { pool_address, delegator_address }); + } + + /// Add `amount` of coins to the delegation pool `pool_address`. + public entry fun add_stake( + delegator: &signer, + pool_address: address, + amount: u64 + ) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + // short-circuit if amount to add is 0 so no event is emitted + if (amount == 0) { return }; + + let delegator_address = signer::address_of(delegator); + assert_delegator_allowlisted(pool_address, delegator_address); + + // synchronize delegation and stake pools before any user operation + synchronize_delegation_pool(pool_address); + + // fee to be charged for adding `amount` stake on this delegation pool at this epoch + let add_stake_fee = get_add_stake_fee(pool_address, amount); + + let pool = borrow_global_mut(pool_address); + + // stake the entire amount to the stake pool + aptos_account::transfer(delegator, pool_address, amount); + stake::add_stake(&retrieve_stake_pool_owner(pool), amount); + + // but buy shares for delegator just for the remaining amount after fee + buy_in_active_shares(pool, delegator_address, amount - add_stake_fee); + assert_min_active_balance(pool, delegator_address); + + // grant temporary ownership over `add_stake` fees to a separate shareholder in order to: + // - not mistake them for rewards to pay the operator from + // - distribute them together with the `active` rewards when this epoch ends + // in order to appreciate all shares on the active pool atomically + buy_in_active_shares(pool, NULL_SHAREHOLDER, add_stake_fee); + + if (features::module_event_migration_enabled()) { + event::emit( + AddStake { + pool_address, + delegator_address, + amount_added: amount, + add_stake_fee, + }, + ); + }; + + event::emit_event( + &mut pool.add_stake_events, + AddStakeEvent { + pool_address, + delegator_address, + amount_added: amount, + add_stake_fee, + }, + ); + } + + /// Unlock `amount` from the active + pending_active stake of `delegator` or + /// at most how much active stake there is on the stake pool. + public entry fun unlock( + delegator: &signer, + pool_address: address, + amount: u64 + ) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + // short-circuit if amount to unlock is 0 so no event is emitted + if (amount == 0) { return }; + + // synchronize delegation and stake pools before any user operation + synchronize_delegation_pool(pool_address); + + let delegator_address = signer::address_of(delegator); + unlock_internal(delegator_address, pool_address, amount); + } + + fun unlock_internal( + delegator_address: address, + pool_address: address, + amount: u64 + ) acquires DelegationPool, GovernanceRecords { + assert!(delegator_address != NULL_SHAREHOLDER, error::invalid_argument(ECANNOT_UNLOCK_NULL_SHAREHOLDER)); + + // fail unlock of more stake than `active` on the stake pool + let (active, _, _, _) = stake::get_stake(pool_address); + assert!(amount <= active, error::invalid_argument(ENOT_ENOUGH_ACTIVE_STAKE_TO_UNLOCK)); + + let pool = borrow_global_mut(pool_address); + amount = coins_to_transfer_to_ensure_min_stake( + &pool.active_shares, + pending_inactive_shares_pool(pool), + delegator_address, + amount, + ); + amount = redeem_active_shares(pool, delegator_address, amount); + + stake::unlock(&retrieve_stake_pool_owner(pool), amount); + + buy_in_pending_inactive_shares(pool, delegator_address, amount); + assert_min_pending_inactive_balance(pool, delegator_address); + + if (features::module_event_migration_enabled()) { + event::emit( + UnlockStake { + pool_address, + delegator_address, + amount_unlocked: amount, + }, + ); + }; + + event::emit_event( + &mut pool.unlock_stake_events, + UnlockStakeEvent { + pool_address, + delegator_address, + amount_unlocked: amount, + }, + ); + } + + /// Move `amount` of coins from pending_inactive to active. + public entry fun reactivate_stake( + delegator: &signer, + pool_address: address, + amount: u64 + ) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + // short-circuit if amount to reactivate is 0 so no event is emitted + if (amount == 0) { return }; + + let delegator_address = signer::address_of(delegator); + assert_delegator_allowlisted(pool_address, delegator_address); + + // synchronize delegation and stake pools before any user operation + synchronize_delegation_pool(pool_address); + + let pool = borrow_global_mut(pool_address); + amount = coins_to_transfer_to_ensure_min_stake( + pending_inactive_shares_pool(pool), + &pool.active_shares, + delegator_address, + amount, + ); + let observed_lockup_cycle = pool.observed_lockup_cycle; + amount = redeem_inactive_shares(pool, delegator_address, amount, observed_lockup_cycle); + + stake::reactivate_stake(&retrieve_stake_pool_owner(pool), amount); + + buy_in_active_shares(pool, delegator_address, amount); + assert_min_active_balance(pool, delegator_address); + + if (features::module_event_migration_enabled()) { + event::emit( + ReactivateStake { + pool_address, + delegator_address, + amount_reactivated: amount, + }, + ); + }; + + event::emit_event( + &mut pool.reactivate_stake_events, + ReactivateStakeEvent { + pool_address, + delegator_address, + amount_reactivated: amount, + }, + ); + } + + /// Withdraw `amount` of owned inactive stake from the delegation pool at `pool_address`. + public entry fun withdraw( + delegator: &signer, + pool_address: address, + amount: u64 + ) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + assert!(amount > 0, error::invalid_argument(EWITHDRAW_ZERO_STAKE)); + // synchronize delegation and stake pools before any user operation + synchronize_delegation_pool(pool_address); + withdraw_internal(borrow_global_mut(pool_address), signer::address_of(delegator), amount); + } + + fun withdraw_internal( + pool: &mut DelegationPool, + delegator_address: address, + amount: u64 + ) acquires GovernanceRecords { + // TODO: recycle storage when a delegator fully exits the delegation pool. + // short-circuit if amount to withdraw is 0 so no event is emitted + if (amount == 0) { return }; + + let pool_address = get_pool_address(pool); + let (withdrawal_exists, withdrawal_olc) = pending_withdrawal_exists(pool, delegator_address); + // exit if no withdrawal or (it is pending and cannot withdraw pending_inactive stake from stake pool) + if (!( + withdrawal_exists && + (withdrawal_olc.index < pool.observed_lockup_cycle.index || can_withdraw_pending_inactive(pool_address)) + )) { return }; + + if (withdrawal_olc.index == pool.observed_lockup_cycle.index) { + amount = coins_to_redeem_to_ensure_min_stake( + pending_inactive_shares_pool(pool), + delegator_address, + amount, + ) + }; + amount = redeem_inactive_shares(pool, delegator_address, amount, withdrawal_olc); + + let stake_pool_owner = &retrieve_stake_pool_owner(pool); + // stake pool will inactivate entire pending_inactive stake at `stake::withdraw` to make it withdrawable + // however, bypassing the inactivation of excess stake (inactivated but not withdrawn) ensures + // the OLC is not advanced indefinitely on `unlock`-`withdraw` paired calls + if (can_withdraw_pending_inactive(pool_address)) { + // get excess stake before being entirely inactivated + let (_, _, _, pending_inactive) = stake::get_stake(pool_address); + if (withdrawal_olc.index == pool.observed_lockup_cycle.index) { + // `amount` less excess if withdrawing pending_inactive stake + pending_inactive = pending_inactive - amount + }; + // escape excess stake from inactivation + stake::reactivate_stake(stake_pool_owner, pending_inactive); + stake::withdraw(stake_pool_owner, amount); + // restore excess stake to the pending_inactive state + stake::unlock(stake_pool_owner, pending_inactive); + } else { + // no excess stake if `stake::withdraw` does not inactivate at all + stake::withdraw(stake_pool_owner, amount); + }; + aptos_account::transfer(stake_pool_owner, delegator_address, amount); + + // commit withdrawal of possibly inactive stake to the `total_coins_inactive` + // known by the delegation pool in order to not mistake it for slashing at next synchronization + let (_, inactive, _, _) = stake::get_stake(pool_address); + pool.total_coins_inactive = inactive; + + if (features::module_event_migration_enabled()) { + event::emit( + WithdrawStake { + pool_address, + delegator_address, + amount_withdrawn: amount, + }, + ); + }; + + event::emit_event( + &mut pool.withdraw_stake_events, + WithdrawStakeEvent { + pool_address, + delegator_address, + amount_withdrawn: amount, + }, + ); + } + + /// Return the unique observed lockup cycle where delegator `delegator_address` may have + /// unlocking (or already unlocked) stake to be withdrawn from delegation pool `pool`. + /// A bool is returned to signal if a pending withdrawal exists at all. + fun pending_withdrawal_exists(pool: &DelegationPool, delegator_address: address): (bool, ObservedLockupCycle) { + if (table::contains(&pool.pending_withdrawals, delegator_address)) { + (true, *table::borrow(&pool.pending_withdrawals, delegator_address)) + } else { + (false, olc_with_index(0)) + } + } + + /// Return a mutable reference to the shares pool of `pending_inactive` stake on the + /// delegation pool, always the last item in `inactive_shares`. + fun pending_inactive_shares_pool_mut(pool: &mut DelegationPool): &mut pool_u64::Pool { + let observed_lockup_cycle = pool.observed_lockup_cycle; + table::borrow_mut(&mut pool.inactive_shares, observed_lockup_cycle) + } + + fun pending_inactive_shares_pool(pool: &DelegationPool): &pool_u64::Pool { + table::borrow(&pool.inactive_shares, pool.observed_lockup_cycle) + } + + /// Execute the pending withdrawal of `delegator_address` on delegation pool `pool` + /// if existing and already inactive to allow the creation of a new one. + /// `pending_inactive` stake would be left untouched even if withdrawable and should + /// be explicitly withdrawn by delegator + fun execute_pending_withdrawal(pool: &mut DelegationPool, delegator_address: address) acquires GovernanceRecords { + let (withdrawal_exists, withdrawal_olc) = pending_withdrawal_exists(pool, delegator_address); + if (withdrawal_exists && withdrawal_olc.index < pool.observed_lockup_cycle.index) { + withdraw_internal(pool, delegator_address, MAX_U64); + } + } + + /// Buy shares into the active pool on behalf of delegator `shareholder` who + /// deposited `coins_amount`. This function doesn't make any coin transfer. + fun buy_in_active_shares( + pool: &mut DelegationPool, + shareholder: address, + coins_amount: u64, + ): u128 acquires GovernanceRecords { + let new_shares = pool_u64::amount_to_shares(&pool.active_shares, coins_amount); + // No need to buy 0 shares. + if (new_shares == 0) { return 0 }; + + // Always update governance records before any change to the shares pool. + let pool_address = get_pool_address(pool); + if (partial_governance_voting_enabled(pool_address)) { + update_governance_records_for_buy_in_active_shares(pool, pool_address, new_shares, shareholder); + }; + + pool_u64::buy_in(&mut pool.active_shares, shareholder, coins_amount); + new_shares + } + + /// Buy shares into the pending_inactive pool on behalf of delegator `shareholder` who + /// redeemed `coins_amount` from the active pool to schedule it for unlocking. + /// If delegator's pending withdrawal exists and has been inactivated, execute it firstly + /// to ensure there is always only one withdrawal request. + fun buy_in_pending_inactive_shares( + pool: &mut DelegationPool, + shareholder: address, + coins_amount: u64, + ): u128 acquires GovernanceRecords { + let new_shares = pool_u64::amount_to_shares(pending_inactive_shares_pool(pool), coins_amount); + // never create a new pending withdrawal unless delegator owns some pending_inactive shares + if (new_shares == 0) { return 0 }; + + // Always update governance records before any change to the shares pool. + let pool_address = get_pool_address(pool); + if (partial_governance_voting_enabled(pool_address)) { + update_governance_records_for_buy_in_pending_inactive_shares(pool, pool_address, new_shares, shareholder); + }; + + // cannot buy inactive shares, only pending_inactive at current lockup cycle + pool_u64::buy_in(pending_inactive_shares_pool_mut(pool), shareholder, coins_amount); + + // execute the pending withdrawal if exists and is inactive before creating a new one + execute_pending_withdrawal(pool, shareholder); + + // save observed lockup cycle for the new pending withdrawal + let observed_lockup_cycle = pool.observed_lockup_cycle; + assert!(*table::borrow_mut_with_default( + &mut pool.pending_withdrawals, + shareholder, + observed_lockup_cycle + ) == observed_lockup_cycle, + error::invalid_state(EPENDING_WITHDRAWAL_EXISTS) + ); + + new_shares + } + + /// Convert `coins_amount` of coins to be redeemed from shares pool `shares_pool` + /// to the exact number of shares to redeem in order to achieve this. + fun amount_to_shares_to_redeem( + shares_pool: &pool_u64::Pool, + shareholder: address, + coins_amount: u64, + ): u128 { + if (coins_amount >= pool_u64::balance(shares_pool, shareholder)) { + // cap result at total shares of shareholder to pass `EINSUFFICIENT_SHARES` on subsequent redeem + pool_u64::shares(shares_pool, shareholder) + } else { + pool_u64::amount_to_shares(shares_pool, coins_amount) + } + } + + /// Redeem shares from the active pool on behalf of delegator `shareholder` who + /// wants to unlock `coins_amount` of its active stake. + /// Extracted coins will be used to buy shares into the pending_inactive pool and + /// be available for withdrawal when current OLC ends. + fun redeem_active_shares( + pool: &mut DelegationPool, + shareholder: address, + coins_amount: u64, + ): u64 acquires GovernanceRecords { + let shares_to_redeem = amount_to_shares_to_redeem(&pool.active_shares, shareholder, coins_amount); + // silently exit if not a shareholder otherwise redeem would fail with `ESHAREHOLDER_NOT_FOUND` + if (shares_to_redeem == 0) return 0; + + // Always update governance records before any change to the shares pool. + let pool_address = get_pool_address(pool); + if (partial_governance_voting_enabled(pool_address)) { + update_governanace_records_for_redeem_active_shares(pool, pool_address, shares_to_redeem, shareholder); + }; + + pool_u64::redeem_shares(&mut pool.active_shares, shareholder, shares_to_redeem) + } + + /// Redeem shares from the inactive pool at `lockup_cycle` < current OLC on behalf of + /// delegator `shareholder` who wants to withdraw `coins_amount` of its unlocked stake. + /// Redeem shares from the pending_inactive pool at `lockup_cycle` == current OLC on behalf of + /// delegator `shareholder` who wants to reactivate `coins_amount` of its unlocking stake. + /// For latter case, extracted coins will be used to buy shares into the active pool and + /// escape inactivation when current lockup ends. + fun redeem_inactive_shares( + pool: &mut DelegationPool, + shareholder: address, + coins_amount: u64, + lockup_cycle: ObservedLockupCycle, + ): u64 acquires GovernanceRecords { + let shares_to_redeem = amount_to_shares_to_redeem( + table::borrow(&pool.inactive_shares, lockup_cycle), + shareholder, + coins_amount); + // silently exit if not a shareholder otherwise redeem would fail with `ESHAREHOLDER_NOT_FOUND` + if (shares_to_redeem == 0) return 0; + + // Always update governance records before any change to the shares pool. + let pool_address = get_pool_address(pool); + // Only redeem shares from the pending_inactive pool at `lockup_cycle` == current OLC. + if (partial_governance_voting_enabled(pool_address) && lockup_cycle.index == pool.observed_lockup_cycle.index) { + update_governanace_records_for_redeem_pending_inactive_shares( + pool, + pool_address, + shares_to_redeem, + shareholder + ); + }; + + let inactive_shares = table::borrow_mut(&mut pool.inactive_shares, lockup_cycle); + // 1. reaching here means delegator owns inactive/pending_inactive shares at OLC `lockup_cycle` + let redeemed_coins = pool_u64::redeem_shares(inactive_shares, shareholder, shares_to_redeem); + + // if entirely reactivated pending_inactive stake or withdrawn inactive one, + // re-enable unlocking for delegator by deleting this pending withdrawal + if (pool_u64::shares(inactive_shares, shareholder) == 0) { + // 2. a delegator owns inactive/pending_inactive shares only at the OLC of its pending withdrawal + // 1 & 2: the pending withdrawal itself has been emptied of shares and can be safely deleted + table::remove(&mut pool.pending_withdrawals, shareholder); + }; + // destroy inactive shares pool of past OLC if all its stake has been withdrawn + if (lockup_cycle.index < pool.observed_lockup_cycle.index && total_coins(inactive_shares) == 0) { + pool_u64::destroy_empty(table::remove(&mut pool.inactive_shares, lockup_cycle)); + }; + + redeemed_coins + } + + /// Calculate stake deviations between the delegation and stake pools in order to + /// capture the rewards earned in the meantime, resulted operator commission and + /// whether the lockup expired on the stake pool. + fun calculate_stake_pool_drift(pool: &DelegationPool): (bool, u64, u64, u64, u64) { + let (active, inactive, pending_active, pending_inactive) = stake::get_stake(get_pool_address(pool)); + assert!( + inactive >= pool.total_coins_inactive, + error::invalid_state(ESLASHED_INACTIVE_STAKE_ON_PAST_OLC) + ); + // determine whether a new lockup cycle has been ended on the stake pool and + // inactivated SOME `pending_inactive` stake which should stop earning rewards now, + // thus requiring separation of the `pending_inactive` stake on current observed lockup + // and the future one on the newly started lockup + let lockup_cycle_ended = inactive > pool.total_coins_inactive; + + // actual coins on stake pool belonging to the active shares pool + active = active + pending_active; + // actual coins on stake pool belonging to the shares pool hosting `pending_inactive` stake + // at current observed lockup cycle, either pending: `pending_inactive` or already inactivated: + if (lockup_cycle_ended) { + // `inactive` on stake pool = any previous `inactive` stake + + // any previous `pending_inactive` stake and its rewards (both inactivated) + pending_inactive = inactive - pool.total_coins_inactive + }; + + // on stake-management operations, total coins on the internal shares pools and individual + // stakes on the stake pool are updated simultaneously, thus the only stakes becoming + // unsynced are rewards and slashes routed exclusively to/out the stake pool + + // operator `active` rewards not persisted yet to the active shares pool + let pool_active = total_coins(&pool.active_shares); + let commission_active = if (active > pool_active) { + math64::mul_div(active - pool_active, pool.operator_commission_percentage, MAX_FEE) + } else { + // handle any slashing applied to `active` stake + 0 + }; + // operator `pending_inactive` rewards not persisted yet to the pending_inactive shares pool + let pool_pending_inactive = total_coins(pending_inactive_shares_pool(pool)); + let commission_pending_inactive = if (pending_inactive > pool_pending_inactive) { + math64::mul_div( + pending_inactive - pool_pending_inactive, + pool.operator_commission_percentage, + MAX_FEE + ) + } else { + // handle any slashing applied to `pending_inactive` stake + 0 + }; + + (lockup_cycle_ended, active, pending_inactive, commission_active, commission_pending_inactive) + } + + /// Synchronize delegation and stake pools: distribute yet-undetected rewards to the corresponding internal + /// shares pools, assign commission to operator and eventually prepare delegation pool for a new lockup cycle. + public entry fun synchronize_delegation_pool( + pool_address: address + ) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + assert_delegation_pool_exists(pool_address); + let pool = borrow_global_mut(pool_address); + let ( + lockup_cycle_ended, + active, + pending_inactive, + commission_active, + commission_pending_inactive + ) = calculate_stake_pool_drift(pool); + + // zero `pending_active` stake indicates that either there are no `add_stake` fees or + // previous epoch has ended and should release the shares owning the existing fees + let (_, _, pending_active, _) = stake::get_stake(pool_address); + if (pending_active == 0) { + // renounce ownership over the `add_stake` fees by redeeming all shares of + // the special shareholder, implicitly their equivalent coins, out of the active shares pool + redeem_active_shares(pool, NULL_SHAREHOLDER, MAX_U64); + }; + + // distribute rewards remaining after commission, to delegators (to already existing shares) + // before buying shares for the operator for its entire commission fee + // otherwise, operator's new shares would additionally appreciate from rewards it does not own + + // update total coins accumulated by `active` + `pending_active` shares + // redeemed `add_stake` fees are restored and distributed to the rest of the pool as rewards + pool_u64::update_total_coins(&mut pool.active_shares, active - commission_active); + // update total coins accumulated by `pending_inactive` shares at current observed lockup cycle + pool_u64::update_total_coins( + pending_inactive_shares_pool_mut(pool), + pending_inactive - commission_pending_inactive + ); + + // reward operator its commission out of uncommitted active rewards (`add_stake` fees already excluded) + buy_in_active_shares(pool, beneficiary_for_operator(stake::get_operator(pool_address)), commission_active); + // reward operator its commission out of uncommitted pending_inactive rewards + buy_in_pending_inactive_shares( + pool, + beneficiary_for_operator(stake::get_operator(pool_address)), + commission_pending_inactive + ); + + event::emit_event( + &mut pool.distribute_commission_events, + DistributeCommissionEvent { + pool_address, + operator: stake::get_operator(pool_address), + commission_active, + commission_pending_inactive, + }, + ); + + if (features::operator_beneficiary_change_enabled()) { + emit(DistributeCommission { + pool_address, + operator: stake::get_operator(pool_address), + beneficiary: beneficiary_for_operator(stake::get_operator(pool_address)), + commission_active, + commission_pending_inactive, + }) + }; + + // advance lockup cycle on delegation pool if already ended on stake pool (AND stake explicitly inactivated) + if (lockup_cycle_ended) { + // capture inactive coins over all ended lockup cycles (including this ending one) + let (_, inactive, _, _) = stake::get_stake(pool_address); + pool.total_coins_inactive = inactive; + + // advance lockup cycle on the delegation pool + pool.observed_lockup_cycle.index = pool.observed_lockup_cycle.index + 1; + // start new lockup cycle with a fresh shares pool for `pending_inactive` stake + table::add( + &mut pool.inactive_shares, + pool.observed_lockup_cycle, + pool_u64::create_with_scaling_factor(SHARES_SCALING_FACTOR) + ); + }; + + if (is_next_commission_percentage_effective(pool_address)) { + pool.operator_commission_percentage = borrow_global( + pool_address + ).commission_percentage_next_lockup_cycle; + } + } + + inline fun assert_and_update_proposal_used_voting_power( + governance_records: &mut GovernanceRecords, pool_address: address, proposal_id: u64, voting_power: u64 + ) { + let stake_pool_remaining_voting_power = aptos_governance::get_remaining_voting_power(pool_address, proposal_id); + let stake_pool_used_voting_power = aptos_governance::get_voting_power( + pool_address + ) - stake_pool_remaining_voting_power; + let proposal_used_voting_power = smart_table::borrow_mut_with_default( + &mut governance_records.votes_per_proposal, + proposal_id, + 0 + ); + // A edge case: Before enabling partial governance voting on a delegation pool, the delegation pool has + // a voter which can vote with all voting power of this delegation pool. If the voter votes on a proposal after + // partial governance voting flag is enabled, the delegation pool doesn't have enough voting power on this + // proposal for all the delegators. To be fair, no one can vote on this proposal through this delegation pool. + // To detect this case, check if the stake pool had used voting power not through delegation_pool module. + assert!( + stake_pool_used_voting_power == *proposal_used_voting_power, + error::invalid_argument(EALREADY_VOTED_BEFORE_ENABLE_PARTIAL_VOTING) + ); + *proposal_used_voting_power = *proposal_used_voting_power + voting_power; + } + + fun update_governance_records_for_buy_in_active_shares( + pool: &DelegationPool, pool_address: address, new_shares: u128, shareholder: address + ) acquires GovernanceRecords { + // of += ----> + // of += + // of += + let governance_records = borrow_global_mut(pool_address); + let vote_delegation = update_and_borrow_mut_delegator_vote_delegation(pool, governance_records, shareholder); + let current_voter = vote_delegation.voter; + let pending_voter = vote_delegation.pending_voter; + let current_delegated_votes = + update_and_borrow_mut_delegated_votes(pool, governance_records, current_voter); + current_delegated_votes.active_shares = current_delegated_votes.active_shares + new_shares; + if (pending_voter == current_voter) { + current_delegated_votes.active_shares_next_lockup = + current_delegated_votes.active_shares_next_lockup + new_shares; + } else { + let pending_delegated_votes = + update_and_borrow_mut_delegated_votes(pool, governance_records, pending_voter); + pending_delegated_votes.active_shares_next_lockup = + pending_delegated_votes.active_shares_next_lockup + new_shares; + }; + } + + fun update_governance_records_for_buy_in_pending_inactive_shares( + pool: &DelegationPool, pool_address: address, new_shares: u128, shareholder: address + ) acquires GovernanceRecords { + // of += ----> + // of += + // no impact on of + let governance_records = borrow_global_mut(pool_address); + let current_voter = calculate_and_update_delegator_voter_internal(pool, governance_records, shareholder); + let current_delegated_votes = update_and_borrow_mut_delegated_votes(pool, governance_records, current_voter); + current_delegated_votes.pending_inactive_shares = current_delegated_votes.pending_inactive_shares + new_shares; + } + + fun update_governanace_records_for_redeem_active_shares( + pool: &DelegationPool, pool_address: address, shares_to_redeem: u128, shareholder: address + ) acquires GovernanceRecords { + // of -= ----> + // of -= + // of -= + let governance_records = borrow_global_mut(pool_address); + let vote_delegation = update_and_borrow_mut_delegator_vote_delegation( + pool, + governance_records, + shareholder + ); + let current_voter = vote_delegation.voter; + let pending_voter = vote_delegation.pending_voter; + let current_delegated_votes = update_and_borrow_mut_delegated_votes(pool, governance_records, current_voter); + current_delegated_votes.active_shares = current_delegated_votes.active_shares - shares_to_redeem; + if (current_voter == pending_voter) { + current_delegated_votes.active_shares_next_lockup = + current_delegated_votes.active_shares_next_lockup - shares_to_redeem; + } else { + let pending_delegated_votes = + update_and_borrow_mut_delegated_votes(pool, governance_records, pending_voter); + pending_delegated_votes.active_shares_next_lockup = + pending_delegated_votes.active_shares_next_lockup - shares_to_redeem; + }; + } + + fun update_governanace_records_for_redeem_pending_inactive_shares( + pool: &DelegationPool, pool_address: address, shares_to_redeem: u128, shareholder: address + ) acquires GovernanceRecords { + // of -= ----> + // of -= + // no impact on of + let governance_records = borrow_global_mut(pool_address); + let current_voter = calculate_and_update_delegator_voter_internal(pool, governance_records, shareholder); + let current_delegated_votes = update_and_borrow_mut_delegated_votes(pool, governance_records, current_voter); + current_delegated_votes.pending_inactive_shares = current_delegated_votes.pending_inactive_shares - shares_to_redeem; + } + + #[deprecated] + /// Deprecated, prefer math64::mul_div + public fun multiply_then_divide(x: u64, y: u64, z: u64): u64 { + math64::mul_div(x, y, z) + } + + #[test_only] + use aptos_framework::reconfiguration; + #[test_only] + use aptos_std::fixed_point64; + #[test_only] + use aptos_framework::stake::fast_forward_to_unlock; + #[test_only] + use aptos_framework::timestamp::fast_forward_seconds; + + #[test_only] + const CONSENSUS_KEY_1: vector = x"8a54b92288d4ba5073d3a52e80cc00ae9fbbc1cc5b433b46089b7804c38a76f00fc64746c7685ee628fc2d0b929c2294"; + #[test_only] + const CONSENSUS_POP_1: vector = x"a9d6c1f1270f2d1454c89a83a4099f813a56dc7db55591d46aa4e6ccae7898b234029ba7052f18755e6fa5e6b73e235f14efc4e2eb402ca2b8f56bad69f965fc11b7b25eb1c95a06f83ddfd023eac4559b6582696cfea97b227f4ce5bdfdfed0"; + + #[test_only] + const EPOCH_DURATION: u64 = 60; + #[test_only] + const LOCKUP_CYCLE_SECONDS: u64 = 2592000; + + #[test_only] + const ONE_APT: u64 = 100000000; + + #[test_only] + const VALIDATOR_STATUS_PENDING_ACTIVE: u64 = 1; + #[test_only] + const VALIDATOR_STATUS_ACTIVE: u64 = 2; + #[test_only] + const VALIDATOR_STATUS_PENDING_INACTIVE: u64 = 3; + + #[test_only] + const DELEGATION_POOLS: u64 = 11; + + #[test_only] + const MODULE_EVENT: u64 = 26; + + #[test_only] + const OPERATOR_BENEFICIARY_CHANGE: u64 = 39; + + #[test_only] + const COMMISSION_CHANGE_DELEGATION_POOL: u64 = 42; + + #[test_only] + public fun end_aptos_epoch() { + stake::end_epoch(); // additionally forwards EPOCH_DURATION seconds + reconfiguration::reconfigure_for_test_custom(); + } + + #[test_only] + public fun initialize_for_test(aptos_framework: &signer) { + initialize_for_test_custom( + aptos_framework, + 100 * ONE_APT, + 10000000 * ONE_APT, + LOCKUP_CYCLE_SECONDS, + true, + 1, + 100, + 1000000 + ); + } + + #[test_only] + public fun initialize_for_test_no_reward(aptos_framework: &signer) { + initialize_for_test_custom( + aptos_framework, + 100 * ONE_APT, + 10000000 * ONE_APT, + LOCKUP_CYCLE_SECONDS, + true, + 0, + 100, + 1000000 + ); + } + + #[test_only] + public fun initialize_for_test_custom( + aptos_framework: &signer, + minimum_stake: u64, + maximum_stake: u64, + recurring_lockup_secs: u64, + allow_validator_set_change: bool, + rewards_rate_numerator: u64, + rewards_rate_denominator: u64, + voting_power_increase_limit: u64, + ) { + account::create_account_for_test(signer::address_of(aptos_framework)); + stake::initialize_for_test_custom( + aptos_framework, + minimum_stake, + maximum_stake, + recurring_lockup_secs, + allow_validator_set_change, + rewards_rate_numerator, + rewards_rate_denominator, + voting_power_increase_limit, + ); + reconfiguration::initialize_for_test(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[DELEGATION_POOLS, MODULE_EVENT, OPERATOR_BENEFICIARY_CHANGE, COMMISSION_CHANGE_DELEGATION_POOL], + vector[] + ); + } + + #[test_only] + public fun initialize_test_validator( + validator: &signer, + amount: u64, + should_join_validator_set: bool, + should_end_epoch: bool, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_test_validator_custom(validator, amount, should_join_validator_set, should_end_epoch, 0); + } + + #[test_only] + public fun initialize_test_validator_custom( + validator: &signer, + amount: u64, + should_join_validator_set: bool, + should_end_epoch: bool, + commission_percentage: u64, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + let validator_address = signer::address_of(validator); + if (!account::exists_at(validator_address)) { + account::create_account_for_test(validator_address); + }; + + initialize_delegation_pool(validator, commission_percentage, vector::empty()); + let pool_address = get_owned_pool_address(validator_address); + + stake::rotate_consensus_key(validator, pool_address, CONSENSUS_KEY_1, CONSENSUS_POP_1); + + if (amount > 0) { + stake::mint(validator, amount); + add_stake(validator, pool_address, amount); + }; + + if (should_join_validator_set) { + stake::join_validator_set(validator, pool_address); + }; + + if (should_end_epoch) { + end_aptos_epoch(); + }; + } + + #[test_only] + fun unlock_with_min_stake_disabled( + delegator: &signer, + pool_address: address, + amount: u64 + ) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + synchronize_delegation_pool(pool_address); + + let pool = borrow_global_mut(pool_address); + let delegator_address = signer::address_of(delegator); + + amount = redeem_active_shares(pool, delegator_address, amount); + stake::unlock(&retrieve_stake_pool_owner(pool), amount); + buy_in_pending_inactive_shares(pool, delegator_address, amount); + } + + #[test_only] + public fun enable_delegation_pool_allowlisting_feature(aptos_framework: &signer) { + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_delegation_pool_allowlisting_feature()], + vector[] + ); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x3000A, location = Self)] + public entry fun test_delegation_pools_disabled( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + initialize_for_test(aptos_framework); + features::change_feature_flags_for_testing(aptos_framework, vector[], vector[DELEGATION_POOLS]); + + initialize_delegation_pool(validator, 0, vector::empty()); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_set_operator_and_delegated_voter( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + initialize_for_test(aptos_framework); + + let validator_address = signer::address_of(validator); + initialize_delegation_pool(validator, 0, vector::empty()); + let pool_address = get_owned_pool_address(validator_address); + + assert!(stake::get_operator(pool_address) == @0x123, 1); + assert!(stake::get_delegated_voter(pool_address) == @0x123, 1); + + set_operator(validator, @0x111); + assert!(stake::get_operator(pool_address) == @0x111, 2); + + set_delegated_voter(validator, @0x112); + assert!(stake::get_delegated_voter(pool_address) == @0x112, 2); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x60001, location = Self)] + public entry fun test_cannot_set_operator( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + initialize_for_test(aptos_framework); + // account does not own any delegation pool + set_operator(validator, @0x111); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x60001, location = Self)] + public entry fun test_cannot_set_delegated_voter( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + initialize_for_test(aptos_framework); + // account does not own any delegation pool + set_delegated_voter(validator, @0x112); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x80002, location = Self)] + public entry fun test_already_owns_delegation_pool( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + initialize_for_test(aptos_framework); + initialize_delegation_pool(validator, 0, x"00"); + initialize_delegation_pool(validator, 0, x"01"); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x1000B, location = Self)] + public entry fun test_cannot_withdraw_zero_stake( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + initialize_for_test(aptos_framework); + initialize_delegation_pool(validator, 0, x"00"); + withdraw(validator, get_owned_pool_address(signer::address_of(validator)), 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_initialize_delegation_pool( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage { + initialize_for_test(aptos_framework); + + let validator_address = signer::address_of(validator); + initialize_delegation_pool(validator, 1234, vector::empty()); + + assert_owner_cap_exists(validator_address); + let pool_address = get_owned_pool_address(validator_address); + assert_delegation_pool_exists(pool_address); + + assert!(stake::stake_pool_exists(pool_address), 0); + assert!(stake::get_operator(pool_address) == validator_address, 0); + assert!(stake::get_delegated_voter(pool_address) == validator_address, 0); + + assert!(observed_lockup_cycle(pool_address) == 0, 0); + assert!(total_coins_inactive(pool_address) == 0, 0); + assert!(operator_commission_percentage(pool_address) == 1234, 0); + assert_inactive_shares_pool(pool_address, 0, true, 0); + stake::assert_stake_pool(pool_address, 0, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, delegator2 = @0x020)] + public entry fun test_add_stake_fee( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test_custom( + aptos_framework, + 100 * ONE_APT, + 10000000 * ONE_APT, + LOCKUP_CYCLE_SECONDS, + true, + 1, + 100, + 1000000 + ); + + let validator_address = signer::address_of(validator); + account::create_account_for_test(validator_address); + + // create delegation pool with 37.35% operator commission + initialize_delegation_pool(validator, 3735, vector::empty()); + let pool_address = get_owned_pool_address(validator_address); + + stake::rotate_consensus_key(validator, pool_address, CONSENSUS_KEY_1, CONSENSUS_POP_1); + + // zero `add_stake` fee as validator is not producing rewards this epoch + assert!(get_add_stake_fee(pool_address, 1000000 * ONE_APT) == 0, 0); + + // add 1M APT, join the validator set and activate this stake + stake::mint(validator, 1000000 * ONE_APT); + add_stake(validator, pool_address, 1000000 * ONE_APT); + + stake::join_validator_set(validator, pool_address); + end_aptos_epoch(); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + + // `add_stake` fee for 100000 coins: 100000 * 0.006265 / (1 + 0.006265) + assert!(get_add_stake_fee(pool_address, 100000 * ONE_APT) == 62259941466, 0); + + // add pending_active stake from multiple delegators + stake::mint(delegator1, 100000 * ONE_APT); + add_stake(delegator1, pool_address, 100000 * ONE_APT); + stake::mint(delegator2, 10000 * ONE_APT); + add_stake(delegator2, pool_address, 10000 * ONE_APT); + + end_aptos_epoch(); + // delegators should own the same amount as initially deposited + assert_delegation(delegator1_address, pool_address, 10000000000000, 0, 0); + assert_delegation(delegator2_address, pool_address, 1000000000000, 0, 0); + + // add more stake from delegator 1 + stake::mint(delegator1, 10000 * ONE_APT); + let (delegator1_active, _, _) = get_stake(pool_address, delegator1_address); + add_stake(delegator1, pool_address, 10000 * ONE_APT); + + let fee = get_add_stake_fee(pool_address, 10000 * ONE_APT); + assert_delegation(delegator1_address, pool_address, delegator1_active + 10000 * ONE_APT - fee, 0, 0); + + // delegator 2 should not benefit in any way from this new stake + assert_delegation(delegator2_address, pool_address, 1000000000000, 0, 0); + + // add more stake from delegator 2 + stake::mint(delegator2, 100000 * ONE_APT); + add_stake(delegator2, pool_address, 100000 * ONE_APT); + + end_aptos_epoch(); + // delegators should own the same amount as initially deposited + any rewards produced + // 10000000000000 * 1% * (100 - 37.35)% + assert_delegation(delegator1_address, pool_address, 11062650000001, 0, 0); + // 1000000000000 * 1% * (100 - 37.35)% + assert_delegation(delegator2_address, pool_address, 11006265000001, 0, 0); + + // in-flight operator commission rewards do not automatically restake/compound + synchronize_delegation_pool(pool_address); + + // stakes should remain the same - `Self::get_stake` correctly calculates them + assert_delegation(delegator1_address, pool_address, 11062650000001, 0, 0); + assert_delegation(delegator2_address, pool_address, 11006265000001, 0, 0); + + end_aptos_epoch(); + // delegators should own previous stake * 1.006265 + assert_delegation(delegator1_address, pool_address, 11131957502251, 0, 0); + assert_delegation(delegator2_address, pool_address, 11075219250226, 0, 0); + + // add more stake from delegator 1 + stake::mint(delegator1, 20000 * ONE_APT); + (delegator1_active, _, _) = get_stake(pool_address, delegator1_address); + add_stake(delegator1, pool_address, 20000 * ONE_APT); + + fee = get_add_stake_fee(pool_address, 20000 * ONE_APT); + assert_delegation(delegator1_address, pool_address, delegator1_active + 20000 * ONE_APT - fee, 0, 0); + + // delegator 1 unlocks his entire newly added stake + unlock(delegator1, pool_address, 20000 * ONE_APT - fee); + end_aptos_epoch(); + // delegator 1 should own previous 11131957502250 active * 1.006265 and 20000 coins pending_inactive + assert_delegation(delegator1_address, pool_address, 11201699216002, 0, 2000000000000); + + // stakes should remain the same - `Self::get_stake` correctly calculates them + synchronize_delegation_pool(pool_address); + assert_delegation(delegator1_address, pool_address, 11201699216002, 0, 2000000000000); + + let reward_period_start_time_in_sec = timestamp::now_seconds(); + // Enable rewards rate decrease. Initially rewards rate is still 1% every epoch. Rewards rate halves every year. + let one_year_in_secs: u64 = 31536000; + staking_config::initialize_rewards( + aptos_framework, + fixed_point64::create_from_rational(2, 100), + fixed_point64::create_from_rational(6, 1000), + one_year_in_secs, + reward_period_start_time_in_sec, + fixed_point64::create_from_rational(50, 100), + ); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_periodical_reward_rate_decrease_feature()], + vector[] + ); + + // add more stake from delegator 1 + stake::mint(delegator1, 20000 * ONE_APT); + let delegator1_pending_inactive: u64; + (delegator1_active, _, delegator1_pending_inactive) = get_stake(pool_address, delegator1_address); + fee = get_add_stake_fee(pool_address, 20000 * ONE_APT); + add_stake(delegator1, pool_address, 20000 * ONE_APT); + + assert_delegation( + delegator1_address, + pool_address, + delegator1_active + 20000 * ONE_APT - fee, + 0, + delegator1_pending_inactive + ); + + // delegator 1 unlocks his entire newly added stake + unlock(delegator1, pool_address, 20000 * ONE_APT - fee); + end_aptos_epoch(); + // delegator 1 should own previous 11201699216002 active * ~1.01253 and 20000 * ~1.01253 + 20000 coins pending_inactive + assert_delegation(delegator1_address, pool_address, 11342056366822, 0, 4025059974939); + + // stakes should remain the same - `Self::get_stake` correctly calculates them + synchronize_delegation_pool(pool_address); + assert_delegation(delegator1_address, pool_address, 11342056366822, 0, 4025059974939); + + fast_forward_seconds(one_year_in_secs); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator = @0x010)] + public entry fun test_never_create_pending_withdrawal_if_no_shares_bought( + aptos_framework: &signer, + validator: &signer, + delegator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1000 * ONE_APT, true, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + // add stake without fees as validator is not active yet + stake::mint(delegator, 10 * ONE_APT); + add_stake(delegator, pool_address, 10 * ONE_APT); + end_aptos_epoch(); + + unlock(validator, pool_address, 100 * ONE_APT); + + stake::assert_stake_pool(pool_address, 91000000000, 0, 0, 10000000000); + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 91910000000, 0, 0, 10100000000); + + unlock_with_min_stake_disabled(delegator, pool_address, 1); + // request 1 coins * 910 / 919.1 = 0.99 shares to redeem * 1.01 price -> 0 coins out + // 1 coins lost at redeem due to 0.99 shares being burned + assert_delegation(delegator_address, pool_address, 1009999999, 0, 0); + assert_pending_withdrawal(delegator_address, pool_address, false, 0, false, 0); + + unlock_with_min_stake_disabled(delegator, pool_address, 2); + // request 2 coins * 909.99 / 919.1 = 1.98 shares to redeem * 1.01 price -> 1 coins out + // with 1 coins buy 1 * 100 / 101 = 0.99 shares in pending_inactive pool * 1.01 -> 0 coins in + // 1 coins lost at redeem due to 1.98 - 1.01 shares being burned + 1 coins extracted + synchronize_delegation_pool(pool_address); + assert_delegation(delegator_address, pool_address, 1009999997, 0, 0); + // the pending withdrawal has been created as > 0 pending_inactive shares have been bought + assert_pending_withdrawal(delegator_address, pool_address, true, 0, false, 0); + + // successfully delete the pending withdrawal (redeem all owned shares even worth 0 coins) + reactivate_stake(delegator, pool_address, 1); + assert_delegation(delegator_address, pool_address, 1009999997, 0, 0); + assert_pending_withdrawal(delegator_address, pool_address, false, 0, false, 0); + + // unlock min coins to own some pending_inactive balance (have to disable min-balance checks) + unlock_with_min_stake_disabled(delegator, pool_address, 3); + // request 3 coins * 909.99 / 919.09 = 2.97 shares to redeem * 1.01 price -> 2 coins out + // with 2 coins buy 2 * 100 / 101 = 1.98 shares in pending_inactive pool * 1.01 -> 1 coins in + // 1 coins lost at redeem due to 2.97 - 2 * 1.01 shares being burned + 2 coins extracted + synchronize_delegation_pool(pool_address); + assert_delegation(delegator_address, pool_address, 1009999994, 0, 1); + // the pending withdrawal has been created as > 0 pending_inactive shares have been bought + assert_pending_withdrawal(delegator_address, pool_address, true, 0, false, 1); + + reactivate_stake(delegator, pool_address, 1); + // redeem 1 coins >= delegator balance -> all shares are redeemed and pending withdrawal is deleted + assert_delegation(delegator_address, pool_address, 1009999995, 0, 0); + // the pending withdrawal has been deleted as delegator has 0 pending_inactive shares now + assert_pending_withdrawal(delegator_address, pool_address, false, 0, false, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x10008, location = Self)] + public entry fun test_add_stake_min_amount( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, MIN_COINS_ON_SHARES_POOL - 1, false, false); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_add_stake_single( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1000 * ONE_APT, false, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + // validator is inactive => added stake is `active` by default + stake::assert_stake_pool(pool_address, 1000 * ONE_APT, 0, 0, 0); + assert_delegation(validator_address, pool_address, 1000 * ONE_APT, 0, 0); + + // zero `add_stake` fee as validator is not producing rewards this epoch + assert!(get_add_stake_fee(pool_address, 250 * ONE_APT) == 0, 0); + + // check `add_stake` increases `active` stakes of delegator and stake pool + stake::mint(validator, 300 * ONE_APT); + let balance = coin::balance(validator_address); + add_stake(validator, pool_address, 250 * ONE_APT); + + // check added stake have been transferred out of delegator account + assert!(coin::balance(validator_address) == balance - 250 * ONE_APT, 0); + // zero `add_stake` fee charged from added stake + assert_delegation(validator_address, pool_address, 1250 * ONE_APT, 0, 0); + // zero `add_stake` fee transferred to null shareholder + assert_delegation(NULL_SHAREHOLDER, pool_address, 0, 0, 0); + // added stake is automatically `active` on inactive validator + stake::assert_stake_pool(pool_address, 1250 * ONE_APT, 0, 0, 0); + + // activate validator + stake::join_validator_set(validator, pool_address); + end_aptos_epoch(); + + // add 250 coins being pending_active until next epoch + stake::mint(validator, 250 * ONE_APT); + add_stake(validator, pool_address, 250 * ONE_APT); + + let fee1 = get_add_stake_fee(pool_address, 250 * ONE_APT); + assert_delegation(validator_address, pool_address, 1500 * ONE_APT - fee1, 0, 0); + // check `add_stake` fee has been transferred to the null shareholder + assert_delegation(NULL_SHAREHOLDER, pool_address, fee1, 0, 0); + stake::assert_stake_pool(pool_address, 1250 * ONE_APT, 0, 250 * ONE_APT, 0); + + // add 100 additional coins being pending_active until next epoch + stake::mint(validator, 100 * ONE_APT); + add_stake(validator, pool_address, 100 * ONE_APT); + + let fee2 = get_add_stake_fee(pool_address, 100 * ONE_APT); + assert_delegation(validator_address, pool_address, 1600 * ONE_APT - fee1 - fee2, 0, 0); + // check `add_stake` fee has been transferred to the null shareholder + assert_delegation(NULL_SHAREHOLDER, pool_address, fee1 + fee2, 0, 0); + stake::assert_stake_pool(pool_address, 1250 * ONE_APT, 0, 350 * ONE_APT, 0); + + end_aptos_epoch(); + // delegator got its `add_stake` fees back + 1250 * 1% * (100% - 0%) active rewards + assert_delegation(validator_address, pool_address, 161250000000, 0, 0); + stake::assert_stake_pool(pool_address, 161250000000, 0, 0, 0); + + // check that shares of null shareholder have been released + assert_delegation(NULL_SHAREHOLDER, pool_address, 0, 0, 0); + synchronize_delegation_pool(pool_address); + assert!(pool_u64::shares(&borrow_global(pool_address).active_shares, NULL_SHAREHOLDER) == 0, 0); + assert_delegation(NULL_SHAREHOLDER, pool_address, 0, 0, 0); + + // add 200 coins being pending_active until next epoch + stake::mint(validator, 200 * ONE_APT); + add_stake(validator, pool_address, 200 * ONE_APT); + + fee1 = get_add_stake_fee(pool_address, 200 * ONE_APT); + assert_delegation(validator_address, pool_address, 181250000000 - fee1, 0, 0); + // check `add_stake` fee has been transferred to the null shareholder + assert_delegation(NULL_SHAREHOLDER, pool_address, fee1 - 1, 0, 0); + stake::assert_stake_pool(pool_address, 161250000000, 0, 20000000000, 0); + + end_aptos_epoch(); + // delegator got its `add_stake` fee back + 161250000000 * 1% active rewards + assert_delegation(validator_address, pool_address, 182862500000, 0, 0); + stake::assert_stake_pool(pool_address, 182862500000, 0, 0, 0); + + // check that shares of null shareholder have been released + assert_delegation(NULL_SHAREHOLDER, pool_address, 0, 0, 0); + synchronize_delegation_pool(pool_address); + assert!(pool_u64::shares(&borrow_global(pool_address).active_shares, NULL_SHAREHOLDER) == 0, 0); + assert_delegation(NULL_SHAREHOLDER, pool_address, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator = @0x010)] + public entry fun test_add_stake_many( + aptos_framework: &signer, + validator: &signer, + delegator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1000 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + stake::assert_stake_pool(pool_address, 1000 * ONE_APT, 0, 0, 0); + assert_delegation(validator_address, pool_address, 1000 * ONE_APT, 0, 0); + + // add 250 coins from second account + stake::mint(delegator, 250 * ONE_APT); + add_stake(delegator, pool_address, 250 * ONE_APT); + + let fee1 = get_add_stake_fee(pool_address, 250 * ONE_APT); + assert_delegation(delegator_address, pool_address, 250 * ONE_APT - fee1, 0, 0); + assert_delegation(validator_address, pool_address, 1000 * ONE_APT, 0, 0); + stake::assert_stake_pool(pool_address, 1000 * ONE_APT, 0, 250 * ONE_APT, 0); + + end_aptos_epoch(); + // 1000 * 1.01 active stake + 250 pending_active stake + stake::assert_stake_pool(pool_address, 1260 * ONE_APT, 0, 0, 0); + // delegator got its `add_stake` fee back + assert_delegation(delegator_address, pool_address, 250 * ONE_APT, 0, 0); + // actual active rewards have been distributed to their earner(s) + assert_delegation(validator_address, pool_address, 100999999999, 0, 0); + + // add another 250 coins from first account + stake::mint(validator, 250 * ONE_APT); + add_stake(validator, pool_address, 250 * ONE_APT); + + fee1 = get_add_stake_fee(pool_address, 250 * ONE_APT); + assert_delegation(validator_address, pool_address, 125999999999 - fee1, 0, 0); + assert_delegation(delegator_address, pool_address, 250 * ONE_APT, 0, 0); + stake::assert_stake_pool(pool_address, 1260 * ONE_APT, 0, 250 * ONE_APT, 0); + + // add another 100 coins from second account + stake::mint(delegator, 100 * ONE_APT); + add_stake(delegator, pool_address, 100 * ONE_APT); + + let fee2 = get_add_stake_fee(pool_address, 100 * ONE_APT); + assert_delegation(delegator_address, pool_address, 350 * ONE_APT - fee2, 0, 0); + assert_delegation(validator_address, pool_address, 125999999999 - fee1, 0, 0); + stake::assert_stake_pool(pool_address, 1260 * ONE_APT, 0, 350 * ONE_APT, 0); + + end_aptos_epoch(); + // both delegators got their `add_stake` fees back + // 250 * 1.01 active stake + 100 pending_active stake + assert_delegation(delegator_address, pool_address, 35250000001, 0, 0); + // 1010 * 1.01 active stake + 250 pending_active stake + assert_delegation(validator_address, pool_address, 127009999998, 0, 0); + stake::assert_stake_pool(pool_address, 162260000000, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator = @0x010)] + public entry fun test_unlock_single( + aptos_framework: &signer, + validator: &signer, + delegator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 100 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + // add 200 coins pending_active until next epoch + stake::mint(validator, 200 * ONE_APT); + add_stake(validator, pool_address, 200 * ONE_APT); + + let fee = get_add_stake_fee(pool_address, 200 * ONE_APT); + assert_delegation(validator_address, pool_address, 300 * ONE_APT - fee, 0, 0); + stake::assert_stake_pool(pool_address, 100 * ONE_APT, 0, 200 * ONE_APT, 0); + + // cannot unlock pending_active stake (only 100/300 stake can be displaced) + unlock(validator, pool_address, 100 * ONE_APT); + assert_delegation(validator_address, pool_address, 200 * ONE_APT - fee, 0, 100 * ONE_APT); + assert_pending_withdrawal(validator_address, pool_address, true, 0, false, 100 * ONE_APT); + stake::assert_stake_pool(pool_address, 0, 0, 200 * ONE_APT, 100 * ONE_APT); + assert_inactive_shares_pool(pool_address, 0, true, 100 * ONE_APT); + + // reactivate entire pending_inactive stake progressively + reactivate_stake(validator, pool_address, 50 * ONE_APT); + + assert_delegation(validator_address, pool_address, 250 * ONE_APT - fee, 0, 50 * ONE_APT); + assert_pending_withdrawal(validator_address, pool_address, true, 0, false, 50 * ONE_APT); + stake::assert_stake_pool(pool_address, 50 * ONE_APT, 0, 200 * ONE_APT, 50 * ONE_APT); + + reactivate_stake(validator, pool_address, 50 * ONE_APT); + + assert_delegation(validator_address, pool_address, 300 * ONE_APT - fee, 0, 0); + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + stake::assert_stake_pool(pool_address, 100 * ONE_APT, 0, 200 * ONE_APT, 0); + // pending_inactive shares pool has not been deleted (as can still `unlock` this OLC) + assert_inactive_shares_pool(pool_address, 0, true, 0); + + end_aptos_epoch(); + // 10000000000 * 1.01 active stake + 20000000000 pending_active stake + assert_delegation(validator_address, pool_address, 301 * ONE_APT, 0, 0); + stake::assert_stake_pool(pool_address, 301 * ONE_APT, 0, 0, 0); + + // can unlock more than at previous epoch as the pending_active stake became active + unlock(validator, pool_address, 150 * ONE_APT); + assert_delegation(validator_address, pool_address, 15100000001, 0, 14999999999); + stake::assert_stake_pool(pool_address, 15100000001, 0, 0, 14999999999); + assert_pending_withdrawal(validator_address, pool_address, true, 0, false, 14999999999); + + assert!(stake::get_remaining_lockup_secs(pool_address) == LOCKUP_CYCLE_SECONDS - EPOCH_DURATION, 0); + end_aptos_epoch(); // additionally forwards EPOCH_DURATION seconds + + // pending_inactive stake should have not been inactivated + // 15100000001 * 1.01 active stake + 14999999999 pending_inactive * 1.01 stake + assert_delegation(validator_address, pool_address, 15251000001, 0, 15149999998); + assert_pending_withdrawal(validator_address, pool_address, true, 0, false, 15149999998); + stake::assert_stake_pool(pool_address, 15251000001, 0, 0, 15149999998); + + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS - 3 * EPOCH_DURATION); + end_aptos_epoch(); // additionally forwards EPOCH_DURATION seconds and expires lockup cycle + + // 15251000001 * 1.01 active stake + 15149999998 * 1.01 pending_inactive(now inactive) stake + assert_delegation(validator_address, pool_address, 15403510001, 15301499997, 0); + assert_pending_withdrawal(validator_address, pool_address, true, 0, true, 15301499997); + stake::assert_stake_pool(pool_address, 15403510001, 15301499997, 0, 0); + + // add 50 coins from another account + stake::mint(delegator, 50 * ONE_APT); + add_stake(delegator, pool_address, 50 * ONE_APT); + + // observed lockup cycle should have advanced at `add_stake`(on synchronization) + assert!(observed_lockup_cycle(pool_address) == 1, 0); + + fee = get_add_stake_fee(pool_address, 50 * ONE_APT); + assert_delegation(delegator_address, pool_address, 4999999999 - fee, 0, 0); + assert_delegation(validator_address, pool_address, 15403510001, 15301499997, 0); + stake::assert_stake_pool(pool_address, 15403510001, 15301499997, 50 * ONE_APT, 0); + + // cannot withdraw stake unlocked by others + withdraw(delegator, pool_address, 50 * ONE_APT); + assert!(coin::balance(delegator_address) == 0, 0); + + // withdraw own unlocked stake + withdraw(validator, pool_address, 15301499997); + assert!(coin::balance(validator_address) == 15301499997, 0); + assert_delegation(validator_address, pool_address, 15403510001, 0, 0); + // pending withdrawal has been executed and deleted + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + // inactive shares pool on OLC 0 has been deleted because its stake has been withdrawn + assert_inactive_shares_pool(pool_address, 0, false, 0); + + // new pending withdrawal can be created on lockup cycle 1 + unlock(validator, pool_address, 5403510001); + assert_delegation(validator_address, pool_address, 10000000000, 0, 5403510000); + assert_pending_withdrawal(validator_address, pool_address, true, 1, false, 5403510000); + + // end lockup cycle 1 + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + // 10000000000 * 1.01 active stake + 5403510000 * 1.01 pending_inactive(now inactive) stake + assert_delegation(validator_address, pool_address, 10100000000, 5457545100, 0); + assert_pending_withdrawal(validator_address, pool_address, true, 1, true, 5457545100); + + // unlock when the pending withdrawal exists and gets automatically executed + let balance = coin::balance(validator_address); + unlock(validator, pool_address, 10100000000); + assert!(coin::balance(validator_address) == balance + 5457545100, 0); + assert_delegation(validator_address, pool_address, 0, 0, 10100000000); + // this is the new pending withdrawal replacing the executed one + assert_pending_withdrawal(validator_address, pool_address, true, 2, false, 10100000000); + + // create dummy validator to ensure the existing validator can leave the set + initialize_test_validator(delegator, 100 * ONE_APT, true, true); + // inactivate validator + stake::leave_validator_set(validator, pool_address); + end_aptos_epoch(); + + // expire lockup cycle on the stake pool + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + let observed_lockup_cycle = observed_lockup_cycle(pool_address); + end_aptos_epoch(); + + // observed lockup cycle should be unchanged as no stake has been inactivated + synchronize_delegation_pool(pool_address); + assert!(observed_lockup_cycle(pool_address) == observed_lockup_cycle, 0); + + // stake is pending_inactive as it has not been inactivated + stake::assert_stake_pool(pool_address, 5100500001, 0, 0, 10303010000); + // 10100000000 * 1.01 * 1.01 pending_inactive stake + assert_delegation(validator_address, pool_address, 0, 0, 10303010000); + // the pending withdrawal should be reported as still pending + assert_pending_withdrawal(validator_address, pool_address, true, 2, false, 10303010000); + + // validator is inactive and lockup expired => pending_inactive stake is withdrawable + balance = coin::balance(validator_address); + withdraw(validator, pool_address, 10303010000); + + assert!(coin::balance(validator_address) == balance + 10303010000, 0); + assert_delegation(validator_address, pool_address, 0, 0, 0); + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + stake::assert_stake_pool(pool_address, 5100500001, 0, 0, 0); + // pending_inactive shares pool has not been deleted (as can still `unlock` this OLC) + assert_inactive_shares_pool(pool_address, observed_lockup_cycle(pool_address), true, 0); + + stake::mint(validator, 30 * ONE_APT); + add_stake(validator, pool_address, 30 * ONE_APT); + unlock(validator, pool_address, 10 * ONE_APT); + + assert_delegation(validator_address, pool_address, 1999999999, 0, 1000000000); + // the pending withdrawal should be reported as still pending + assert_pending_withdrawal(validator_address, pool_address, true, 2, false, 1000000000); + + balance = coin::balance(validator_address); + // pending_inactive balance would be under threshold => redeem entire balance + withdraw(validator, pool_address, 1); + // pending_inactive balance has been withdrawn and the pending withdrawal executed + assert_delegation(validator_address, pool_address, 1999999999, 0, 0); + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + assert!(coin::balance(validator_address) == balance + 1000000000, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, delegator2 = @0x020)] + public entry fun test_total_coins_inactive( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 200 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + + stake::mint(delegator1, 100 * ONE_APT); + stake::mint(delegator2, 200 * ONE_APT); + add_stake(delegator1, pool_address, 100 * ONE_APT); + add_stake(delegator2, pool_address, 200 * ONE_APT); + end_aptos_epoch(); + + assert_delegation(delegator1_address, pool_address, 100 * ONE_APT, 0, 0); + assert_delegation(delegator2_address, pool_address, 200 * ONE_APT, 0, 0); + + // unlock some stake from delegator 1 + unlock(delegator1, pool_address, 50 * ONE_APT); + assert_delegation(delegator1_address, pool_address, 5000000000, 0, 4999999999); + + // move to lockup cycle 1 + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + // delegator 1 pending_inactive stake has been inactivated + assert_delegation(delegator1_address, pool_address, 5050000000, 5049999998, 0); + assert_delegation(delegator2_address, pool_address, 202 * ONE_APT, 0, 0); + + synchronize_delegation_pool(pool_address); + assert!(total_coins_inactive(pool_address) == 5049999998, 0); + + // unlock some stake from delegator 2 + unlock(delegator2, pool_address, 50 * ONE_APT); + assert_delegation(delegator2_address, pool_address, 15200000001, 0, 4999999999); + + // withdraw some of inactive stake of delegator 1 + withdraw(delegator1, pool_address, 2049999998); + assert_delegation(delegator1_address, pool_address, 5050000000, 3000000001, 0); + assert!(total_coins_inactive(pool_address) == 3000000001, 0); + + // move to lockup cycle 2 + let (_, inactive, _, pending_inactive) = stake::get_stake(pool_address); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + // delegator 2 pending_inactive stake has been inactivated + assert_delegation(delegator1_address, pool_address, 5100500000, 3000000001, 0); + assert_delegation(delegator2_address, pool_address, 15352000001, 5049999998, 0); + + // total_coins_inactive remains unchanged in the absence of user operations + assert!(total_coins_inactive(pool_address) == inactive, 0); + synchronize_delegation_pool(pool_address); + // total_coins_inactive == previous inactive stake + previous pending_inactive stake and its rewards + assert!(total_coins_inactive(pool_address) == inactive + pending_inactive + pending_inactive / 100, 0); + + // withdraw some of inactive stake of delegator 2 + let total_coins_inactive = total_coins_inactive(pool_address); + withdraw(delegator2, pool_address, 3049999998); + assert!(total_coins_inactive(pool_address) == total_coins_inactive - 3049999997, 0); + + // unlock some stake from delegator `validator` + unlock(validator, pool_address, 50 * ONE_APT); + + // create dummy validator to ensure the existing validator can leave the set + initialize_test_validator(delegator1, 100 * ONE_APT, true, true); + // inactivate validator + stake::leave_validator_set(validator, pool_address); + end_aptos_epoch(); + + // move to lockup cycle 3 + (_, inactive, _, pending_inactive) = stake::get_stake(pool_address); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + // pending_inactive stake has not been inactivated as validator is inactive + let (_, inactive_now, _, pending_inactive_now) = stake::get_stake(pool_address); + assert!(inactive_now == inactive, inactive_now); + assert!(pending_inactive_now == pending_inactive, pending_inactive_now); + + // total_coins_inactive remains unchanged in the absence of a new OLC + synchronize_delegation_pool(pool_address); + assert!(total_coins_inactive(pool_address) == inactive, 0); + + // withdraw entire pending_inactive stake + withdraw(validator, pool_address, MAX_U64); + assert!(total_coins_inactive(pool_address) == inactive, 0); + (_, _, _, pending_inactive) = stake::get_stake(pool_address); + assert!(pending_inactive == 0, pending_inactive); + + // withdraw entire inactive stake + withdraw(delegator1, pool_address, MAX_U64); + withdraw(delegator2, pool_address, MAX_U64); + assert!(total_coins_inactive(pool_address) == 0, 0); + (_, inactive, _, _) = stake::get_stake(pool_address); + assert!(inactive == 0, inactive); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_reactivate_stake_single( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 200 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + // unlock some stake from the active one + unlock(validator, pool_address, 100 * ONE_APT); + assert_delegation(validator_address, pool_address, 100 * ONE_APT, 0, 100 * ONE_APT); + stake::assert_stake_pool(pool_address, 100 * ONE_APT, 0, 0, 100 * ONE_APT); + assert_pending_withdrawal(validator_address, pool_address, true, 0, false, 100 * ONE_APT); + + // add some stake to pending_active state + stake::mint(validator, 150 * ONE_APT); + add_stake(validator, pool_address, 150 * ONE_APT); + + let fee = get_add_stake_fee(pool_address, 150 * ONE_APT); + assert_delegation(validator_address, pool_address, 250 * ONE_APT - fee, 0, 100 * ONE_APT); + stake::assert_stake_pool(pool_address, 100 * ONE_APT, 0, 150 * ONE_APT, 100 * ONE_APT); + + // can reactivate only pending_inactive stake + reactivate_stake(validator, pool_address, 150 * ONE_APT); + + assert_delegation(validator_address, pool_address, 350 * ONE_APT - fee, 0, 0); + stake::assert_stake_pool(pool_address, 200 * ONE_APT, 0, 150 * ONE_APT, 0); + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + + end_aptos_epoch(); + // 20000000000 active stake * 1.01 + 15000000000 pending_active stake + assert_delegation(validator_address, pool_address, 35200000000, 0, 0); + + // unlock stake added at previous epoch (expect some imprecision when moving shares) + unlock(validator, pool_address, 150 * ONE_APT); + assert_delegation(validator_address, pool_address, 20200000001, 0, 14999999999); + stake::assert_stake_pool(pool_address, 20200000001, 0, 0, 14999999999); + + // inactivate pending_inactive stake + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + // 20200000001 active stake * 1.01 + 14999999999 pending_inactive stake * 1.01 + assert_delegation(validator_address, pool_address, 20402000001, 15149999998, 0); + assert_pending_withdrawal(validator_address, pool_address, true, 0, true, 15149999998); + + // cannot reactivate inactive stake + reactivate_stake(validator, pool_address, 15149999998); + assert_delegation(validator_address, pool_address, 20402000001, 15149999998, 0); + + // unlock stake in the new lockup cycle (the pending withdrawal is executed) + unlock(validator, pool_address, 100 * ONE_APT); + assert!(coin::balance(validator_address) == 15149999998, 0); + assert_delegation(validator_address, pool_address, 10402000002, 0, 9999999999); + assert_pending_withdrawal(validator_address, pool_address, true, 1, false, 9999999999); + + // reactivate the new pending withdrawal almost entirely + reactivate_stake(validator, pool_address, 8999999999); + assert_pending_withdrawal(validator_address, pool_address, true, 1, false, 1000000000); + // reactivate remaining stake of the new pending withdrawal + reactivate_stake(validator, pool_address, 1000000000); + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator = @0x010)] + public entry fun test_withdraw_many( + aptos_framework: &signer, + validator: &signer, + delegator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1000 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + stake::mint(delegator, 200 * ONE_APT); + add_stake(delegator, pool_address, 200 * ONE_APT); + + unlock(validator, pool_address, 100 * ONE_APT); + assert_pending_withdrawal(validator_address, pool_address, true, 0, false, 100 * ONE_APT); + + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + assert_delegation(delegator_address, pool_address, 200 * ONE_APT, 0, 0); + assert_delegation(validator_address, pool_address, 90899999999, 10100000000, 0); + assert_pending_withdrawal(validator_address, pool_address, true, 0, true, 10100000000); + assert_inactive_shares_pool(pool_address, 0, true, 100 * ONE_APT); + + // check cannot withdraw inactive stake unlocked by others + withdraw(delegator, pool_address, MAX_U64); + assert_delegation(delegator_address, pool_address, 200 * ONE_APT, 0, 0); + assert_delegation(validator_address, pool_address, 90899999999, 10100000000, 0); + + unlock(delegator, pool_address, 100 * ONE_APT); + assert_delegation(delegator_address, pool_address, 10000000000, 0, 9999999999); + assert_delegation(validator_address, pool_address, 90900000000, 10100000000, 0); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, false, 9999999999); + + // check cannot withdraw inactive stake unlocked by others even if owning pending_inactive + withdraw(delegator, pool_address, MAX_U64); + assert_delegation(delegator_address, pool_address, 10000000000, 0, 9999999999); + assert_delegation(validator_address, pool_address, 90900000000, 10100000000, 0); + + // withdraw entire owned inactive stake + let balance = coin::balance(validator_address); + withdraw(validator, pool_address, MAX_U64); + assert!(coin::balance(validator_address) == balance + 10100000000, 0); + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + assert_inactive_shares_pool(pool_address, 0, false, 0); + + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + assert_delegation(delegator_address, pool_address, 10100000000, 10099999998, 0); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, true, 10099999998); + assert_inactive_shares_pool(pool_address, 1, true, 9999999999); + + // use too small of an unlock amount to actually transfer shares to the pending_inactive pool + // check that no leftovers have been produced on the stake or delegation pools + stake::assert_stake_pool(pool_address, 101909000001, 10099999998, 0, 0); + unlock_with_min_stake_disabled(delegator, pool_address, 1); + stake::assert_stake_pool(pool_address, 101909000001, 10099999998, 0, 0); + assert_delegation(delegator_address, pool_address, 10100000000, 10099999998, 0); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, true, 10099999998); + + // implicitly execute the pending withdrawal by unlocking min stake to buy 1 share + unlock_with_min_stake_disabled(delegator, pool_address, 2); + stake::assert_stake_pool(pool_address, 101909000000, 0, 0, 1); + assert_delegation(delegator_address, pool_address, 10099999998, 0, 1); + // old pending withdrawal has been replaced + assert_pending_withdrawal(delegator_address, pool_address, true, 2, false, 1); + assert_inactive_shares_pool(pool_address, 1, false, 0); + assert_inactive_shares_pool(pool_address, 2, true, 1); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator = @0x010)] + public entry fun test_inactivate_no_excess_stake( + aptos_framework: &signer, + validator: &signer, + delegator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1200 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + stake::mint(delegator, 200 * ONE_APT); + add_stake(delegator, pool_address, 200 * ONE_APT); + + // create inactive and pending_inactive stakes on the stake pool + unlock(validator, pool_address, 200 * ONE_APT); + + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + unlock(delegator, pool_address, 100 * ONE_APT); + + // check no excess pending_inactive is inactivated in the special case + // the validator had gone inactive before its lockup expired + + let observed_lockup_cycle = observed_lockup_cycle(pool_address); + + // create dummy validator to ensure the existing validator can leave the set + initialize_test_validator(delegator, 100 * ONE_APT, true, true); + // inactivate validator + stake::leave_validator_set(validator, pool_address); + end_aptos_epoch(); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_INACTIVE, 0); + + // expire lockup afterwards + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + synchronize_delegation_pool(pool_address); + // no new inactive stake detected => OLC does not advance + assert!(observed_lockup_cycle(pool_address) == observed_lockup_cycle, 0); + + // pending_inactive stake has not been inactivated + stake::assert_stake_pool(pool_address, 113231100001, 20200000000, 0, 10200999997); + assert_delegation(delegator_address, pool_address, 10201000000, 0, 10200999997); + assert_delegation(validator_address, pool_address, 103030100000, 20200000000, 0); + + // withdraw some inactive stake (remaining pending_inactive is not inactivated) + withdraw(validator, pool_address, 200000000); + stake::assert_stake_pool(pool_address, 113231100001, 20000000001, 0, 10200999997); + assert_delegation(delegator_address, pool_address, 10201000000, 0, 10200999997); + assert_delegation(validator_address, pool_address, 103030100000, 20000000001, 0); + + // withdraw some pending_inactive stake (remaining pending_inactive is not inactivated) + withdraw(delegator, pool_address, 200999997); + stake::assert_stake_pool(pool_address, 113231100001, 20000000001, 0, 10000000001); + assert_delegation(delegator_address, pool_address, 10201000000, 0, 10000000001); + assert_delegation(validator_address, pool_address, 103030100000, 20000000001, 0); + + // no new inactive stake detected => OLC does not advance + assert!(observed_lockup_cycle(pool_address) == observed_lockup_cycle, 0); + + unlock(delegator, pool_address, 10201000000); + withdraw(delegator, pool_address, 10201000000); + assert!(observed_lockup_cycle(pool_address) == observed_lockup_cycle, 0); + + assert_delegation(delegator_address, pool_address, 0, 0, 10000000002); + assert_delegation(validator_address, pool_address, 103030100001, 20000000001, 0); + assert_pending_withdrawal(validator_address, pool_address, true, 0, true, 20000000001); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, false, 10000000002); + stake::assert_stake_pool(pool_address, 103030100001, 20000000001, 0, 10000000002); + + // reactivate validator + stake::join_validator_set(validator, pool_address); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_PENDING_ACTIVE, 0); + end_aptos_epoch(); + + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 0); + // no rewards have been produced yet and no stake inactivated as lockup has been refreshed + stake::assert_stake_pool(pool_address, 103030100001, 20000000001, 0, 10000000002); + + synchronize_delegation_pool(pool_address); + assert_pending_withdrawal(validator_address, pool_address, true, 0, true, 20000000001); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, false, 10000000002); + assert!(observed_lockup_cycle(pool_address) == observed_lockup_cycle, 0); + + // cannot withdraw pending_inactive stake anymore + withdraw(delegator, pool_address, 10000000002); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, false, 10000000002); + + // earning rewards is resumed from this epoch on + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 104060401001, 20000000001, 0, 10100000002); + + // new pending_inactive stake earns rewards but so does the old one + unlock(validator, pool_address, 104060401001); + assert_pending_withdrawal(validator_address, pool_address, true, 1, false, 104060401000); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, false, 10100000002); + end_aptos_epoch(); + assert_pending_withdrawal(validator_address, pool_address, true, 1, false, 105101005010); + assert_pending_withdrawal(delegator_address, pool_address, true, 1, false, 10201000002); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_stake_rewards( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1000 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + end_aptos_epoch(); + // 100000000000 active stake * 1.01 + assert_delegation(validator_address, pool_address, 1010 * ONE_APT, 0, 0); + + // add stake in pending_active state + stake::mint(validator, 200 * ONE_APT); + add_stake(validator, pool_address, 200 * ONE_APT); + + let fee = get_add_stake_fee(pool_address, 200 * ONE_APT); + assert_delegation(validator_address, pool_address, 1210 * ONE_APT - fee, 0, 0); + + end_aptos_epoch(); + // 101000000000 active stake * 1.01 + 20000000000 pending_active stake with no rewards + assert_delegation(validator_address, pool_address, 122010000000, 0, 0); + + end_aptos_epoch(); + // 122010000000 active stake * 1.01 + assert_delegation(validator_address, pool_address, 123230100000, 0, 0); + + // 123230100000 active stake * 1.01 + end_aptos_epoch(); + // 124462401000 active stake * 1.01 + end_aptos_epoch(); + // 125707025010 active stake * 1.01 + end_aptos_epoch(); + // 126964095260 active stake * 1.01 + end_aptos_epoch(); + // 128233736212 active stake * 1.01 + end_aptos_epoch(); + assert_delegation(validator_address, pool_address, 129516073574, 0, 0); + + // unlock 200 coins from delegator `validator` + unlock(validator, pool_address, 200 * ONE_APT); + assert_delegation(validator_address, pool_address, 109516073575, 0, 19999999999); + + // end this lockup cycle + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + // 109516073575 active stake * 1.01 + 19999999999 pending_inactive stake * 1.01 + assert_delegation(validator_address, pool_address, 110611234310, 20199999998, 0); + + end_aptos_epoch(); + // 110611234310 active stake * 1.01 + 20199999998 inactive stake + assert_delegation(validator_address, pool_address, 111717346653, 20199999998, 0); + + // add stake in pending_active state + stake::mint(validator, 1000 * ONE_APT); + add_stake(validator, pool_address, 1000 * ONE_APT); + + fee = get_add_stake_fee(pool_address, 1000 * ONE_APT); + assert_delegation(validator_address, pool_address, 211717346653 - fee, 20199999998, 0); + + end_aptos_epoch(); + // 111717346653 active stake * 1.01 + 100000000000 pending_active stake + 20199999998 inactive stake + assert_delegation(validator_address, pool_address, 212834520119, 20199999998, 0); + + end_aptos_epoch(); + // 212834520119 active stake * 1.01 + 20199999998 inactive stake + assert_delegation(validator_address, pool_address, 214962865320, 20199999998, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator = @0x010)] + public entry fun test_active_stake_rewards_multiple( + aptos_framework: &signer, + validator: &signer, + delegator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 200 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + // add stake in pending_active state + stake::mint(delegator, 300 * ONE_APT); + add_stake(delegator, pool_address, 300 * ONE_APT); + + let fee = get_add_stake_fee(pool_address, 300 * ONE_APT); + assert_delegation(delegator_address, pool_address, 300 * ONE_APT - fee, 0, 0); + assert_delegation(validator_address, pool_address, 200 * ONE_APT, 0, 0); + stake::assert_stake_pool(pool_address, 200 * ONE_APT, 0, 300 * ONE_APT, 0); + + end_aptos_epoch(); + // `delegator` got its `add_stake` fee back and `validator` its active stake rewards + assert_delegation(delegator_address, pool_address, 300 * ONE_APT, 0, 0); + assert_delegation(validator_address, pool_address, 20199999999, 0, 0); + stake::assert_stake_pool(pool_address, 502 * ONE_APT, 0, 0, 0); + + // delegators earn their own rewards from now on + end_aptos_epoch(); + assert_delegation(delegator_address, pool_address, 303 * ONE_APT, 0, 0); + assert_delegation(validator_address, pool_address, 20401999999, 0, 0); + stake::assert_stake_pool(pool_address, 50702000000, 0, 0, 0); + + end_aptos_epoch(); + assert_delegation(delegator_address, pool_address, 30603000000, 0, 0); + assert_delegation(validator_address, pool_address, 20606019999, 0, 0); + stake::assert_stake_pool(pool_address, 51209020000, 0, 0, 0); + + end_aptos_epoch(); + assert_delegation(delegator_address, pool_address, 30909030000, 0, 0); + assert_delegation(validator_address, pool_address, 20812080199, 0, 0); + stake::assert_stake_pool(pool_address, 51721110200, 0, 0, 0); + + // add more stake in pending_active state than currently active + stake::mint(delegator, 1000 * ONE_APT); + add_stake(delegator, pool_address, 1000 * ONE_APT); + + fee = get_add_stake_fee(pool_address, 1000 * ONE_APT); + assert_delegation(delegator_address, pool_address, 130909030000 - fee, 0, 0); + assert_delegation(validator_address, pool_address, 20812080199, 0, 0); + + end_aptos_epoch(); + // `delegator` got its `add_stake` fee back and `validator` its active stake rewards + assert_delegation(delegator_address, pool_address, 131218120300, 0, 0); + assert_delegation(validator_address, pool_address, 21020201001, 0, 0); + stake::assert_stake_pool(pool_address, 152238321302, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_pending_inactive_stake_rewards( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1000 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + end_aptos_epoch(); + assert_delegation(validator_address, pool_address, 1010 * ONE_APT, 0, 0); + + // unlock 200 coins from delegator `validator` + unlock(validator, pool_address, 200 * ONE_APT); + assert_delegation(validator_address, pool_address, 81000000001, 0, 19999999999); + + end_aptos_epoch(); // 81000000001 active stake * 1.01 + 19999999999 pending_inactive stake * 1.01 + end_aptos_epoch(); // 81810000001 active stake * 1.01 + 20199999998 pending_inactive stake * 1.01 + + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); // 82628100001 active stake * 1.01 + 20401999997 pending_inactive stake * 1.01 + end_aptos_epoch(); // 83454381001 active stake * 1.01 + 20606019996 pending_inactive stake(now inactive) + assert_delegation(validator_address, pool_address, 84288924811, 20606019996, 0); + + // unlock 200 coins from delegator `validator` which implicitly executes its pending withdrawal + unlock(validator, pool_address, 200 * ONE_APT); + assert!(coin::balance(validator_address) == 20606019996, 0); + assert_delegation(validator_address, pool_address, 64288924812, 0, 19999999999); + + // lockup cycle is not ended, pending_inactive stake is still earning + end_aptos_epoch(); // 64288924812 active stake * 1.01 + 19999999999 pending_inactive stake * 1.01 + end_aptos_epoch(); // 64931814060 active stake * 1.01 + 20199999998 pending_inactive stake * 1.01 + end_aptos_epoch(); // 65581132200 active stake * 1.01 + 20401999997 pending_inactive stake * 1.01 + end_aptos_epoch(); // 66236943522 active stake * 1.01 + 20606019996 pending_inactive stake * 1.01 + assert_delegation(validator_address, pool_address, 66899312957, 0, 20812080195); + + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); // 66899312957 active stake * 1.01 + 20812080195 pending_inactive stake * 1.01 + end_aptos_epoch(); // 67568306086 active stake * 1.01 + 21020200996 pending_inactive stake(now inactive) + end_aptos_epoch(); // 68243989147 active stake * 1.01 + 21020200996 inactive stake + assert_delegation(validator_address, pool_address, 68926429037, 21020200996, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, delegator2 = @0x020)] + public entry fun test_out_of_order_redeem( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 1000 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + + stake::mint(delegator1, 300 * ONE_APT); + add_stake(delegator1, pool_address, 300 * ONE_APT); + + stake::mint(delegator2, 300 * ONE_APT); + add_stake(delegator2, pool_address, 300 * ONE_APT); + + end_aptos_epoch(); + + // create the pending withdrawal of delegator 1 in lockup cycle 0 + unlock(delegator1, pool_address, 150 * ONE_APT); + assert_pending_withdrawal(delegator1_address, pool_address, true, 0, false, 14999999999); + + // move to lockup cycle 1 + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + // create the pending withdrawal of delegator 2 in lockup cycle 1 + unlock(delegator2, pool_address, 150 * ONE_APT); + assert_pending_withdrawal(delegator2_address, pool_address, true, 1, false, 14999999999); + // 14999999999 pending_inactive stake * 1.01 + assert_pending_withdrawal(delegator1_address, pool_address, true, 0, true, 15149999998); + + // move to lockup cycle 2 + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + assert_pending_withdrawal(delegator2_address, pool_address, true, 1, true, 15149999998); + assert_pending_withdrawal(delegator1_address, pool_address, true, 0, true, 15149999998); + + // both delegators who unlocked at different lockup cycles should be able to withdraw their stakes + withdraw(delegator1, pool_address, 15149999998); + withdraw(delegator2, pool_address, 5149999998); + + assert_pending_withdrawal(delegator2_address, pool_address, true, 1, true, 10000000001); + assert_pending_withdrawal(delegator1_address, pool_address, false, 0, false, 0); + assert!(coin::balance(delegator1_address) == 15149999998, 0); + assert!(coin::balance(delegator2_address) == 5149999997, 0); + + // recreate the pending withdrawal of delegator 1 in lockup cycle 2 + unlock(delegator1, pool_address, 100 * ONE_APT); + + // move to lockup cycle 3 + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + assert_pending_withdrawal(delegator2_address, pool_address, true, 1, true, 10000000001); + // 9999999999 pending_inactive stake * 1.01 + assert_pending_withdrawal(delegator1_address, pool_address, true, 2, true, 10099999998); + + // withdraw inactive stake of delegator 2 left from lockup cycle 1 in cycle 3 + withdraw(delegator2, pool_address, 10000000001); + assert!(coin::balance(delegator2_address) == 15149999998, 0); + assert_pending_withdrawal(delegator2_address, pool_address, false, 0, false, 0); + + // withdraw inactive stake of delegator 1 left from previous lockup cycle + withdraw(delegator1, pool_address, 10099999998); + assert!(coin::balance(delegator1_address) == 15149999998 + 10099999998, 0); + assert_pending_withdrawal(delegator1_address, pool_address, false, 0, false, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, delegator2 = @0x020)] + public entry fun test_operator_fee( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + + let validator_address = signer::address_of(validator); + account::create_account_for_test(validator_address); + + // create delegation pool of commission fee 12.65% + initialize_delegation_pool(validator, 1265, vector::empty()); + let pool_address = get_owned_pool_address(validator_address); + assert!(stake::get_operator(pool_address) == validator_address, 0); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + + stake::mint(delegator1, 100 * ONE_APT); + add_stake(delegator1, pool_address, 100 * ONE_APT); + + stake::mint(delegator2, 200 * ONE_APT); + add_stake(delegator2, pool_address, 200 * ONE_APT); + + // validator is inactive and added stake is instantly `active` + stake::assert_stake_pool(pool_address, 300 * ONE_APT, 0, 0, 0); + + // validator does not produce rewards yet + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 300 * ONE_APT, 0, 0, 0); + + // therefore, there are no operator commission rewards yet + assert_delegation(validator_address, pool_address, 0, 0, 0); + + // activate validator + stake::rotate_consensus_key(validator, pool_address, CONSENSUS_KEY_1, CONSENSUS_POP_1); + stake::join_validator_set(validator, pool_address); + end_aptos_epoch(); + + // produce active rewards + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 30300000000, 0, 0, 0); + + // 300000000 active rewards * 0.1265 + assert_delegation(validator_address, pool_address, 37950000, 0, 0); + // 10000000000 active stake * (1 + 1% reward-rate * 0.8735) + assert_delegation(delegator1_address, pool_address, 10087350000, 0, 0); + // 20000000000 active stake * 1.008735 + assert_delegation(delegator2_address, pool_address, 20174700000, 0, 0); + + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 30603000000, 0, 0, 0); + + // 603000000 active rewards * 0.1265 instead of + // 303000000 active rewards * 0.1265 + 37950000 active stake * 1.008735 + // because operator commission rewards are not automatically restaked compared to already owned stake + assert_delegation(validator_address, pool_address, 76279500, 0, 0); + // 10087350000 active stake * 1.008735 + some of the rewards of previous commission if restaked + assert_delegation(delegator1_address, pool_address, 10175573500, 0, 0); + // 20174700000 active stake * 1.008735 + some of the rewards of previous commission if restaked + assert_delegation(delegator2_address, pool_address, 20351147000, 0, 0); + + // restake operator commission rewards + synchronize_delegation_pool(pool_address); + + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 30909030000, 0, 0, 0); + + // 306030000 active rewards * 0.1265 + 76279500 active stake * 1.008735 + assert_delegation(validator_address, pool_address, 115658596, 0, 0); + // 10175573500 active stake * 1.008735 + assert_delegation(delegator1_address, pool_address, 10264457134, 0, 0); + // 20351147000 active stake * 1.008735 + assert_delegation(delegator2_address, pool_address, 20528914269, 0, 0); + + // check operator is rewarded by pending_inactive stake too + unlock(delegator2, pool_address, 100 * ONE_APT); + stake::assert_stake_pool(pool_address, 20909030001, 0, 0, 9999999999); + + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 21118120301, 0, 0, 10099999998); + + assert_pending_withdrawal(validator_address, pool_address, false, 0, false, 0); + // distribute operator pending_inactive commission rewards + synchronize_delegation_pool(pool_address); + // 99999999 pending_inactive rewards * 0.1265 + assert_pending_withdrawal(validator_address, pool_address, true, 0, false, 12649998); + + // 209090300 active rewards * 0.1265 + 115658596 active stake * 1.008735 + // 99999999 pending_inactive rewards * 0.1265 + assert_delegation(validator_address, pool_address, 143118796, 0, 12649998); + // 10264457134 active stake * 1.008735 + assert_delegation(delegator1_address, pool_address, 10354117168, 0, 0); + // 10528914270 active stake * 1.008735 + // 9999999999 pending_inactive stake * 1.008735 + assert_delegation(delegator2_address, pool_address, 10620884336, 0, 10087349999); + + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 21329301504, 10200999997, 0, 0); + + // operator pending_inactive rewards on previous epoch have been inactivated + // 211181203 active rewards * 0.1265 + 143118796 active stake * 1.008735 + // 100999999 pending_inactive rewards * 0.1265 + 12649998 pending_inactive stake * 1.008735 + assert_delegation(validator_address, pool_address, 171083360, 25536995, 0); + // distribute operator pending_inactive commission rewards + synchronize_delegation_pool(pool_address); + assert_pending_withdrawal(validator_address, pool_address, true, 0, true, 25536995); + + // check operator is not rewarded by `add_stake` fees + stake::mint(delegator1, 100 * ONE_APT); + assert!(get_add_stake_fee(pool_address, 100 * ONE_APT) > 0, 0); + add_stake(delegator1, pool_address, 100 * ONE_APT); + + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 31542594519, 10200999997, 0, 0); + + // 213293015 active rewards * 0.1265 + 171083360 active stake * 1.008735 + assert_delegation(validator_address, pool_address, 199559340, 25536995, 0); + + // unlock some more stake to produce pending_inactive commission + // 10620884336 active stake * (1.008735 ^ 2 epochs) + // 10087349999 pending_inactive stake * 1.008735 + assert_delegation(delegator2_address, pool_address, 10807241561, 10175463001, 0); + unlock(delegator2, pool_address, 100 * ONE_APT); + // 10807241561 - 100 APT < `MIN_COINS_ON_SHARES_POOL` thus active stake is entirely unlocked + assert_delegation(delegator2_address, pool_address, 0, 0, 10807241561); + end_aptos_epoch(); + + // in-flight pending_inactive commission can coexist with previous inactive commission + assert_delegation(validator_address, pool_address, 227532711, 25536996, 13671160); + assert_pending_withdrawal(validator_address, pool_address, true, 0, true, 25536996); + + // distribute in-flight pending_inactive commission, implicitly executing the inactive withdrawal of operator + coin::register(validator); + synchronize_delegation_pool(pool_address); + assert!(coin::balance(validator_address) == 25536996, 0); + + // in-flight commission has been synced, implicitly used to buy shares for operator + // expect operator stake to be slightly less than previously reported by `Self::get_stake` + assert_delegation(validator_address, pool_address, 227532711, 0, 13671159); + assert_pending_withdrawal(validator_address, pool_address, true, 1, false, 13671159); + } + + #[test(aptos_framework = @aptos_framework, old_operator = @0x123, delegator = @0x010, new_operator = @0x020)] + public entry fun test_change_operator( + aptos_framework: &signer, + old_operator: &signer, + delegator: &signer, + new_operator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + + let old_operator_address = signer::address_of(old_operator); + account::create_account_for_test(old_operator_address); + + let new_operator_address = signer::address_of(new_operator); + account::create_account_for_test(new_operator_address); + + // create delegation pool of commission fee 12.65% + initialize_delegation_pool(old_operator, 1265, vector::empty()); + let pool_address = get_owned_pool_address(old_operator_address); + assert!(stake::get_operator(pool_address) == old_operator_address, 0); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + stake::mint(delegator, 200 * ONE_APT); + add_stake(delegator, pool_address, 200 * ONE_APT); + unlock(delegator, pool_address, 100 * ONE_APT); + + // activate validator + stake::rotate_consensus_key(old_operator, pool_address, CONSENSUS_KEY_1, CONSENSUS_POP_1); + stake::join_validator_set(old_operator, pool_address); + end_aptos_epoch(); + + // produce active and pending_inactive rewards + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 10100000000, 0, 0, 10100000000); + assert_delegation(old_operator_address, pool_address, 12650000, 0, 12650000); + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 10201000000, 0, 0, 10201000000); + assert_delegation(old_operator_address, pool_address, 25426500, 0, 25426500); + + // change operator + set_operator(old_operator, new_operator_address); + + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 10303010000, 0, 0, 10303010000); + // 25426500 active stake * 1.008735 and 25426500 pending_inactive stake * 1.008735 + assert_delegation(old_operator_address, pool_address, 25648600, 0, 25648600); + // 102010000 active rewards * 0.1265 and 102010000 pending_inactive rewards * 0.1265 + assert_delegation(new_operator_address, pool_address, 12904265, 0, 12904265); + + // restake `new_operator` commission rewards + synchronize_delegation_pool(pool_address); + + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 10406040100, 0, 0, 10406040100); + // 25648600 active stake * 1.008735 and 25648600 pending_inactive stake * 1.008735 + assert_delegation(old_operator_address, pool_address, 25872641, 0, 25872641); + // 103030100 active rewards * 0.1265 and 12904265 active stake * 1.008735 + // 103030100 pending_inactive rewards * 0.1265 and 12904265 pending_inactive stake * 1.008735 + assert_delegation(new_operator_address, pool_address, 26050290, 0, 26050290); + } + + #[test( + aptos_framework = @aptos_framework, + operator1 = @0x123, + delegator = @0x010, + beneficiary = @0x020, + operator2 = @0x030 + )] + public entry fun test_set_beneficiary_for_operator( + aptos_framework: &signer, + operator1: &signer, + delegator: &signer, + beneficiary: &signer, + operator2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + + let operator1_address = signer::address_of(operator1); + aptos_account::create_account(operator1_address); + + let operator2_address = signer::address_of(operator2); + aptos_account::create_account(operator2_address); + + let beneficiary_address = signer::address_of(beneficiary); + aptos_account::create_account(beneficiary_address); + + // create delegation pool of commission fee 12.65% + initialize_delegation_pool(operator1, 1265, vector::empty()); + let pool_address = get_owned_pool_address(operator1_address); + assert!(stake::get_operator(pool_address) == operator1_address, 0); + assert!(beneficiary_for_operator(operator1_address) == operator1_address, 0); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + stake::mint(delegator, 2000000 * ONE_APT); + add_stake(delegator, pool_address, 2000000 * ONE_APT); + unlock(delegator, pool_address, 1000000 * ONE_APT); + + // activate validator + stake::rotate_consensus_key(operator1, pool_address, CONSENSUS_KEY_1, CONSENSUS_POP_1); + stake::join_validator_set(operator1, pool_address); + end_aptos_epoch(); + + // produce active and pending_inactive rewards + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 101000000000000, 0, 0, 101000000000000); + assert_delegation(operator1_address, pool_address, 126500000000, 0, 126500000000); + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 102010000000000, 0, 0, 102010000000000); + assert_delegation(operator1_address, pool_address, 254265000000, 0, 254265000000); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + withdraw(operator1, pool_address, ONE_APT); + assert!(coin::balance(operator1_address) == ONE_APT - 1, 0); + + set_beneficiary_for_operator(operator1, beneficiary_address); + assert!(beneficiary_for_operator(operator1_address) == beneficiary_address, 0); + end_aptos_epoch(); + + unlock(beneficiary, pool_address, ONE_APT); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + withdraw(beneficiary, pool_address, ONE_APT); + assert!(coin::balance(beneficiary_address) == ONE_APT - 1, 0); + assert!(coin::balance(operator1_address) == ONE_APT - 1, 0); + + // switch operator to operator2. The rewards should go to operator2 not to the beneficiay of operator1. + set_operator(operator1, operator2_address); + end_aptos_epoch(); + unlock(operator2, pool_address, ONE_APT); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + + withdraw(operator2, pool_address, ONE_APT); + assert!(coin::balance(beneficiary_address) == ONE_APT - 1, 0); + assert!(coin::balance(operator2_address) == ONE_APT - 1, 0); + } + + #[test(aptos_framework = @aptos_framework, operator = @0x123, delegator = @0x010)] + public entry fun test_update_commission_percentage( + aptos_framework: &signer, + operator: &signer, + delegator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + + let operator_address = signer::address_of(operator); + account::create_account_for_test(operator_address); + + // create delegation pool of commission fee 12.65% + initialize_delegation_pool(operator, 1265, vector::empty()); + let pool_address = get_owned_pool_address(operator_address); + assert!(stake::get_operator(pool_address) == operator_address, 0); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + stake::mint(delegator, 200 * ONE_APT); + add_stake(delegator, pool_address, 200 * ONE_APT); + unlock(delegator, pool_address, 100 * ONE_APT); + + // activate validator + stake::rotate_consensus_key(operator, pool_address, CONSENSUS_KEY_1, CONSENSUS_POP_1); + stake::join_validator_set(operator, pool_address); + end_aptos_epoch(); + + // produce active and pending_inactive rewards + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 10100000000, 0, 0, 10100000000); + assert_delegation(operator_address, pool_address, 12650000, 0, 12650000); + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 10201000000, 0, 0, 10201000000); + assert_delegation(operator_address, pool_address, 25426500, 0, 25426500); + + // change the commission percentage + update_commission_percentage(operator, 2265); + // the new commission percentage does not take effect until the next lockup cycle. + assert!(operator_commission_percentage(pool_address) == 1265, 0); + + // end the lockup cycle + fast_forward_to_unlock(pool_address); + + // Test that the `get_add_stake_fee` correctly uses the new commission percentage, and returns the correct + // fee amount 76756290 in the following case, not 86593604 (calculated with the old commission rate). + assert!(get_add_stake_fee(pool_address, 100 * ONE_APT) == 76756290, 0); + + synchronize_delegation_pool(pool_address); + // the commission percentage is updated to the new one. + assert!(operator_commission_percentage(pool_address) == 2265, 0); + + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 10406040100, 10303010000, 0, 0); + assert_delegation(operator_address, pool_address, 62187388, 38552865, 0); + + end_aptos_epoch(); + stake::assert_stake_pool(pool_address, 10510100501, 10303010000, 0, 0); + assert_delegation(operator_address, pool_address, 86058258, 38552865, 0); + } + + #[test(aptos_framework = @aptos_framework, operator = @0x123, delegator = @0x010)] + #[expected_failure(abort_code = 196629, location = Self)] + public entry fun test_last_minute_commission_rate_change_failed( + aptos_framework: &signer, + operator: &signer, + delegator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + + let operator_address = signer::address_of(operator); + account::create_account_for_test(operator_address); + + // create delegation pool of commission fee 12.65% + initialize_delegation_pool(operator, 1265, vector::empty()); + let pool_address = get_owned_pool_address(operator_address); + assert!(stake::get_operator(pool_address) == operator_address, 0); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + + stake::mint(delegator, 200 * ONE_APT); + add_stake(delegator, pool_address, 200 * ONE_APT); + unlock(delegator, pool_address, 100 * ONE_APT); + + // activate validator + stake::rotate_consensus_key(operator, pool_address, CONSENSUS_KEY_1, CONSENSUS_POP_1); + stake::join_validator_set(operator, pool_address); + end_aptos_epoch(); + + // 30 days are remaining in the lockup period. + update_commission_percentage(operator, 2215); + timestamp::fast_forward_seconds(7 * 24 * 60 * 60); + end_aptos_epoch(); + + // 23 days are remaining in the lockup period. + update_commission_percentage(operator, 2225); + timestamp::fast_forward_seconds(7 * 24 * 60 * 60); + end_aptos_epoch(); + + // 16 days are remaining in the lockup period. + update_commission_percentage(operator, 2235); + timestamp::fast_forward_seconds(7 * 24 * 60 * 60); + end_aptos_epoch(); + + // 9 days are remaining in the lockup period. + update_commission_percentage(operator, 2245); + timestamp::fast_forward_seconds(7 * 24 * 60 * 60); + end_aptos_epoch(); + + // 2 days are remaining in the lockup period. So, the following line is expected to fail. + update_commission_percentage(operator, 2255); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, delegator2 = @0x020)] + public entry fun test_min_stake_is_preserved( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 100 * ONE_APT, true, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + + // add stake without fees as validator is not active yet + stake::mint(delegator1, 50 * ONE_APT); + add_stake(delegator1, pool_address, 50 * ONE_APT); + stake::mint(delegator2, 16 * ONE_APT); + add_stake(delegator2, pool_address, 16 * ONE_APT); + + // validator becomes active and share price is 1 + end_aptos_epoch(); + + assert_delegation(delegator1_address, pool_address, 5000000000, 0, 0); + // pending_inactive balance would be under threshold => move MIN_COINS_ON_SHARES_POOL coins + unlock(delegator1, pool_address, MIN_COINS_ON_SHARES_POOL - 1); + assert_delegation(delegator1_address, pool_address, 3999999999, 0, 1000000001); + + // pending_inactive balance is over threshold + reactivate_stake(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 4000000000, 0, 1000000000); + + // pending_inactive balance would be under threshold => move entire balance + reactivate_stake(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 5000000000, 0, 0); + + // active balance would be under threshold => move entire balance + unlock(delegator1, pool_address, 5000000000 - (MIN_COINS_ON_SHARES_POOL - 1)); + assert_delegation(delegator1_address, pool_address, 0, 0, 5000000000); + + // active balance would be under threshold => move MIN_COINS_ON_SHARES_POOL coins + reactivate_stake(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 1000000001, 0, 3999999999); + + // active balance is over threshold + unlock(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 1000000000, 0, 4000000000); + + // pending_inactive balance would be under threshold => move entire balance + reactivate_stake(delegator1, pool_address, 4000000000 - (MIN_COINS_ON_SHARES_POOL - 1)); + assert_delegation(delegator1_address, pool_address, 5000000000, 0, 0); + + // active + pending_inactive balance < 2 * MIN_COINS_ON_SHARES_POOL + // stake can live on only one of the shares pools + assert_delegation(delegator2_address, pool_address, 16 * ONE_APT, 0, 0); + unlock(delegator2, pool_address, 1); + assert_delegation(delegator2_address, pool_address, 0, 0, 16 * ONE_APT); + reactivate_stake(delegator2, pool_address, 1); + assert_delegation(delegator2_address, pool_address, 16 * ONE_APT, 0, 0); + + unlock(delegator2, pool_address, ONE_APT); + assert_delegation(delegator2_address, pool_address, 0, 0, 16 * ONE_APT); + reactivate_stake(delegator2, pool_address, 2 * ONE_APT); + assert_delegation(delegator2_address, pool_address, 16 * ONE_APT, 0, 0); + + // share price becomes 1.01 on both pools + unlock(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 3999999999, 0, 1000000001); + end_aptos_epoch(); + assert_delegation(delegator1_address, pool_address, 4039999998, 0, 1010000001); + + // pending_inactive balance is over threshold + reactivate_stake(delegator1, pool_address, 10000001); + assert_delegation(delegator1_address, pool_address, 4049999998, 0, 1000000001); + + // 1 coin < 1.01 so no shares are redeemed + reactivate_stake(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 4049999998, 0, 1000000001); + + // pending_inactive balance is over threshold + // requesting 2 coins actually redeems 1 coin from pending_inactive pool + reactivate_stake(delegator1, pool_address, 2); + assert_delegation(delegator1_address, pool_address, 4049999999, 0, 1000000000); + + // 1 coin < 1.01 so no shares are redeemed + reactivate_stake(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 4049999999, 0, 1000000000); + + // pending_inactive balance would be under threshold => move entire balance + reactivate_stake(delegator1, pool_address, 2); + assert_delegation(delegator1_address, pool_address, 5049999999, 0, 0); + + // pending_inactive balance would be under threshold => move MIN_COINS_ON_SHARES_POOL coins + unlock(delegator1, pool_address, MIN_COINS_ON_SHARES_POOL - 1); + assert_delegation(delegator1_address, pool_address, 4049999998, 0, 1000000000); + + // pending_inactive balance would be under threshold => move entire balance + reactivate_stake(delegator1, pool_address, 1); + assert_delegation(delegator1_address, pool_address, 5049999998, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010)] + #[expected_failure(abort_code = 0x1000f, location = Self)] + public entry fun test_create_proposal_abort_if_inefficient_stake( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + // delegator2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + aptos_governance::initialize_for_test( + aptos_framework, + (10 * ONE_APT as u128), + 100 * ONE_APT, + 1000, + ); + aptos_governance::initialize_partial_voting(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting( + )], + vector[]); + initialize_test_validator(validator, 100 * ONE_APT, true, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + // Delegation pool is created after partial governance voting feature flag is enabled. So this delegation + // pool is created with partial governance voting enabled. + assert!(stake::get_delegated_voter(pool_address) == pool_address, 1); + assert!(partial_governance_voting_enabled(pool_address), 2); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + stake::mint(delegator1, 100 * ONE_APT); + add_stake(delegator1, pool_address, 10 * ONE_APT); + end_aptos_epoch(); + + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + create_proposal( + delegator1, + pool_address, + execution_hash, + b"", + b"", + true, + ); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010)] + public entry fun test_create_proposal_with_sufficient_stake( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + aptos_governance::initialize_for_test( + aptos_framework, + (10 * ONE_APT as u128), + 100 * ONE_APT, + 1000, + ); + aptos_governance::initialize_partial_voting(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting( + )], + vector[]); + initialize_test_validator(validator, 100 * ONE_APT, true, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + // Delegation pool is created after partial governance voting feature flag is enabled. So this delegation + // pool is created with partial governance voting enabled. + assert!(stake::get_delegated_voter(pool_address) == pool_address, 1); + assert!(partial_governance_voting_enabled(pool_address), 2); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + stake::mint(delegator1, 100 * ONE_APT); + add_stake(delegator1, pool_address, 100 * ONE_APT); + end_aptos_epoch(); + + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + create_proposal( + delegator1, + pool_address, + execution_hash, + b"", + b"", + true, + ); + } + + #[test( + aptos_framework = @aptos_framework, + validator = @0x123, + delegator1 = @0x010, + delegator2 = @0x020, + voter1 = @0x030, + voter2 = @0x040 + )] + public entry fun test_voting_power_change( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + voter1: &signer, + voter2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test_no_reward(aptos_framework); + aptos_governance::initialize_for_test( + aptos_framework, + (10 * ONE_APT as u128), + 100 * ONE_APT, + 1000, + ); + aptos_governance::initialize_partial_voting(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting( + )], + vector[] + ); + + initialize_test_validator(validator, 100 * ONE_APT, true, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + // Delegation pool is created after partial governance voting feature flag is enabled. So this delegation + // pool is created with partial governance voting enabled. + assert!(stake::get_delegated_voter(pool_address) == pool_address, 1); + assert!(partial_governance_voting_enabled(pool_address), 1); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + let voter1_address = signer::address_of(voter1); + account::create_account_for_test(voter1_address); + let voter2_address = signer::address_of(voter2); + account::create_account_for_test(voter2_address); + + stake::mint(delegator1, 110 * ONE_APT); + add_stake(delegator1, pool_address, 10 * ONE_APT); + stake::mint(delegator2, 110 * ONE_APT); + add_stake(delegator2, pool_address, 90 * ONE_APT); + // By default, the voter of a delegator is itself. + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + end_aptos_epoch(); + // Reward rate is 0. No reward so no voting power change. + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + // Delegator1 delegates its voting power to voter1 but it takes 1 lockup cycle to take effects. So no voting power + // change now. + delegate_voting_power(delegator1, pool_address, voter1_address); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + // 1 epoch passed but the lockup cycle hasn't ended. No voting power change. + end_aptos_epoch(); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + // One cycle passed. The voter change takes effects. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + // Delegator2 delegates its voting power to voter1 but it takes 1 lockup cycle to take effects. So no voting power + // change now. + delegate_voting_power(delegator2, pool_address, voter1_address); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + // One cycle passed. The voter change takes effects. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + assert!(calculate_and_update_delegator_voter(pool_address, delegator2_address) == voter1_address, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + + // delegator1 changes to voter2 then change back. delegator2 changes to voter1. + // No voting power change in this lockup cycle. + delegate_voting_power(delegator1, pool_address, voter2_address); + delegate_voting_power(delegator2, pool_address, voter2_address); + delegate_voting_power(delegator1, pool_address, voter1_address); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + + // One cycle passed. The voter change takes effects. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + assert!(calculate_and_update_delegator_voter(pool_address, delegator1_address) == voter1_address, 1); + assert!(calculate_and_update_delegator_voter(pool_address, delegator2_address) == voter2_address, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 90 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + + // delegator1 adds stake to the pool. Voting power changes immediately. + add_stake(delegator1, pool_address, 90 * ONE_APT); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 90 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + + // delegator1 unlocks stake and changes its voter. No voting power change until next lockup cycle. + unlock(delegator1, pool_address, 90 * ONE_APT); + delegate_voting_power(delegator1, pool_address, voter2_address); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 90 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + + // One cycle passed. The voter change takes effects. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + // Withdrawl inactive shares will not change voting power. + withdraw(delegator1, pool_address, 45 * ONE_APT); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + + // voter2 adds stake for itself. Voting power changes immediately. + stake::mint(voter2, 110 * ONE_APT); + add_stake(voter2, pool_address, 10 * ONE_APT); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 110 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, voter1 = @0x030)] + public entry fun test_voting_power_change_for_existing_delegation_pool( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + voter1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test_no_reward(aptos_framework); + aptos_governance::initialize_for_test( + aptos_framework, + (10 * ONE_APT as u128), + 100 * ONE_APT, + 1000, + ); + aptos_governance::initialize_partial_voting(aptos_framework); + + initialize_test_validator(validator, 100 * ONE_APT, true, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + // Delegation pool is created before partial governance voting feature flag is enabled. So this delegation + // pool's voter is its owner. + assert!(stake::get_delegated_voter(pool_address) == validator_address, 1); + assert!(!partial_governance_voting_enabled(pool_address), 1); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + let voter1_address = signer::address_of(voter1); + account::create_account_for_test(voter1_address); + + stake::mint(delegator1, 110 * ONE_APT); + add_stake(delegator1, pool_address, 10 * ONE_APT); + + // Enable partial governance voting feature flag. + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting( + )], + vector[] + ); + // Voter doens't change until enabling partial governance voting on this delegation pool. + assert!(stake::get_delegated_voter(pool_address) == validator_address, 1); + // Enable partial governance voting on this delegation pool. + enable_partial_governance_voting(pool_address); + assert!(stake::get_delegated_voter(pool_address) == pool_address, 1); + assert!(partial_governance_voting_enabled(pool_address), 1); + + // By default, the voter of a delegator is itself. + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + + // Delegator1 delegates its voting power to voter1. + // It takes 1 cycle to take effect. No immediate change. + delegate_voting_power(delegator1, pool_address, voter1_address); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + + // One cycle passed. The voter change takes effects. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + } + + #[test( + aptos_framework = @aptos_framework, + validator = @0x123, + delegator1 = @0x010, + delegator2 = @0x020, + voter1 = @0x030, + voter2 = @0x040 + )] + public entry fun test_voting_power_change_for_rewards( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + voter1: &signer, + voter2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test_custom( + aptos_framework, + 100 * ONE_APT, + 10000 * ONE_APT, + LOCKUP_CYCLE_SECONDS, + true, + 100, + 100, + 1000000 + ); + aptos_governance::initialize_for_test( + aptos_framework, + (10 * ONE_APT as u128), + 100 * ONE_APT, + 1000, + ); + aptos_governance::initialize_partial_voting(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting( + )], + vector[] + ); + + // 50% commission rate + initialize_test_validator_custom(validator, 100 * ONE_APT, true, false, 5000); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + // Delegation pool is created after partial governance voting feature flag is enabled. So this delegation + // pool is created with partial governance voting enabled. + assert!(stake::get_delegated_voter(pool_address) == pool_address, 1); + assert!(partial_governance_voting_enabled(pool_address), 1); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + let voter1_address = signer::address_of(voter1); + account::create_account_for_test(voter1_address); + let voter2_address = signer::address_of(voter2); + account::create_account_for_test(voter2_address); + + stake::mint(delegator1, 110 * ONE_APT); + add_stake(delegator1, pool_address, 10 * ONE_APT); + stake::mint(delegator2, 110 * ONE_APT); + add_stake(delegator2, pool_address, 90 * ONE_APT); + // By default, the voter of a delegator is itself. + assert!(calculate_and_update_voter_total_voting_power(pool_address, validator_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + // One epoch is passed. Delegators earn no reward because their stake was inactive. + end_aptos_epoch(); + assert!(calculate_and_update_voter_total_voting_power(pool_address, validator_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + + // 2 epoches are passed. Delegators earn reward and voting power increases. Operator earns reward and + // commission. Because there is no operation during these 2 epoches. Operator's commission is not compounded. + end_aptos_epoch(); + end_aptos_epoch(); + assert!(calculate_and_update_voter_total_voting_power(pool_address, validator_address) == 550 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 25 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 225 * ONE_APT, 1); + + // Another epoch is passed. Voting power chage due to reward is correct even if delegator1 and delegator2 change its voter. + delegate_voting_power(delegator1, pool_address, voter1_address); + delegate_voting_power(delegator2, pool_address, voter1_address); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_aptos_epoch(); + assert!(calculate_and_update_voter_total_voting_power(pool_address, validator_address) == 122499999999, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 375 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 0, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 0, 1); + } + + #[test( + aptos_framework = @aptos_framework, + validator = @0x123, + delegator1 = @0x010, + delegator2 = @0x020, + voter1 = @0x030, + voter2 = @0x040 + )] + public entry fun test_voting_power_change_already_voted_before_partial( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + delegator2: &signer, + voter1: &signer, + voter2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + // partial voing hasn't been enabled yet. A proposal has been created by the validator. + let proposal1_id = setup_vote(aptos_framework, validator, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + let delegator2_address = signer::address_of(delegator2); + account::create_account_for_test(delegator2_address); + let voter1_address = signer::address_of(voter1); + account::create_account_for_test(voter1_address); + let voter2_address = signer::address_of(voter2); + account::create_account_for_test(voter2_address); + + stake::mint(delegator1, 110 * ONE_APT); + add_stake(delegator1, pool_address, 10 * ONE_APT); + stake::mint(delegator2, 110 * ONE_APT); + add_stake(delegator2, pool_address, 90 * ONE_APT); + + // Create 2 proposals and vote for proposal1. + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let proposal2_id = aptos_governance::create_proposal_v2_impl( + validator, + pool_address, + execution_hash, + b"", + b"", + true, + ); + aptos_governance::vote(validator, pool_address, proposal1_id, true); + + // Enable partial governance voting feature flag. + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting( + )], + vector[] + ); + // Voter doens't change until enabling partial governance voting on this delegation pool. + assert!(stake::get_delegated_voter(pool_address) == validator_address, 1); + // Enable partial governance voting on this delegation pool. + enable_partial_governance_voting(pool_address); + assert!(stake::get_delegated_voter(pool_address) == pool_address, 1); + assert!(partial_governance_voting_enabled(pool_address), 1); + + assert!(calculate_and_update_voter_total_voting_power(pool_address, validator_address) == 100 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 10 * ONE_APT, 1); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator2_address) == 90 * ONE_APT, 1); + // No one can vote for proposal1 because it's already voted before enabling partial governance voting. + assert!(calculate_and_update_remaining_voting_power(pool_address, validator_address, proposal1_id) == 0, 1); + assert!(calculate_and_update_remaining_voting_power(pool_address, delegator1_address, proposal1_id) == 0, 1); + assert!(calculate_and_update_remaining_voting_power(pool_address, delegator2_address, proposal1_id) == 0, 1); + assert!( + calculate_and_update_remaining_voting_power(pool_address, validator_address, proposal2_id) == 100 * ONE_APT, + 1 + ); + assert!( + calculate_and_update_remaining_voting_power(pool_address, delegator1_address, proposal2_id) == 10 * ONE_APT, + 1 + ); + assert!( + calculate_and_update_remaining_voting_power(pool_address, delegator2_address, proposal2_id) == 90 * ONE_APT, + 1 + ); + + // Delegator1 tries to use 50 APT to vote on proposal2, but it only has 10 APT. So only 10 APT voting power is used. + vote(delegator1, pool_address, proposal2_id, 50 * ONE_APT, true); + assert!(calculate_and_update_remaining_voting_power(pool_address, delegator1_address, proposal2_id) == 0, 1); + + add_stake(delegator1, pool_address, 60 * ONE_APT); + assert!(calculate_and_update_voter_total_voting_power(pool_address, delegator1_address) == 70 * ONE_APT, 1); + vote(delegator1, pool_address, proposal2_id, 25 * ONE_APT, true); + assert!( + calculate_and_update_remaining_voting_power(pool_address, delegator1_address, proposal2_id) == 35 * ONE_APT, + 1 + ); + vote(delegator1, pool_address, proposal2_id, 30 * ONE_APT, false); + assert!( + calculate_and_update_remaining_voting_power(pool_address, delegator1_address, proposal2_id) == 5 * ONE_APT, + 1 + ); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, voter1 = @0x030)] + #[expected_failure(abort_code = 0x10010, location = Self)] + public entry fun test_vote_should_failed_if_already_voted_before_enable_partial_voting_flag( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + voter1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + // partial voing hasn't been enabled yet. A proposal has been created by the validator. + let proposal1_id = setup_vote(aptos_framework, validator, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + let voter1_address = signer::address_of(voter1); + account::create_account_for_test(voter1_address); + + stake::mint(delegator1, 110 * ONE_APT); + add_stake(delegator1, pool_address, 10 * ONE_APT); + end_aptos_epoch(); + + aptos_governance::vote(validator, pool_address, proposal1_id, true); + + // Enable partial governance voting feature flag. + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting( + )], + vector[] + ); + // Enable partial governance voting on this delegation pool. + enable_partial_governance_voting(pool_address); + + vote(delegator1, pool_address, proposal1_id, 10 * ONE_APT, true); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, voter1 = @0x030)] + #[expected_failure(abort_code = 0x10011, location = Self)] + public entry fun test_vote_should_failed_if_already_voted_before_enable_partial_voting_on_pool( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + voter1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + // partial voing hasn't been enabled yet. A proposal has been created by the validator. + let proposal1_id = setup_vote(aptos_framework, validator, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + let voter1_address = signer::address_of(voter1); + account::create_account_for_test(voter1_address); + + stake::mint(delegator1, 110 * ONE_APT); + add_stake(delegator1, pool_address, 10 * ONE_APT); + end_aptos_epoch(); + + // Enable partial governance voting feature flag. + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_partial_governance_voting(), features::get_delegation_pool_partial_governance_voting( + )], + vector[] + ); + + // The operator voter votes on the proposal after partial governace voting flag is enabled but before partial voting is enabled on the pool. + aptos_governance::vote(validator, pool_address, proposal1_id, true); + + // Enable partial governance voting on this delegation pool. + enable_partial_governance_voting(pool_address); + + add_stake(delegator1, pool_address, 10 * ONE_APT); + vote(delegator1, pool_address, proposal1_id, 10 * ONE_APT, true); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010)] + #[expected_failure(abort_code = 0x10010, location = Self)] + public entry fun test_vote_should_failed_if_no_stake( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + // partial voing hasn't been enabled yet. A proposal has been created by the validator. + let proposal1_id = setup_vote(aptos_framework, validator, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + + // Delegator1 has no stake. Abort. + vote(delegator1, pool_address, proposal1_id, 10 * ONE_APT, true); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator1 = @0x010, voter1 = @0x030)] + public entry fun test_delegate_voting_power_should_pass_even_if_no_stake( + aptos_framework: &signer, + validator: &signer, + delegator1: &signer, + voter1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + // partial voing hasn't been enabled yet. A proposal has been created by the validator. + setup_vote(aptos_framework, validator, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + let delegator1_address = signer::address_of(delegator1); + account::create_account_for_test(delegator1_address); + + // Delegator1 has no stake. Abort. + delegate_voting_power(delegator1, pool_address, signer::address_of(voter1)); + } + + #[test( + aptos_framework = @aptos_framework, + validator = @0x123, + delegator = @0x010, + voter1 = @0x020, + voter2 = @0x030 + )] + public entry fun test_delegate_voting_power_applies_next_lockup( + aptos_framework: &signer, + validator: &signer, + delegator: &signer, + voter1: &signer, + voter2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + aptos_governance::initialize_partial_voting(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[ + features::get_partial_governance_voting(), + features::get_delegation_pool_partial_governance_voting() + ], + vector[] + ); + + initialize_test_validator(validator, 100 * ONE_APT, true, true); + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + let voter1_address = signer::address_of(voter1); + let voter2_address = signer::address_of(voter2); + + stake::mint(delegator, 100 * ONE_APT); + add_stake(delegator, pool_address, 20 * ONE_APT); + + let first_lockup_end = stake::get_lockup_secs(pool_address); + // default voter is the delegator + let (voter, pending_voter, last_locked_until_secs) = calculate_and_update_voting_delegation( + pool_address, + delegator_address + ); + assert!(voter == delegator_address, 0); + assert!(pending_voter == delegator_address, 0); + assert!(last_locked_until_secs == first_lockup_end, 0); + + // delegate to voter 1 which takes effect next lockup + delegate_voting_power(delegator, pool_address, voter1_address); + (voter, pending_voter, last_locked_until_secs) = calculate_and_update_voting_delegation( + pool_address, + delegator_address + ); + assert!(voter == delegator_address, 0); + assert!(pending_voter == voter1_address, 0); + assert!(last_locked_until_secs == first_lockup_end, 0); + assert!( + calculate_and_update_voter_total_voting_power( + pool_address, + delegator_address + ) == 20 * ONE_APT - get_add_stake_fee(pool_address, 20 * ONE_APT), + 0 + ); + + // end this lockup cycle + fast_forward_to_unlock(pool_address); + let second_lockup_end = stake::get_lockup_secs(pool_address); + assert!(second_lockup_end > first_lockup_end, 0); + + (voter, pending_voter, last_locked_until_secs) = calculate_and_update_voting_delegation( + pool_address, + delegator_address + ); + // voter 1 becomes current voter and owns all voting power of delegator + assert!(voter == voter1_address, 0); + assert!(pending_voter == voter1_address, 0); + assert!(last_locked_until_secs == second_lockup_end, 0); + assert!( + calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 20 * ONE_APT, + 0 + ); + + // delegate to voter 2, current voter should still be voter 1 + delegate_voting_power(delegator, pool_address, voter2_address); + (voter, pending_voter, last_locked_until_secs) = calculate_and_update_voting_delegation( + pool_address, + delegator_address + ); + assert!(voter == voter1_address, 0); + assert!(pending_voter == voter2_address, 0); + assert!(last_locked_until_secs == second_lockup_end, 0); + assert!( + calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 20 * ONE_APT, + 0 + ); + + // stake added by delegator counts as voting power for the current voter + add_stake(delegator, pool_address, 30 * ONE_APT); + assert!( + calculate_and_update_voter_total_voting_power( + pool_address, + voter1_address + ) == 20 * ONE_APT + 30 * ONE_APT - get_add_stake_fee(pool_address, 30 * ONE_APT), + 0 + ); + + // refunded `add_stake` fee is counted as voting power too + end_aptos_epoch(); + assert!( + calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 5020000000, + 0 + ); + + // delegator can unlock their entire stake (all voting shares are owned by voter 1) + unlock(delegator, pool_address, 5020000000); + assert!( + calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 5020000000, + 0 + ); + + // delegator can reactivate their entire stake (all voting shares are owned by voter 1) + reactivate_stake(delegator, pool_address, 5020000000); + assert!( + calculate_and_update_voter_total_voting_power(pool_address, voter1_address) == 5019999999, + 0 + ); + + // end this lockup cycle + fast_forward_to_unlock(pool_address); + let third_lockup_end = stake::get_lockup_secs(pool_address); + assert!(third_lockup_end > second_lockup_end, 0); + + // voter 2 becomes current voter and owns all voting power of delegator + (voter, pending_voter, last_locked_until_secs) = calculate_and_update_voting_delegation( + pool_address, + delegator_address + ); + assert!(voter == voter2_address, 0); + assert!(pending_voter == voter2_address, 0); + assert!(last_locked_until_secs == third_lockup_end, 0); + assert!( + calculate_and_update_voter_total_voting_power(pool_address, voter2_address) == 5070199999, + 0 + ); + } + + #[test( + aptos_framework = @aptos_framework, + validator = @0x123, + validator_min_consensus = @0x234, + delegator = @0x010, + voter1 = @0x020, + voter2 = @0x030 + )] + public entry fun test_delegate_voting_power_from_inactive_validator( + aptos_framework: &signer, + validator: &signer, + validator_min_consensus: &signer, + delegator: &signer, + voter1: &signer, + voter2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + aptos_governance::initialize_partial_voting(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[ + features::get_partial_governance_voting(), + features::get_delegation_pool_partial_governance_voting() + ], + vector[] + ); + + // activate more validators in order to inactivate one later + initialize_test_validator(validator, 100 * ONE_APT, true, false); + initialize_test_validator(validator_min_consensus, 100 * ONE_APT, true, true); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_address = signer::address_of(delegator); + account::create_account_for_test(delegator_address); + let voter1_address = signer::address_of(voter1); + let voter2_address = signer::address_of(voter2); + + let first_lockup_end = stake::get_lockup_secs(pool_address); + let (voter, pending_voter, last_locked_until_secs) = calculate_and_update_voting_delegation( + pool_address, + delegator_address + ); + assert!(voter == delegator_address, 0); + assert!(pending_voter == delegator_address, 0); + assert!(last_locked_until_secs == first_lockup_end, 0); + + delegate_voting_power(delegator, pool_address, voter1_address); + (voter, pending_voter, last_locked_until_secs) = calculate_and_update_voting_delegation( + pool_address, + delegator_address + ); + assert!(voter == delegator_address, 0); + assert!(pending_voter == voter1_address, 0); + assert!(last_locked_until_secs == first_lockup_end, 0); + + // end this lockup cycle + fast_forward_to_unlock(pool_address); + let second_lockup_end = stake::get_lockup_secs(pool_address); + assert!(second_lockup_end > first_lockup_end, 0); + + // voter 1 becomes current voter + (voter, pending_voter, last_locked_until_secs) = calculate_and_update_voting_delegation( + pool_address, + delegator_address + ); + assert!(voter == voter1_address, 0); + assert!(pending_voter == voter1_address, 0); + assert!(last_locked_until_secs == second_lockup_end, 0); + + // delegate to voter 2 which should apply next lockup + delegate_voting_power(delegator, pool_address, voter2_address); + (voter, pending_voter, last_locked_until_secs) = calculate_and_update_voting_delegation( + pool_address, + delegator_address + ); + assert!(voter == voter1_address, 0); + assert!(pending_voter == voter2_address, 0); + assert!(last_locked_until_secs == second_lockup_end, 0); + + // lockup cycle won't be refreshed on the pool anymore + stake::leave_validator_set(validator, pool_address); + end_aptos_epoch(); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_INACTIVE, 0); + + // lockup cycle passes, but validator has no lockup refresh because it is inactive + fast_forward_to_unlock(pool_address); + assert!(second_lockup_end == stake::get_lockup_secs(pool_address), 0); + assert!(second_lockup_end <= reconfiguration::last_reconfiguration_time(), 0); + + // pending voter 2 is not applied + (voter, pending_voter, last_locked_until_secs) = calculate_and_update_voting_delegation( + pool_address, + delegator_address + ); + assert!(voter == voter1_address, 0); + assert!(pending_voter == voter2_address, 0); + assert!(last_locked_until_secs == second_lockup_end, 0); + + // reactivate validator + stake::join_validator_set(validator, pool_address); + end_aptos_epoch(); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 0); + + // lockup cycle of pool has been refreshed again + let third_lockup_end = stake::get_lockup_secs(pool_address); + assert!(third_lockup_end > second_lockup_end, 0); + + // voter 2 finally becomes current voter + (voter, pending_voter, last_locked_until_secs) = calculate_and_update_voting_delegation( + pool_address, + delegator_address + ); + assert!(voter == voter2_address, 0); + assert!(pending_voter == voter2_address, 0); + assert!(last_locked_until_secs == third_lockup_end, 0); + } + + #[test(staker = @0xe256f4f4e2986cada739e339895cf5585082ff247464cab8ec56eea726bd2263)] + public entry fun test_get_expected_stake_pool_address(staker: address) { + let pool_address = get_expected_stake_pool_address(staker, vector[0x42, 0x42]); + assert!(pool_address == @0xe9fc2fbb82b7e1cb7af3daef8c7a24e66780f9122d15e4f1d486ee7c7c36c48d, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x30017, location = Self)] + public entry fun test_delegators_allowlisting_not_supported( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 100 * ONE_APT, true, true); + features::change_feature_flags_for_testing( + aptos_framework, + vector[], + vector[features::get_delegation_pool_allowlisting_feature()], + ); + + enable_delegators_allowlisting(validator); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x30018, location = Self)] + public entry fun test_cannot_disable_allowlisting_if_already_off( + aptos_framework: &signer, + validator: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 100 * ONE_APT, true, true); + + let pool_address = get_owned_pool_address(signer::address_of(validator)); + assert!(!allowlisting_enabled(pool_address), 0); + + disable_delegators_allowlisting(validator); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator_1 = @0x010)] + #[expected_failure(abort_code = 0x30018, location = Self)] + public entry fun test_cannot_allowlist_delegator_if_allowlisting_disabled( + aptos_framework: &signer, + validator: &signer, + delegator_1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 100 * ONE_APT, true, true); + + let pool_address = get_owned_pool_address(signer::address_of(validator)); + assert!(!allowlisting_enabled(pool_address), 0); + + allowlist_delegator(validator, signer::address_of(delegator_1)); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator_1 = @0x010)] + #[expected_failure(abort_code = 0x30018, location = Self)] + public entry fun test_cannot_remove_delegator_from_allowlist_if_allowlisting_disabled( + aptos_framework: &signer, + validator: &signer, + delegator_1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 100 * ONE_APT, true, true); + + let pool_address = get_owned_pool_address(signer::address_of(validator)); + assert!(!allowlisting_enabled(pool_address), 0); + + remove_delegator_from_allowlist(validator, signer::address_of(delegator_1)); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator_1 = @0x010)] + #[expected_failure(abort_code = 0x30018, location = Self)] + public entry fun test_cannot_evict_delegator_if_allowlisting_disabled( + aptos_framework: &signer, + validator: &signer, + delegator_1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 100 * ONE_APT, true, true); + + let pool_address = get_owned_pool_address(signer::address_of(validator)); + assert!(!allowlisting_enabled(pool_address), 0); + + evict_delegator(validator, signer::address_of(delegator_1)); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator_1 = @0x010, delegator_2 = @0x020)] + public entry fun test_allowlist_operations_only_e2e( + aptos_framework: &signer, + validator: &signer, + delegator_1: &signer, + delegator_2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 100 * ONE_APT, true, true); + enable_delegation_pool_allowlisting_feature(aptos_framework); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + let delegator_1_address = signer::address_of(delegator_1); + let delegator_2_address = signer::address_of(delegator_2); + + // any address is allowlisted if allowlist is not created + assert!(!allowlisting_enabled(pool_address), 0); + assert!(delegator_allowlisted(pool_address, delegator_1_address), 0); + assert!(delegator_allowlisted(pool_address, delegator_2_address), 0); + + // no address is allowlisted when allowlist is empty + enable_delegators_allowlisting(validator); + assert!(!delegator_allowlisted(pool_address, delegator_1_address), 0); + assert!(!delegator_allowlisted(pool_address, delegator_2_address), 0); + let allowlist = &get_delegators_allowlist(pool_address); + assert!(vector::length(allowlist) == 0, 0); + + allowlist_delegator(validator, delegator_1_address); + assert!(delegator_allowlisted(pool_address, delegator_1_address), 0); + assert!(!delegator_allowlisted(pool_address, delegator_2_address), 0); + allowlist = &get_delegators_allowlist(pool_address); + assert!(vector::length(allowlist) == 1 && vector::contains(allowlist, &delegator_1_address), 0); + + allowlist_delegator(validator, delegator_2_address); + assert!(delegator_allowlisted(pool_address, delegator_1_address), 0); + assert!(delegator_allowlisted(pool_address, delegator_2_address), 0); + allowlist = &get_delegators_allowlist(pool_address); + assert!(vector::length(allowlist) == 2 && + vector::contains(allowlist, &delegator_1_address) && + vector::contains(allowlist, &delegator_2_address), + 0 + ); + + remove_delegator_from_allowlist(validator, delegator_2_address); + assert!(delegator_allowlisted(pool_address, delegator_1_address), 0); + assert!(!delegator_allowlisted(pool_address, delegator_2_address), 0); + allowlist = &get_delegators_allowlist(pool_address); + assert!(vector::length(allowlist) == 1 && vector::contains(allowlist, &delegator_1_address), 0); + + // destroy the allowlist constructed so far + disable_delegators_allowlisting(validator); + assert!(!allowlisting_enabled(pool_address), 0); + assert!(delegator_allowlisted(pool_address, delegator_1_address), 0); + assert!(delegator_allowlisted(pool_address, delegator_2_address), 0); + + enable_delegators_allowlisting(validator); + assert!(!delegator_allowlisted(pool_address, delegator_1_address), 0); + assert!(!delegator_allowlisted(pool_address, delegator_2_address), 0); + + allowlist_delegator(validator, delegator_2_address); + assert!(!delegator_allowlisted(pool_address, delegator_1_address), 0); + assert!(delegator_allowlisted(pool_address, delegator_2_address), 0); + allowlist = &get_delegators_allowlist(pool_address); + assert!(vector::length(allowlist) == 1 && vector::contains(allowlist, &delegator_2_address), 0); + + // allowlist does not ever have duplicates + allowlist_delegator(validator, delegator_2_address); + allowlist = &get_delegators_allowlist(pool_address); + assert!(vector::length(allowlist) == 1 && vector::contains(allowlist, &delegator_2_address), 0); + + // no override of existing allowlist when enabling allowlisting again + enable_delegators_allowlisting(validator); + allowlist = &get_delegators_allowlist(pool_address); + assert!(vector::length(allowlist) == 1 && vector::contains(allowlist, &delegator_2_address), 0); + + // nothing changes when trying to remove an inexistent delegator + remove_delegator_from_allowlist(validator, delegator_1_address); + allowlist = &get_delegators_allowlist(pool_address); + assert!(vector::length(allowlist) == 1 && vector::contains(allowlist, &delegator_2_address), 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator_1 = @0x010)] + #[expected_failure(abort_code = 0x3001a, location = Self)] + public entry fun test_cannot_evict_explicitly_allowlisted_delegator( + aptos_framework: &signer, + validator: &signer, + delegator_1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 100 * ONE_APT, true, true); + enable_delegation_pool_allowlisting_feature(aptos_framework); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + enable_delegators_allowlisting(validator); + assert!(allowlisting_enabled(pool_address), 0); + + let delegator_1_address = signer::address_of(delegator_1); + allowlist_delegator(validator, delegator_1_address); + + assert!(delegator_allowlisted(pool_address, delegator_1_address), 0); + evict_delegator(validator, delegator_1_address); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator_1 = @0x010)] + #[expected_failure(abort_code = 0x1001b, location = Self)] + public entry fun test_cannot_evict_null_address( + aptos_framework: &signer, + validator: &signer, + delegator_1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 100 * ONE_APT, true, true); + enable_delegation_pool_allowlisting_feature(aptos_framework); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_1_address = signer::address_of(delegator_1); + account::create_account_for_test(delegator_1_address); + + // add some active shares to NULL_SHAREHOLDER from `add_stake` fee + stake::mint(delegator_1, 50 * ONE_APT); + add_stake(delegator_1, pool_address, 50 * ONE_APT); + assert!(get_delegator_active_shares(borrow_global(pool_address), NULL_SHAREHOLDER) != 0, 0); + + enable_delegators_allowlisting(validator); + evict_delegator(validator, NULL_SHAREHOLDER); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator_1 = @0x010)] + #[expected_failure(abort_code = 0x50019, location = Self)] + public entry fun test_cannot_add_stake_if_not_allowlisted( + aptos_framework: &signer, + validator: &signer, + delegator_1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 100 * ONE_APT, true, true); + enable_delegation_pool_allowlisting_feature(aptos_framework); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_1_address = signer::address_of(delegator_1); + account::create_account_for_test(delegator_1_address); + + // allowlisting not enabled yet + assert!(!allowlisting_enabled(pool_address), 0); + assert!(delegator_allowlisted(pool_address, delegator_1_address), 0); + + stake::mint(delegator_1, 30 * ONE_APT); + add_stake(delegator_1, pool_address, 20 * ONE_APT); + + end_aptos_epoch(); + assert_delegation(delegator_1_address, pool_address, 20 * ONE_APT, 0, 0); + + // allowlist is created but has no address added + enable_delegators_allowlisting(validator); + assert!(allowlisting_enabled(pool_address), 0); + assert!(!delegator_allowlisted(pool_address, delegator_1_address), 0); + + add_stake(delegator_1, pool_address, 10 * ONE_APT); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator_1 = @0x010)] + #[expected_failure(abort_code = 0x50019, location = Self)] + public entry fun test_cannot_reactivate_stake_if_not_allowlisted( + aptos_framework: &signer, + validator: &signer, + delegator_1: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 100 * ONE_APT, true, true); + enable_delegation_pool_allowlisting_feature(aptos_framework); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_1_address = signer::address_of(delegator_1); + account::create_account_for_test(delegator_1_address); + + // allowlist is created but has no address added + enable_delegators_allowlisting(validator); + // allowlist delegator + allowlist_delegator(validator, delegator_1_address); + assert!(delegator_allowlisted(pool_address, delegator_1_address), 0); + + // delegator is allowed to add stake + stake::mint(delegator_1, 50 * ONE_APT); + add_stake(delegator_1, pool_address, 50 * ONE_APT); + + // restore `add_stake` fee back to delegator + end_aptos_epoch(); + assert_delegation(delegator_1_address, pool_address, 50 * ONE_APT, 0, 0); + + // some of the stake is unlocked by the delegator + unlock(delegator_1, pool_address, 30 * ONE_APT); + assert_delegation(delegator_1_address, pool_address, 20 * ONE_APT, 0, 2999999999); + + // remove delegator from allowlist + remove_delegator_from_allowlist(validator, delegator_1_address); + assert!(!delegator_allowlisted(pool_address, delegator_1_address), 0); + + // remaining stake is unlocked by the pool owner by evicting the delegator + evict_delegator(validator, delegator_1_address); + assert_delegation(delegator_1_address, pool_address, 0, 0, 4999999999); + + // delegator cannot reactivate stake + reactivate_stake(delegator_1, pool_address, 50 * ONE_APT); + assert_delegation(delegator_1_address, pool_address, 0, 0, 4999999999); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, delegator_1 = @0x010, delegator_2 = @0x020)] + public entry fun test_delegation_pool_allowlisting_e2e( + aptos_framework: &signer, + validator: &signer, + delegator_1: &signer, + delegator_2: &signer, + ) acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test(aptos_framework); + initialize_test_validator(validator, 100 * ONE_APT, true, true); + enable_delegation_pool_allowlisting_feature(aptos_framework); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + + let delegator_1_address = signer::address_of(delegator_1); + account::create_account_for_test(delegator_1_address); + let delegator_2_address = signer::address_of(delegator_2); + account::create_account_for_test(delegator_2_address); + + // add stake while allowlisting is disabled + assert!(!allowlisting_enabled(pool_address), 0); + stake::mint(delegator_1, 100 * ONE_APT); + stake::mint(delegator_2, 100 * ONE_APT); + add_stake(delegator_1, pool_address, 50 * ONE_APT); + add_stake(delegator_2, pool_address, 30 * ONE_APT); + + end_aptos_epoch(); + assert_delegation(delegator_1_address, pool_address, 50 * ONE_APT, 0, 0); + assert_delegation(delegator_2_address, pool_address, 30 * ONE_APT, 0, 0); + + // create allowlist + enable_delegators_allowlisting(validator); + assert!(allowlisting_enabled(pool_address), 0); + assert!(!delegator_allowlisted(pool_address, delegator_1_address), 0); + assert!(!delegator_allowlisted(pool_address, delegator_2_address), 0); + + allowlist_delegator(validator, delegator_1_address); + assert!(delegator_allowlisted(pool_address, delegator_1_address), 0); + assert!(!delegator_allowlisted(pool_address, delegator_2_address), 0); + + // evict delegator 2 which unlocks their entire active stake + evict_delegator(validator, delegator_2_address); + assert_delegation(delegator_2_address, pool_address, 0, 0, 30 * ONE_APT); + + end_aptos_epoch(); + // 5000000000 * 1.01 active + assert_delegation(delegator_1_address, pool_address, 5050000000, 0, 0); + // 3000000000 * 1.01 pending-inactive + assert_delegation(delegator_2_address, pool_address, 0, 0, 3030000000); + + // can add stake when allowlisted + add_stake(delegator_1, pool_address, 10 * ONE_APT); + end_aptos_epoch(); + // 5050000000 * 1.01 + 1000000000 active + assert_delegation(delegator_1_address, pool_address, 6100500000, 0, 0); + // 3030000000 * 1.01 pending-inactive + assert_delegation(delegator_2_address, pool_address, 0, 0, 3060300000); + + end_aptos_epoch(); + // 6100500000 * 1.01 active + assert_delegation(delegator_1_address, pool_address, 6161505000, 0, 0); + // 3060300000 * 1.01 pending-inactive + assert_delegation(delegator_2_address, pool_address, 0, 0, 3090903000); + + remove_delegator_from_allowlist(validator, delegator_1_address); + assert!(!delegator_allowlisted(pool_address, delegator_1_address), 0); + + // check that in-flight active rewards are evicted too, which validates that `synchronize_delegation_pool` was called + let active = pool_u64::balance( + &borrow_global(pool_address).active_shares, + delegator_1_address + ) + get_add_stake_fee(pool_address, 10 * ONE_APT); + // 5050000000 + 1000000000 active at last `synchronize_delegation_pool` + assert!(active == 6050000000, active); + + evict_delegator(validator, delegator_1_address); + assert_delegation(delegator_1_address, pool_address, 0, 0, 6161504999); + let pending_inactive = pool_u64::balance( + pending_inactive_shares_pool(borrow_global(pool_address)), + delegator_1_address + ); + assert!(pending_inactive == 6161504999, pending_inactive); + + // allowlist delegator 1 back and check that they can add stake + allowlist_delegator(validator, delegator_1_address); + add_stake(delegator_1, pool_address, 20 * ONE_APT); + end_aptos_epoch(); + // 2000000000 active and 6161505000 * 1.01 pending-inactive + assert_delegation(delegator_1_address, pool_address, 20 * ONE_APT, 0, 6223120049); + + // can reactivate stake when allowlisted + reactivate_stake(delegator_1, pool_address, 5223120050); + assert_delegation(delegator_1_address, pool_address, 20 * ONE_APT + 5223120049, 0, 10 * ONE_APT); + + // evict delegator 1 after they reactivated + remove_delegator_from_allowlist(validator, delegator_1_address); + evict_delegator(validator, delegator_1_address); + // 2000000000 + 5223120050 + 1000000000 pending-inactive + assert_delegation(delegator_1_address, pool_address, 0, 0, 8223120049); + + end_aptos_epoch(); + // (2000000000 + 5223120050 + 1000000000) * 1.01 pending-inactive + assert_delegation(delegator_1_address, pool_address, 0, 0, 8305351249); + } + + #[test_only] + public fun assert_delegation( + delegator_address: address, + pool_address: address, + active_stake: u64, + inactive_stake: u64, + pending_inactive_stake: u64, + ) acquires DelegationPool, BeneficiaryForOperator { + let (actual_active, actual_inactive, actual_pending_inactive) = get_stake(pool_address, delegator_address); + assert!(actual_active == active_stake, actual_active); + assert!(actual_inactive == inactive_stake, actual_inactive); + assert!(actual_pending_inactive == pending_inactive_stake, actual_pending_inactive); + } + + #[test_only] + public fun assert_pending_withdrawal( + delegator_address: address, + pool_address: address, + exists: bool, + olc: u64, + inactive: bool, + stake: u64, + ) acquires DelegationPool { + assert_delegation_pool_exists(pool_address); + let pool = borrow_global(pool_address); + let (withdrawal_exists, withdrawal_olc) = pending_withdrawal_exists(pool, delegator_address); + assert!(withdrawal_exists == exists, 0); + assert!(withdrawal_olc.index == olc, withdrawal_olc.index); + let (withdrawal_inactive, withdrawal_stake) = get_pending_withdrawal(pool_address, delegator_address); + assert!(withdrawal_inactive == inactive, 0); + assert!(withdrawal_stake == stake, withdrawal_stake); + } + + #[test_only] + public fun assert_inactive_shares_pool( + pool_address: address, + olc: u64, + exists: bool, + stake: u64, + ) acquires DelegationPool { + assert_delegation_pool_exists(pool_address); + let pool = borrow_global(pool_address); + assert!(table::contains(&pool.inactive_shares, olc_with_index(olc)) == exists, 0); + if (exists) { + let actual_stake = total_coins(table::borrow(&pool.inactive_shares, olc_with_index(olc))); + assert!(actual_stake == stake, actual_stake); + } else { + assert!(0 == stake, 0); + } + } + + #[test_only] + public fun setup_vote( + aptos_framework: &signer, + validator: &signer, + enable_partial_voting: bool, + ): u64 acquires DelegationPoolOwnership, DelegationPool, GovernanceRecords, BeneficiaryForOperator, NextCommissionPercentage, DelegationPoolAllowlisting { + initialize_for_test_no_reward(aptos_framework); + aptos_governance::initialize_for_test( + aptos_framework, + (10 * ONE_APT as u128), + 100 * ONE_APT, + 1000, + ); + aptos_governance::initialize_partial_voting(aptos_framework); + + initialize_test_validator(validator, 100 * ONE_APT, true, false); + + let validator_address = signer::address_of(validator); + let pool_address = get_owned_pool_address(validator_address); + // Delegation pool is created before partial governance voting feature flag is enabled. So this delegation + // pool's voter is its owner. + assert!(stake::get_delegated_voter(pool_address) == validator_address, 1); + assert!(!partial_governance_voting_enabled(pool_address), 1); + end_aptos_epoch(); + + // Create 1 proposals and vote for proposal1. + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let proposal_id = aptos_governance::create_proposal_v2_impl( + validator, + pool_address, + execution_hash, + b"", + b"", + true, + ); + if (enable_partial_voting) { + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_partial_governance_voting( + ), features::get_delegation_pool_partial_governance_voting()], + vector[]); + enable_partial_governance_voting(pool_address); + }; + proposal_id + } + + #[test_only] + public fun total_coins_inactive(pool_address: address): u64 acquires DelegationPool { + borrow_global(pool_address).total_coins_inactive + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/dispatchable_fungible_asset.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/dispatchable_fungible_asset.move new file mode 100644 index 000000000..aa843a38f --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/dispatchable_fungible_asset.move @@ -0,0 +1,194 @@ +/// This defines the fungible asset module that can issue fungible asset of any `Metadata` object. The +/// metadata object can be any object that equipped with `Metadata` resource. +/// +/// The dispatchable_fungible_asset wraps the existing fungible_asset module and adds the ability for token issuer +/// to customize the logic for withdraw and deposit operations. For example: +/// +/// - Deflation token: a fixed percentage of token will be destructed upon transfer. +/// - Transfer allowlist: token can only be transfered to addresses in the allow list. +/// - Predicated transfer: transfer can only happen when some certain predicate has been met. +/// - Loyalty token: a fixed loyalty will be paid to a designated address when a fungible asset transfer happens +/// +/// The api listed here intended to be an in-place replacement for defi applications that uses fungible_asset api directly +/// and is safe for non-dispatchable (aka vanilla) fungible assets as well. +/// +/// See AIP-73 for further discussion +/// +module aptos_framework::dispatchable_fungible_asset { + use aptos_framework::fungible_asset::{Self, FungibleAsset, TransferRef}; + use aptos_framework::function_info::{Self, FunctionInfo}; + use aptos_framework::object::{Self, ConstructorRef, Object}; + + use std::error; + use std::features; + use std::option::{Self, Option}; + + /// TransferRefStore doesn't exist on the fungible asset type. + const ESTORE_NOT_FOUND: u64 = 1; + /// Recipient is not getting the guaranteed value; + const EAMOUNT_MISMATCH: u64 = 2; + /// Feature is not activated yet on the network. + const ENOT_ACTIVATED: u64 = 3; + /// Dispatch target is not loaded. + const ENOT_LOADED: u64 = 4; + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + struct TransferRefStore has key { + transfer_ref: TransferRef + } + + public fun register_dispatch_functions( + constructor_ref: &ConstructorRef, + withdraw_function: Option, + deposit_function: Option, + derived_balance_function: Option, + ) { + fungible_asset::register_dispatch_functions( + constructor_ref, + withdraw_function, + deposit_function, + derived_balance_function, + ); + let store_obj = &object::generate_signer(constructor_ref); + move_to( + store_obj, + TransferRefStore { + transfer_ref: fungible_asset::generate_transfer_ref(constructor_ref), + } + ); + } + + /// Withdraw `amount` of the fungible asset from `store` by the owner. + /// + /// The semantics of deposit will be governed by the function specified in DispatchFunctionStore. + public fun withdraw( + owner: &signer, + store: Object, + amount: u64, + ): FungibleAsset acquires TransferRefStore { + fungible_asset::withdraw_sanity_check(owner, store, false); + let func_opt = fungible_asset::withdraw_dispatch_function(store); + if (option::is_some(&func_opt)) { + assert!( + features::dispatchable_fungible_asset_enabled(), + error::aborted(ENOT_ACTIVATED) + ); + let start_balance = fungible_asset::balance(store); + let func = option::borrow(&func_opt); + function_info::load_module_from_function(func); + let fa = dispatchable_withdraw( + store, + amount, + borrow_transfer_ref(store), + func, + ); + let end_balance = fungible_asset::balance(store); + assert!(amount <= start_balance - end_balance, error::aborted(EAMOUNT_MISMATCH)); + fa + } else { + fungible_asset::withdraw_internal(object::object_address(&store), amount) + } + } + + /// Deposit `amount` of the fungible asset to `store`. + /// + /// The semantics of deposit will be governed by the function specified in DispatchFunctionStore. + public fun deposit(store: Object, fa: FungibleAsset) acquires TransferRefStore { + fungible_asset::deposit_sanity_check(store, false); + let func_opt = fungible_asset::deposit_dispatch_function(store); + if (option::is_some(&func_opt)) { + assert!( + features::dispatchable_fungible_asset_enabled(), + error::aborted(ENOT_ACTIVATED) + ); + let func = option::borrow(&func_opt); + function_info::load_module_from_function(func); + dispatchable_deposit( + store, + fa, + borrow_transfer_ref(store), + func + ) + } else { + fungible_asset::deposit_internal(object::object_address(&store), fa) + } + } + + /// Transfer an `amount` of fungible asset from `from_store`, which should be owned by `sender`, to `receiver`. + /// Note: it does not move the underlying object. + public entry fun transfer( + sender: &signer, + from: Object, + to: Object, + amount: u64, + ) acquires TransferRefStore { + let fa = withdraw(sender, from, amount); + deposit(to, fa); + } + + /// Transfer an `amount` of fungible asset from `from_store`, which should be owned by `sender`, to `receiver`. + /// The recipient is guranteed to receive asset greater than the expected amount. + /// Note: it does not move the underlying object. + public entry fun transfer_assert_minimum_deposit( + sender: &signer, + from: Object, + to: Object, + amount: u64, + expected: u64 + ) acquires TransferRefStore { + let start = fungible_asset::balance(to); + let fa = withdraw(sender, from, amount); + deposit(to, fa); + let end = fungible_asset::balance(to); + assert!(end - start >= expected, error::aborted(EAMOUNT_MISMATCH)); + } + + #[view] + /// Get the derived value of store using the overloaded hook. + /// + /// The semantics of value will be governed by the function specified in DispatchFunctionStore. + public fun derived_balance(store: Object): u64 { + let func_opt = fungible_asset::derived_balance_dispatch_function(store); + if (option::is_some(&func_opt)) { + assert!( + features::dispatchable_fungible_asset_enabled(), + error::aborted(ENOT_ACTIVATED) + ); + let func = option::borrow(&func_opt); + function_info::load_module_from_function(func); + dispatchable_derived_balance(store, func) + } else { + fungible_asset::balance(store) + } + } + + inline fun borrow_transfer_ref(metadata: Object): &TransferRef acquires TransferRefStore { + let metadata_addr = object::object_address( + &fungible_asset::store_metadata(metadata) + ); + assert!( + exists(metadata_addr), + error::not_found(ESTORE_NOT_FOUND) + ); + &borrow_global(metadata_addr).transfer_ref + } + + native fun dispatchable_withdraw( + store: Object, + amount: u64, + transfer_ref: &TransferRef, + function: &FunctionInfo, + ): FungibleAsset; + + native fun dispatchable_deposit( + store: Object, + fa: FungibleAsset, + transfer_ref: &TransferRef, + function: &FunctionInfo, + ); + + native fun dispatchable_derived_balance( + store: Object, + function: &FunctionInfo, + ): u64; +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/dkg.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/dkg.move new file mode 100644 index 000000000..8e55ccb2a --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/dkg.move @@ -0,0 +1,121 @@ +/// DKG on-chain states and helper functions. +module aptos_framework::dkg { + use std::error; + use std::option; + use std::option::Option; + use aptos_framework::event::emit; + use aptos_framework::randomness_config::RandomnessConfig; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + use aptos_framework::validator_consensus_info::ValidatorConsensusInfo; + friend aptos_framework::block; + friend aptos_framework::reconfiguration_with_dkg; + + const EDKG_IN_PROGRESS: u64 = 1; + const EDKG_NOT_IN_PROGRESS: u64 = 2; + + /// This can be considered as the public input of DKG. + struct DKGSessionMetadata has copy, drop, store { + dealer_epoch: u64, + randomness_config: RandomnessConfig, + dealer_validator_set: vector, + target_validator_set: vector, + } + + #[event] + struct DKGStartEvent has drop, store { + session_metadata: DKGSessionMetadata, + start_time_us: u64, + } + + /// The input and output of a DKG session. + /// The validator set of epoch `x` works together for an DKG output for the target validator set of epoch `x+1`. + struct DKGSessionState has copy, store, drop { + metadata: DKGSessionMetadata, + start_time_us: u64, + transcript: vector, + } + + /// The completed and in-progress DKG sessions. + struct DKGState has key { + last_completed: Option, + in_progress: Option, + } + + /// Called in genesis to initialize on-chain states. + public fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + if (!exists(@aptos_framework)) { + move_to( + aptos_framework, + DKGState { + last_completed: std::option::none(), + in_progress: std::option::none(), + } + ); + } + } + + /// Mark on-chain DKG state as in-progress. Notify validators to start DKG. + /// Abort if a DKG is already in progress. + public(friend) fun start( + dealer_epoch: u64, + randomness_config: RandomnessConfig, + dealer_validator_set: vector, + target_validator_set: vector, + ) acquires DKGState { + let dkg_state = borrow_global_mut(@aptos_framework); + let new_session_metadata = DKGSessionMetadata { + dealer_epoch, + randomness_config, + dealer_validator_set, + target_validator_set, + }; + let start_time_us = timestamp::now_microseconds(); + dkg_state.in_progress = std::option::some(DKGSessionState { + metadata: new_session_metadata, + start_time_us, + transcript: vector[], + }); + + emit(DKGStartEvent { + start_time_us, + session_metadata: new_session_metadata, + }); + } + + /// Put a transcript into the currently incomplete DKG session, then mark it completed. + /// + /// Abort if DKG is not in progress. + public(friend) fun finish(transcript: vector) acquires DKGState { + let dkg_state = borrow_global_mut(@aptos_framework); + assert!(option::is_some(&dkg_state.in_progress), error::invalid_state(EDKG_NOT_IN_PROGRESS)); + let session = option::extract(&mut dkg_state.in_progress); + session.transcript = transcript; + dkg_state.last_completed = option::some(session); + dkg_state.in_progress = option::none(); + } + + /// Delete the currently incomplete session, if it exists. + public fun try_clear_incomplete_session(fx: &signer) acquires DKGState { + system_addresses::assert_aptos_framework(fx); + if (exists(@aptos_framework)) { + let dkg_state = borrow_global_mut(@aptos_framework); + dkg_state.in_progress = option::none(); + } + } + + /// Return the incomplete DKG session state, if it exists. + public fun incomplete_session(): Option acquires DKGState { + if (exists(@aptos_framework)) { + borrow_global(@aptos_framework).in_progress + } else { + option::none() + } + } + + /// Return the dealer epoch of a `DKGSessionState`. + public fun session_dealer_epoch(session: &DKGSessionState): u64 { + session.metadata.dealer_epoch + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/ethereum.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/ethereum.move new file mode 100644 index 000000000..0c883393c --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/ethereum.move @@ -0,0 +1,193 @@ +module aptos_framework::ethereum { + use std::vector; + use aptos_std::aptos_hash::keccak256; + + /// Constants for ASCII character codes + const ASCII_A: u8 = 0x41; + const ASCII_Z: u8 = 0x5A; + const ASCII_A_LOWERCASE: u8 = 0x61; + const ASCII_F_LOWERCASE: u8 = 0x66; + + // Error codes + + const EINVALID_LENGTH: u64 = 1; + + /// Represents an Ethereum address within Aptos smart contracts. + /// Provides structured handling, storage, and validation of Ethereum addresses. + struct EthereumAddress has store, copy, drop { + inner: vector, + } + + /// Validates an Ethereum address against EIP-55 checksum rules and returns a new `EthereumAddress`. + /// + /// @param ethereum_address A 40-byte vector of unsigned 8-bit integers (hexadecimal format). + /// @return A validated `EthereumAddress` struct. + /// @abort If the address does not conform to EIP-55 standards. + public fun ethereum_address(ethereum_address: vector): EthereumAddress { + assert_eip55(ðereum_address); + EthereumAddress { inner: ethereum_address } + } + + /// Returns a new `EthereumAddress` without EIP-55 validation. + /// + /// @param ethereum_address A 40-byte vector of unsigned 8-bit integers (hexadecimal format). + /// @return A validated `EthereumAddress` struct. + /// @abort If the address does not conform to EIP-55 standards. + public fun ethereum_address_no_eip55(ethereum_address: vector): EthereumAddress { + assert_40_char_hex(ðereum_address); + EthereumAddress { inner: ethereum_address } + } + + /// Returns a new 20-byte `EthereumAddress` without EIP-55 validation. + /// + /// @param ethereum_address A 20-byte vector of unsigned 8-bit bytes. + /// @return An `EthereumAddress` struct. + /// @abort If the address does not conform to EIP-55 standards. + public fun ethereum_address_20_bytes(ethereum_address: vector): EthereumAddress { + assert!(vector::length(ðereum_address) == 20, EINVALID_LENGTH); + EthereumAddress { inner: ethereum_address } + } + + /// Gets the inner vector of an `EthereumAddress`. + /// + /// @param ethereum_address A 40-byte vector of unsigned 8-bit integers (hexadecimal format). + /// @return The vector inner value of the EthereumAddress + public fun get_inner_ethereum_address(ethereum_address: EthereumAddress): vector { + ethereum_address.inner + } + + /// Converts uppercase ASCII characters in a vector to their lowercase equivalents. + /// + /// @param input A reference to a vector of ASCII characters. + /// @return A new vector with lowercase equivalents of the input characters. + /// @note Only affects ASCII letters; non-alphabetic characters are unchanged. + public fun to_lowercase(input: &vector): vector { + let lowercase_bytes = vector::empty(); + vector::enumerate_ref(input, |_i, element| { + let lower_byte = if (*element >= ASCII_A && *element <= ASCII_Z) { + *element + 32 + } else { + *element + }; + vector::push_back(&mut lowercase_bytes, lower_byte); + }); + lowercase_bytes + } + + #[test] + fun test_to_lowercase() { + let upper = b"TeST"; + let lower = b"test"; + assert!(to_lowercase(&upper) == lower, 0); + } + + /// Converts an Ethereum address to EIP-55 checksummed format. + /// + /// @param ethereum_address A 40-character vector representing the Ethereum address in hexadecimal format. + /// @return The EIP-55 checksummed version of the input address. + /// @abort If the input address does not have exactly 40 characters. + /// @note Assumes input address is valid and in lowercase hexadecimal format. + public fun to_eip55_checksumed_address(ethereum_address: &vector): vector { + assert!(vector::length(ethereum_address) == 40, 0); + let lowercase = to_lowercase(ethereum_address); + let hash = keccak256(lowercase); + let output = vector::empty(); + + for (index in 0..40) { + let item = *vector::borrow(ethereum_address, index); + if (item >= ASCII_A_LOWERCASE && item <= ASCII_F_LOWERCASE) { + let hash_item = *vector::borrow(&hash, index / 2); + if ((hash_item >> ((4 * (1 - (index % 2))) as u8)) & 0xF >= 8) { + vector::push_back(&mut output, item - 32); + } else { + vector::push_back(&mut output, item); + } + } else { + vector::push_back(&mut output, item); + } + }; + output + } + + public fun get_inner(eth_address: &EthereumAddress): vector { + eth_address.inner + } + + /// Checks if an Ethereum address conforms to the EIP-55 checksum standard. + /// + /// @param ethereum_address A reference to a 40-character vector of an Ethereum address in hexadecimal format. + /// @abort If the address does not match its EIP-55 checksummed version. + /// @note Assumes the address is correctly formatted as a 40-character hexadecimal string. + public fun assert_eip55(ethereum_address: &vector) { + let eip55 = to_eip55_checksumed_address(ethereum_address); + let len = vector::length(&eip55); + for (index in 0..len) { + assert!(vector::borrow(&eip55, index) == vector::borrow(ethereum_address, index), 0); + }; + } + + /// Checks if an Ethereum address is a nonzero 40-character hexadecimal string. + /// + /// @param ethereum_address A reference to a vector of bytes representing the Ethereum address as characters. + /// @abort If the address is not 40 characters long, contains invalid characters, or is all zeros. + public fun assert_40_char_hex(ethereum_address: &vector) { + let len = vector::length(ethereum_address); + + // Ensure the address is exactly 40 characters long + assert!(len == 40, 1); + + // Ensure the address contains only valid hexadecimal characters + let is_zero = true; + for (index in 0..len) { + let char = *vector::borrow(ethereum_address, index); + + // Check if the character is a valid hexadecimal character (0-9, a-f, A-F) + assert!( + (char >= 0x30 && char <= 0x39) || // '0' to '9' + (char >= 0x41 && char <= 0x46) || // 'A' to 'F' + (char >= 0x61 && char <= 0x66), // 'a' to 'f' + 2 + ); + + // Check if the address is nonzero + if (char != 0x30) { // '0' + is_zero = false; + }; + }; + + // Abort if the address is all zeros + assert!(!is_zero, 3); + } + + #[test_only] + public fun eth_address_20_bytes(): vector { + vector[0x32, 0xBe, 0x34, 0x3B, 0x94, 0xf8, 0x60, 0x12, 0x4d, 0xC4, 0xfE, 0xE2, 0x78, 0xFD, 0xCB, 0xD3, 0x8C, 0x10, 0x2D, 0x88] +} + + #[test_only] + public fun valid_eip55(): vector { + b"32Be343B94f860124dC4fEe278FDCBD38C102D88" + } + + #[test_only] + public fun invalid_eip55(): vector { + b"32be343b94f860124dc4fee278fdcbd38c102d88" + } + + #[test] + fun test_valid_eip55_checksum() { + assert_eip55(&valid_eip55()); + } + + #[test] + #[expected_failure(abort_code = 0, location = Self)] + fun test_invalid_eip55_checksum() { + assert_eip55(&invalid_eip55()); + } + + #[test] + #[expected_failure(abort_code = 0, location = Self)] + fun test_simple_invalid_eip55_checksum() { + assert_eip55(&b"0"); + } +} \ No newline at end of file diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/event.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/event.move new file mode 100644 index 000000000..542808163 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/event.move @@ -0,0 +1,92 @@ +/// The Event module defines an `EventHandleGenerator` that is used to create +/// `EventHandle`s with unique GUIDs. It contains a counter for the number +/// of `EventHandle`s it generates. An `EventHandle` is used to count the number of +/// events emitted to a handle and emit events to the event store. +module aptos_framework::event { + use std::bcs; + + use aptos_framework::guid::GUID; + + friend aptos_framework::account; + friend aptos_framework::object; + + /// Emit a module event with payload `msg`. + public fun emit(msg: T) { + write_module_event_to_store(msg); + } + + /// Log `msg` with the event stream identified by `T` + native fun write_module_event_to_store(msg: T); + + #[test_only] + public native fun emitted_events(): vector; + + #[test_only] + public fun was_event_emitted(msg: &T): bool { + use std::vector; + vector::contains(&emitted_events(), msg) + } + + #[deprecated] + /// A handle for an event such that: + /// 1. Other modules can emit events to this handle. + /// 2. Storage can use this handle to prove the total number of events that happened in the past. + struct EventHandle has store { + /// Total number of events emitted to this event stream. + counter: u64, + /// A globally unique ID for this event stream. + guid: GUID, + } + + #[deprecated] + /// Use EventHandleGenerator to generate a unique event handle for `sig` + public(friend) fun new_event_handle(guid: GUID): EventHandle { + EventHandle { + counter: 0, + guid, + } + } + + #[deprecated] + /// Emit an event with payload `msg` by using `handle_ref`'s key and counter. + public fun emit_event(handle_ref: &mut EventHandle, msg: T) { + write_to_event_store(bcs::to_bytes(&handle_ref.guid), handle_ref.counter, msg); + spec { + assume handle_ref.counter + 1 <= MAX_U64; + }; + handle_ref.counter = handle_ref.counter + 1; + } + + #[deprecated] + /// Return the GUID associated with this EventHandle + public fun guid(handle_ref: &EventHandle): &GUID { + &handle_ref.guid + } + + #[deprecated] + /// Return the current counter associated with this EventHandle + public fun counter(handle_ref: &EventHandle): u64 { + handle_ref.counter + } + + #[deprecated] + /// Log `msg` as the `count`th event associated with the event stream identified by `guid` + native fun write_to_event_store(guid: vector, count: u64, msg: T); + + #[deprecated] + /// Destroy a unique handle. + public fun destroy_handle(handle: EventHandle) { + EventHandle { counter: _, guid: _ } = handle; + } + + #[deprecated] + #[test_only] + public native fun emitted_events_by_handle(handle: &EventHandle): vector; + + #[deprecated] + #[test_only] + public fun was_event_emitted_by_handle(handle: &EventHandle, msg: &T): bool { + use std::vector; + vector::contains(&emitted_events_by_handle(handle), msg) + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/execution_config.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/execution_config.move new file mode 100644 index 000000000..6322a6cfe --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/execution_config.move @@ -0,0 +1,66 @@ +/// Maintains the execution config for the blockchain. The config is stored in a +/// Reconfiguration, and may be updated by root. +module aptos_framework::execution_config { + use aptos_framework::config_buffer; + use std::error; + use std::vector; + use aptos_framework::chain_status; + + use aptos_framework::reconfiguration; + use aptos_framework::system_addresses; + friend aptos_framework::genesis; + friend aptos_framework::reconfiguration_with_dkg; + + struct ExecutionConfig has drop, key, store { + config: vector, + } + + /// The provided on chain config bytes are empty or invalid + const EINVALID_CONFIG: u64 = 1; + + /// Deprecated by `set_for_next_epoch()`. + /// + /// WARNING: calling this while randomness is enabled will trigger a new epoch without randomness! + /// + /// TODO: update all the tests that reference this function, then disable this function. + public fun set(account: &signer, config: vector) acquires ExecutionConfig { + system_addresses::assert_aptos_framework(account); + chain_status::assert_genesis(); + + assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG)); + + if (exists(@aptos_framework)) { + let config_ref = &mut borrow_global_mut(@aptos_framework).config; + *config_ref = config; + } else { + move_to(account, ExecutionConfig { config }); + }; + // Need to trigger reconfiguration so validator nodes can sync on the updated configs. + reconfiguration::reconfigure(); + } + + /// This can be called by on-chain governance to update on-chain execution configs for the next epoch. + /// Example usage: + /// ``` + /// aptos_framework::execution_config::set_for_next_epoch(&framework_signer, some_config_bytes); + /// aptos_framework::aptos_governance::reconfigure(&framework_signer); + /// ``` + public fun set_for_next_epoch(account: &signer, config: vector) { + system_addresses::assert_aptos_framework(account); + assert!(vector::length(&config) > 0, error::invalid_argument(EINVALID_CONFIG)); + config_buffer::upsert(ExecutionConfig { config }); + } + + /// Only used in reconfigurations to apply the pending `ExecutionConfig`, if there is any. + public(friend) fun on_new_epoch(framework: &signer) acquires ExecutionConfig { + system_addresses::assert_aptos_framework(framework); + if (config_buffer::does_exist()) { + let config = config_buffer::extract(); + if (exists(@aptos_framework)) { + *borrow_global_mut(@aptos_framework) = config; + } else { + move_to(framework, config); + }; + } + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/function_info.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/function_info.move new file mode 100644 index 000000000..c7f78c11d --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/function_info.move @@ -0,0 +1,100 @@ +/// The `function_info` module defines the `FunctionInfo` type which simulates a function pointer. +module aptos_framework::function_info { + use std::error; + use std::features; + use std::signer; + use std::string::{Self, String}; + + friend aptos_framework::fungible_asset; + friend aptos_framework::dispatchable_fungible_asset; + + /// String is not a valid Move identifier + const EINVALID_IDENTIFIER: u64 = 1; + /// Function specified in the FunctionInfo doesn't exist on chain. + const EINVALID_FUNCTION: u64 = 2; + /// Feature hasn't been activated yet. + const ENOT_ACTIVATED: u64 = 3; + + /// A `String` holds a sequence of bytes which is guaranteed to be in utf8 format. + struct FunctionInfo has copy, drop, store { + module_address: address, + module_name: String, + function_name: String, + } + + /// Creates a new function info from names. + public fun new_function_info( + module_signer: &signer, + module_name: String, + function_name: String, + ): FunctionInfo { + new_function_info_from_address( + signer::address_of(module_signer), + module_name, + function_name, + ) + } + + public(friend) fun new_function_info_from_address( + module_address: address, + module_name: String, + function_name: String, + ): FunctionInfo { + assert!( + is_identifier(string::bytes(&module_name)), + EINVALID_IDENTIFIER + ); + assert!( + is_identifier(string::bytes(&function_name)), + EINVALID_IDENTIFIER + ); + FunctionInfo { + module_address, + module_name, + function_name, + } + } + + /// Check if the dispatch target function meets the type requirements of the disptach entry point. + /// + /// framework_function is the dispatch native function defined in the aptos_framework. + /// dispatch_target is the function passed in by the user. + /// + /// dispatch_target should have the same signature (same argument type, same generics constraint) except + /// that the framework_function will have a `&FunctionInfo` in the last argument that will instruct the VM which + /// function to jump to. + /// + /// dispatch_target also needs to be public so the type signature will remain unchanged. + public(friend) fun check_dispatch_type_compatibility( + framework_function: &FunctionInfo, + dispatch_target: &FunctionInfo, + ): bool { + assert!( + features::dispatchable_fungible_asset_enabled(), + error::aborted(ENOT_ACTIVATED) + ); + load_function_impl(dispatch_target); + check_dispatch_type_compatibility_impl(framework_function, dispatch_target) + } + + /// Load up a function into VM's loader and charge for its dependencies + /// + /// It is **critical** to make sure that this function is invoked before `check_dispatch_type_compatibility` + /// or performing any other dispatching logic to ensure: + /// 1. We properly charge gas for the function to dispatch. + /// 2. The function is loaded in the cache so that we can perform further type checking/dispatching logic. + /// + /// Calling `check_dispatch_type_compatibility_impl` or dispatch without loading up the module would yield an error + /// if such module isn't accessed previously in the transaction. + public(friend) fun load_module_from_function(f: &FunctionInfo) { + load_function_impl(f) + } + + native fun check_dispatch_type_compatibility_impl(lhs: &FunctionInfo, r: &FunctionInfo): bool; + native fun is_identifier(s: &vector): bool; + native fun load_function_impl(f: &FunctionInfo); + + // Test only dependencies so we can invoke those friend functions. + #[test_only] + friend aptos_framework::function_info_tests; +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/fungible_asset.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/fungible_asset.move new file mode 100644 index 000000000..194cf32d9 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/fungible_asset.move @@ -0,0 +1,1502 @@ +/// This defines the fungible asset module that can issue fungible asset of any `Metadata` object. The +/// metadata object can be any object that equipped with `Metadata` resource. +module aptos_framework::fungible_asset { + use aptos_framework::aggregator_v2::{Self, Aggregator}; + use aptos_framework::create_signer; + use aptos_framework::event; + use aptos_framework::function_info::{Self, FunctionInfo}; + use aptos_framework::object::{Self, Object, ConstructorRef, DeleteRef, ExtendRef}; + use std::string; + use std::features; + + use std::error; + use std::option::{Self, Option}; + use std::signer; + use std::string::String; + + friend aptos_framework::coin; + friend aptos_framework::primary_fungible_store; + friend aptos_framework::aptos_account; + + friend aptos_framework::dispatchable_fungible_asset; + friend aptos_framework::governed_gas_pool; + + /// Amount cannot be zero. + const EAMOUNT_CANNOT_BE_ZERO: u64 = 1; + /// The transfer ref and the fungible asset do not match. + const ETRANSFER_REF_AND_FUNGIBLE_ASSET_MISMATCH: u64 = 2; + /// Store is disabled from sending and receiving this fungible asset. + const ESTORE_IS_FROZEN: u64 = 3; + /// Insufficient balance to withdraw or transfer. + const EINSUFFICIENT_BALANCE: u64 = 4; + /// The fungible asset's supply has exceeded maximum. + const EMAX_SUPPLY_EXCEEDED: u64 = 5; + /// Fungible asset do not match when merging. + const EFUNGIBLE_ASSET_MISMATCH: u64 = 6; + /// The mint ref and the store do not match. + const EMINT_REF_AND_STORE_MISMATCH: u64 = 7; + /// Account is not the store's owner. + const ENOT_STORE_OWNER: u64 = 8; + /// Transfer ref and store do not match. + const ETRANSFER_REF_AND_STORE_MISMATCH: u64 = 9; + /// Burn ref and store do not match. + const EBURN_REF_AND_STORE_MISMATCH: u64 = 10; + /// Fungible asset and store do not match. + const EFUNGIBLE_ASSET_AND_STORE_MISMATCH: u64 = 11; + /// Cannot destroy non-empty fungible assets. + const EAMOUNT_IS_NOT_ZERO: u64 = 12; + /// Burn ref and fungible asset do not match. + const EBURN_REF_AND_FUNGIBLE_ASSET_MISMATCH: u64 = 13; + /// Cannot destroy fungible stores with a non-zero balance. + const EBALANCE_IS_NOT_ZERO: u64 = 14; + /// Name of the fungible asset metadata is too long + const ENAME_TOO_LONG: u64 = 15; + /// Symbol of the fungible asset metadata is too long + const ESYMBOL_TOO_LONG: u64 = 16; + /// Decimals is over the maximum of 32 + const EDECIMALS_TOO_LARGE: u64 = 17; + /// Fungibility is only available for non-deletable objects. + const EOBJECT_IS_DELETABLE: u64 = 18; + /// URI for the icon of the fungible asset metadata is too long + const EURI_TOO_LONG: u64 = 19; + /// The fungible asset's supply will be negative which should be impossible. + const ESUPPLY_UNDERFLOW: u64 = 20; + /// Supply resource is not found for a metadata object. + const ESUPPLY_NOT_FOUND: u64 = 21; + /// Flag for Concurrent Supply not enabled + const ECONCURRENT_SUPPLY_NOT_ENABLED: u64 = 22; + /// Flag for the existence of fungible store. + const EFUNGIBLE_STORE_EXISTENCE: u64 = 23; + /// Account is not the owner of metadata object. + const ENOT_METADATA_OWNER: u64 = 24; + /// Provided withdraw function type doesn't meet the signature requirement. + const EWITHDRAW_FUNCTION_SIGNATURE_MISMATCH: u64 = 25; + /// Provided deposit function type doesn't meet the signature requirement. + const EDEPOSIT_FUNCTION_SIGNATURE_MISMATCH: u64 = 26; + /// Provided derived_balance function type doesn't meet the signature requirement. + const EDERIVED_BALANCE_FUNCTION_SIGNATURE_MISMATCH: u64 = 27; + /// Invalid withdraw/deposit on dispatchable token. The specified token has a dispatchable function hook. + /// Need to invoke dispatchable_fungible_asset::withdraw/deposit to perform transfer. + const EINVALID_DISPATCHABLE_OPERATIONS: u64 = 28; + /// Trying to re-register dispatch hook on a fungible asset. + const EALREADY_REGISTERED: u64 = 29; + /// Fungible metadata does not exist on this account. + const EFUNGIBLE_METADATA_EXISTENCE: u64 = 30; + /// Cannot register dispatch hook for APT. + const EAPT_NOT_DISPATCHABLE: u64 = 31; + /// Flag for Concurrent Supply not enabled + const ECONCURRENT_BALANCE_NOT_ENABLED: u64 = 32; + + // + // Constants + // + + const MAX_NAME_LENGTH: u64 = 32; + const MAX_SYMBOL_LENGTH: u64 = 10; + const MAX_DECIMALS: u8 = 32; + const MAX_URI_LENGTH: u64 = 512; + + /// Maximum possible coin supply. + const MAX_U128: u128 = 340282366920938463463374607431768211455; + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + struct Supply has key { + current: u128, + // option::none() means unlimited supply. + maximum: Option, + } + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + struct ConcurrentSupply has key { + current: Aggregator, + } + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// Metadata of a Fungible asset + struct Metadata has key, copy, drop { + /// Name of the fungible metadata, i.e., "USDT". + name: String, + /// Symbol of the fungible metadata, usually a shorter version of the name. + /// For example, Singapore Dollar is SGD. + symbol: String, + /// Number of decimals used for display purposes. + /// For example, if `decimals` equals `2`, a balance of `505` coins should + /// be displayed to a user as `5.05` (`505 / 10 ** 2`). + decimals: u8, + /// The Uniform Resource Identifier (uri) pointing to an image that can be used as the icon for this fungible + /// asset. + icon_uri: String, + /// The Uniform Resource Identifier (uri) pointing to the website for the fungible asset. + project_uri: String, + } + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// Defines a `FungibleAsset`, such that all `FungibleStore`s stores are untransferable at + /// the object layer. + struct Untransferable has key {} + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// The store object that holds fungible assets of a specific type associated with an account. + struct FungibleStore has key { + /// The address of the base metadata object. + metadata: Object, + /// The balance of the fungible metadata. + balance: u64, + /// If true, owner transfer is disabled that only `TransferRef` can move in/out from this store. + frozen: bool, + } + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + struct DispatchFunctionStore has key { + withdraw_function: Option, + deposit_function: Option, + derived_balance_function: Option, + } + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// The store object that holds concurrent fungible asset balance. + struct ConcurrentFungibleBalance has key { + /// The balance of the fungible metadata. + balance: Aggregator, + } + + /// FungibleAsset can be passed into function for type safety and to guarantee a specific amount. + /// FungibleAsset is ephemeral and cannot be stored directly. It must be deposited back into a store. + struct FungibleAsset { + metadata: Object, + amount: u64, + } + + /// MintRef can be used to mint the fungible asset into an account's store. + struct MintRef has drop, store { + metadata: Object + } + + /// TransferRef can be used to allow or disallow the owner of fungible assets from transferring the asset + /// and allow the holder of TransferRef to transfer fungible assets from any account. + struct TransferRef has drop, store { + metadata: Object + } + + /// BurnRef can be used to burn fungible assets from a given holder account. + struct BurnRef has drop, store { + metadata: Object + } + + /// MutateMetadataRef can be used to directly modify the fungible asset's Metadata. + struct MutateMetadataRef has drop, store { + metadata: Object + } + + #[event] + /// Emitted when fungible assets are deposited into a store. + struct Deposit has drop, store { + store: address, + amount: u64, + } + + #[event] + /// Emitted when fungible assets are withdrawn from a store. + struct Withdraw has drop, store { + store: address, + amount: u64, + } + + #[event] + /// Emitted when a store's frozen status is updated. + struct Frozen has drop, store { + store: address, + frozen: bool, + } + + inline fun default_to_concurrent_fungible_supply(): bool { + features::concurrent_fungible_assets_enabled() + } + + inline fun allow_upgrade_to_concurrent_fungible_balance(): bool { + features::concurrent_fungible_balance_enabled() + } + + inline fun default_to_concurrent_fungible_balance(): bool { + features::default_to_concurrent_fungible_balance_enabled() + } + + /// Make an existing object fungible by adding the Metadata resource. + /// This returns the capabilities to mint, burn, and transfer. + /// maximum_supply defines the behavior of maximum supply when monitoring: + /// - option::none(): Monitoring unlimited supply + /// (width of the field - MAX_U128 is the implicit maximum supply) + /// if option::some(MAX_U128) is used, it is treated as unlimited supply. + /// - option::some(max): Monitoring fixed supply with `max` as the maximum supply. + public fun add_fungibility( + constructor_ref: &ConstructorRef, + maximum_supply: Option, + name: String, + symbol: String, + decimals: u8, + icon_uri: String, + project_uri: String, + ): Object { + assert!(!object::can_generate_delete_ref(constructor_ref), error::invalid_argument(EOBJECT_IS_DELETABLE)); + let metadata_object_signer = &object::generate_signer(constructor_ref); + assert!(string::length(&name) <= MAX_NAME_LENGTH, error::out_of_range(ENAME_TOO_LONG)); + assert!(string::length(&symbol) <= MAX_SYMBOL_LENGTH, error::out_of_range(ESYMBOL_TOO_LONG)); + assert!(decimals <= MAX_DECIMALS, error::out_of_range(EDECIMALS_TOO_LARGE)); + assert!(string::length(&icon_uri) <= MAX_URI_LENGTH, error::out_of_range(EURI_TOO_LONG)); + assert!(string::length(&project_uri) <= MAX_URI_LENGTH, error::out_of_range(EURI_TOO_LONG)); + move_to(metadata_object_signer, + Metadata { + name, + symbol, + decimals, + icon_uri, + project_uri, + } + ); + + if (default_to_concurrent_fungible_supply()) { + let unlimited = option::is_none(&maximum_supply); + move_to(metadata_object_signer, ConcurrentSupply { + current: if (unlimited) { + aggregator_v2::create_unbounded_aggregator() + } else { + aggregator_v2::create_aggregator(option::extract(&mut maximum_supply)) + }, + }); + } else { + move_to(metadata_object_signer, Supply { + current: 0, + maximum: maximum_supply + }); + }; + + object::object_from_constructor_ref(constructor_ref) + } + + /// Set that only untransferable stores can be created for this fungible asset. + public fun set_untransferable(constructor_ref: &ConstructorRef) { + let metadata_addr = object::address_from_constructor_ref(constructor_ref); + assert!(exists(metadata_addr), error::not_found(EFUNGIBLE_METADATA_EXISTENCE)); + let metadata_signer = &object::generate_signer(constructor_ref); + move_to(metadata_signer, Untransferable {}); + } + + + #[view] + /// Returns true if the FA is untransferable. + public fun is_untransferable(metadata: Object): bool { + exists(object::object_address(&metadata)) + } + + /// Create a fungible asset store whose transfer rule would be overloaded by the provided function. + public(friend) fun register_dispatch_functions( + constructor_ref: &ConstructorRef, + withdraw_function: Option, + deposit_function: Option, + derived_balance_function: Option, + ) { + // Verify that caller type matches callee type so wrongly typed function cannot be registered. + option::for_each_ref(&withdraw_function, |withdraw_function| { + let dispatcher_withdraw_function_info = function_info::new_function_info_from_address( + @aptos_framework, + string::utf8(b"dispatchable_fungible_asset"), + string::utf8(b"dispatchable_withdraw"), + ); + + assert!( + function_info::check_dispatch_type_compatibility( + &dispatcher_withdraw_function_info, + withdraw_function + ), + error::invalid_argument( + EWITHDRAW_FUNCTION_SIGNATURE_MISMATCH + ) + ); + }); + + option::for_each_ref(&deposit_function, |deposit_function| { + let dispatcher_deposit_function_info = function_info::new_function_info_from_address( + @aptos_framework, + string::utf8(b"dispatchable_fungible_asset"), + string::utf8(b"dispatchable_deposit"), + ); + // Verify that caller type matches callee type so wrongly typed function cannot be registered. + assert!( + function_info::check_dispatch_type_compatibility( + &dispatcher_deposit_function_info, + deposit_function + ), + error::invalid_argument( + EDEPOSIT_FUNCTION_SIGNATURE_MISMATCH + ) + ); + }); + + option::for_each_ref(&derived_balance_function, |balance_function| { + let dispatcher_derived_balance_function_info = function_info::new_function_info_from_address( + @aptos_framework, + string::utf8(b"dispatchable_fungible_asset"), + string::utf8(b"dispatchable_derived_balance"), + ); + // Verify that caller type matches callee type so wrongly typed function cannot be registered. + assert!( + function_info::check_dispatch_type_compatibility( + &dispatcher_derived_balance_function_info, + balance_function + ), + error::invalid_argument( + EDERIVED_BALANCE_FUNCTION_SIGNATURE_MISMATCH + ) + ); + }); + + // Cannot register hook for APT. + assert!( + object::address_from_constructor_ref(constructor_ref) != @aptos_fungible_asset, + error::permission_denied(EAPT_NOT_DISPATCHABLE) + ); + assert!( + !object::can_generate_delete_ref(constructor_ref), + error::invalid_argument(EOBJECT_IS_DELETABLE) + ); + assert!( + !exists( + object::address_from_constructor_ref(constructor_ref) + ), + error::already_exists(EALREADY_REGISTERED) + ); + assert!( + exists( + object::address_from_constructor_ref(constructor_ref) + ), + error::not_found(EFUNGIBLE_METADATA_EXISTENCE), + ); + + let store_obj = &object::generate_signer(constructor_ref); + + // Store the overload function hook. + move_to( + store_obj, + DispatchFunctionStore { + withdraw_function, + deposit_function, + derived_balance_function, + } + ); + } + + /// Creates a mint ref that can be used to mint fungible assets from the given fungible object's constructor ref. + /// This can only be called at object creation time as constructor_ref is only available then. + public fun generate_mint_ref(constructor_ref: &ConstructorRef): MintRef { + let metadata = object::object_from_constructor_ref(constructor_ref); + MintRef { metadata } + } + + /// Creates a burn ref that can be used to burn fungible assets from the given fungible object's constructor ref. + /// This can only be called at object creation time as constructor_ref is only available then. + public fun generate_burn_ref(constructor_ref: &ConstructorRef): BurnRef { + let metadata = object::object_from_constructor_ref(constructor_ref); + BurnRef { metadata } + } + + /// Creates a transfer ref that can be used to freeze/unfreeze/transfer fungible assets from the given fungible + /// object's constructor ref. + /// This can only be called at object creation time as constructor_ref is only available then. + public fun generate_transfer_ref(constructor_ref: &ConstructorRef): TransferRef { + let metadata = object::object_from_constructor_ref(constructor_ref); + TransferRef { metadata } + } + + /// Creates a mutate metadata ref that can be used to change the metadata information of fungible assets from the + /// given fungible object's constructor ref. + /// This can only be called at object creation time as constructor_ref is only available then. + public fun generate_mutate_metadata_ref(constructor_ref: &ConstructorRef): MutateMetadataRef { + let metadata = object::object_from_constructor_ref(constructor_ref); + MutateMetadataRef { metadata } + } + + #[view] + /// Get the current supply from the `metadata` object. + public fun supply(metadata: Object): Option acquires Supply, ConcurrentSupply { + let metadata_address = object::object_address(&metadata); + if (exists(metadata_address)) { + let supply = borrow_global(metadata_address); + option::some(aggregator_v2::read(&supply.current)) + } else if (exists(metadata_address)) { + let supply = borrow_global(metadata_address); + option::some(supply.current) + } else { + option::none() + } + } + + #[view] + /// Get the maximum supply from the `metadata` object. + /// If supply is unlimited (or set explicitly to MAX_U128), none is returned + public fun maximum(metadata: Object): Option acquires Supply, ConcurrentSupply { + let metadata_address = object::object_address(&metadata); + if (exists(metadata_address)) { + let supply = borrow_global(metadata_address); + let max_value = aggregator_v2::max_value(&supply.current); + if (max_value == MAX_U128) { + option::none() + } else { + option::some(max_value) + } + } else if (exists(metadata_address)) { + let supply = borrow_global(metadata_address); + supply.maximum + } else { + option::none() + } + } + + #[view] + /// Get the name of the fungible asset from the `metadata` object. + public fun name(metadata: Object): String acquires Metadata { + borrow_fungible_metadata(&metadata).name + } + + #[view] + /// Get the symbol of the fungible asset from the `metadata` object. + public fun symbol(metadata: Object): String acquires Metadata { + borrow_fungible_metadata(&metadata).symbol + } + + #[view] + /// Get the decimals from the `metadata` object. + public fun decimals(metadata: Object): u8 acquires Metadata { + borrow_fungible_metadata(&metadata).decimals + } + + #[view] + /// Get the icon uri from the `metadata` object. + public fun icon_uri(metadata: Object): String acquires Metadata { + borrow_fungible_metadata(&metadata).icon_uri + } + + #[view] + /// Get the project uri from the `metadata` object. + public fun project_uri(metadata: Object): String acquires Metadata { + borrow_fungible_metadata(&metadata).project_uri + } + + #[view] + /// Get the metadata struct from the `metadata` object. + public fun metadata(metadata: Object): Metadata acquires Metadata { + *borrow_fungible_metadata(&metadata) + } + + #[view] + /// Return whether the provided address has a store initialized. + public fun store_exists(store: address): bool { + store_exists_inline(store) + } + + /// Return whether the provided address has a store initialized. + inline fun store_exists_inline(store: address): bool { + exists(store) + } + + /// Return whether the provided address has a concurrent fungible balance initialized, + /// at the fungible store address. + inline fun concurrent_fungible_balance_exists_inline(store: address): bool { + exists(store) + } + + /// Return the underlying metadata object + public fun metadata_from_asset(fa: &FungibleAsset): Object { + fa.metadata + } + + #[view] + /// Return the underlying metadata object. + public fun store_metadata(store: Object): Object acquires FungibleStore { + borrow_store_resource(&store).metadata + } + + /// Return the `amount` of a given fungible asset. + public fun amount(fa: &FungibleAsset): u64 { + fa.amount + } + + #[view] + /// Get the balance of a given store. + public fun balance(store: Object): u64 acquires FungibleStore, ConcurrentFungibleBalance { + let store_addr = object::object_address(&store); + if (store_exists_inline(store_addr)) { + let store_balance = borrow_store_resource(&store).balance; + if (store_balance == 0 && concurrent_fungible_balance_exists_inline(store_addr)) { + let balance_resource = borrow_global(store_addr); + aggregator_v2::read(&balance_resource.balance) + } else { + store_balance + } + } else { + 0 + } + } + + #[view] + /// Check whether the balance of a given store is >= `amount`. + public fun is_balance_at_least(store: Object, amount: u64): bool acquires FungibleStore, ConcurrentFungibleBalance { + let store_addr = object::object_address(&store); + is_address_balance_at_least(store_addr, amount) + } + + /// Check whether the balance of a given store is >= `amount`. + public(friend) fun is_address_balance_at_least(store_addr: address, amount: u64): bool acquires FungibleStore, ConcurrentFungibleBalance { + if (store_exists_inline(store_addr)) { + let store_balance = borrow_global(store_addr).balance; + if (store_balance == 0 && concurrent_fungible_balance_exists_inline(store_addr)) { + let balance_resource = borrow_global(store_addr); + aggregator_v2::is_at_least(&balance_resource.balance, amount) + } else { + store_balance >= amount + } + } else { + amount == 0 + } + } + + #[view] + /// Return whether a store is frozen. + /// + /// If the store has not been created, we default to returning false so deposits can be sent to it. + public fun is_frozen(store: Object): bool acquires FungibleStore { + let store_addr = object::object_address(&store); + store_exists_inline(store_addr) && borrow_global(store_addr).frozen + } + + #[view] + /// Return whether a fungible asset type is dispatchable. + public fun is_store_dispatchable(store: Object): bool acquires FungibleStore { + let fa_store = borrow_store_resource(&store); + let metadata_addr = object::object_address(&fa_store.metadata); + exists(metadata_addr) + } + + public fun deposit_dispatch_function(store: Object): Option acquires FungibleStore, DispatchFunctionStore { + let fa_store = borrow_store_resource(&store); + let metadata_addr = object::object_address(&fa_store.metadata); + if(exists(metadata_addr)) { + borrow_global(metadata_addr).deposit_function + } else { + option::none() + } + } + + fun has_deposit_dispatch_function(metadata: Object): bool acquires DispatchFunctionStore { + let metadata_addr = object::object_address(&metadata); + // Short circuit on APT for better perf + if(metadata_addr != @aptos_fungible_asset && exists(metadata_addr)) { + option::is_some(&borrow_global(metadata_addr).deposit_function) + } else { + false + } + } + + public fun withdraw_dispatch_function(store: Object): Option acquires FungibleStore, DispatchFunctionStore { + let fa_store = borrow_store_resource(&store); + let metadata_addr = object::object_address(&fa_store.metadata); + if(exists(metadata_addr)) { + borrow_global(metadata_addr).withdraw_function + } else { + option::none() + } + } + + fun has_withdraw_dispatch_function(metadata: Object): bool acquires DispatchFunctionStore { + let metadata_addr = object::object_address(&metadata); + // Short circuit on APT for better perf + if (metadata_addr != @aptos_fungible_asset && exists(metadata_addr)) { + option::is_some(&borrow_global(metadata_addr).withdraw_function) + } else { + false + } + } + + public(friend) fun derived_balance_dispatch_function(store: Object): Option acquires FungibleStore, DispatchFunctionStore { + let fa_store = borrow_store_resource(&store); + let metadata_addr = object::object_address(&fa_store.metadata); + if (exists(metadata_addr)) { + borrow_global(metadata_addr).derived_balance_function + } else { + option::none() + } + } + + public fun asset_metadata(fa: &FungibleAsset): Object { + fa.metadata + } + + /// Get the underlying metadata object from the `MintRef`. + public fun mint_ref_metadata(ref: &MintRef): Object { + ref.metadata + } + + /// Get the underlying metadata object from the `TransferRef`. + public fun transfer_ref_metadata(ref: &TransferRef): Object { + ref.metadata + } + + /// Get the underlying metadata object from the `BurnRef`. + public fun burn_ref_metadata(ref: &BurnRef): Object { + ref.metadata + } + + /// Get the underlying metadata object from the `MutateMetadataRef`. + public fun object_from_metadata_ref(ref: &MutateMetadataRef): Object { + ref.metadata + } + + /// Transfer an `amount` of fungible asset from `from_store`, which should be owned by `sender`, to `receiver`. + /// Note: it does not move the underlying object. + public entry fun transfer( + sender: &signer, + from: Object, + to: Object, + amount: u64, + ) acquires FungibleStore, DispatchFunctionStore, ConcurrentFungibleBalance { + let fa = withdraw(sender, from, amount); + deposit(to, fa); + } + + /// Allow an object to hold a store for fungible assets. + /// Applications can use this to create multiple stores for isolating fungible assets for different purposes. + public fun create_store( + constructor_ref: &ConstructorRef, + metadata: Object, + ): Object { + let store_obj = &object::generate_signer(constructor_ref); + move_to(store_obj, FungibleStore { + metadata: object::convert(metadata), + balance: 0, + frozen: false, + }); + + if (is_untransferable(metadata)) { + object::set_untransferable(constructor_ref); + }; + + if (default_to_concurrent_fungible_balance()) { + move_to(store_obj, ConcurrentFungibleBalance { + balance: aggregator_v2::create_unbounded_aggregator(), + }); + }; + + object::object_from_constructor_ref(constructor_ref) + } + + /// Used to delete a store. Requires the store to be completely empty prior to removing it + public fun remove_store(delete_ref: &DeleteRef) acquires FungibleStore, FungibleAssetEvents, ConcurrentFungibleBalance { + let store = &object::object_from_delete_ref(delete_ref); + let addr = object::object_address(store); + let FungibleStore { metadata: _, balance, frozen: _ } + = move_from(addr); + assert!(balance == 0, error::permission_denied(EBALANCE_IS_NOT_ZERO)); + + if (concurrent_fungible_balance_exists_inline(addr)) { + let ConcurrentFungibleBalance { balance } = move_from(addr); + assert!(aggregator_v2::read(&balance) == 0, error::permission_denied(EBALANCE_IS_NOT_ZERO)); + }; + + // Cleanup deprecated event handles if exist. + if (exists(addr)) { + let FungibleAssetEvents { + deposit_events, + withdraw_events, + frozen_events, + } = move_from(addr); + event::destroy_handle(deposit_events); + event::destroy_handle(withdraw_events); + event::destroy_handle(frozen_events); + }; + } + + /// Withdraw `amount` of the fungible asset from `store` by the owner. + public fun withdraw( + owner: &signer, + store: Object, + amount: u64, + ): FungibleAsset acquires FungibleStore, DispatchFunctionStore, ConcurrentFungibleBalance { + withdraw_sanity_check(owner, store, true); + withdraw_internal(object::object_address(&store), amount) + } + + /// Check the permission for withdraw operation. + public(friend) fun withdraw_sanity_check( + owner: &signer, + store: Object, + abort_on_dispatch: bool, + ) acquires FungibleStore, DispatchFunctionStore { + assert!(object::owns(store, signer::address_of(owner)), error::permission_denied(ENOT_STORE_OWNER)); + let fa_store = borrow_store_resource(&store); + assert!( + !abort_on_dispatch || !has_withdraw_dispatch_function(fa_store.metadata), + error::invalid_argument(EINVALID_DISPATCHABLE_OPERATIONS) + ); + assert!(!fa_store.frozen, error::permission_denied(ESTORE_IS_FROZEN)); + } + + /// Deposit `amount` of the fungible asset to `store`. + public fun deposit_sanity_check( + store: Object, + abort_on_dispatch: bool + ) acquires FungibleStore, DispatchFunctionStore { + let fa_store = borrow_store_resource(&store); + assert!( + !abort_on_dispatch || !has_deposit_dispatch_function(fa_store.metadata), + error::invalid_argument(EINVALID_DISPATCHABLE_OPERATIONS) + ); + assert!(!fa_store.frozen, error::permission_denied(ESTORE_IS_FROZEN)); + } + + /// Deposit `amount` of the fungible asset to `store`. + public fun deposit(store: Object, fa: FungibleAsset) acquires FungibleStore, DispatchFunctionStore, ConcurrentFungibleBalance { + deposit_sanity_check(store, true); + deposit_internal(object::object_address(&store), fa); + } + + /// Mint the specified `amount` of the fungible asset. + public fun mint(ref: &MintRef, amount: u64): FungibleAsset acquires Supply, ConcurrentSupply { + let metadata = ref.metadata; + mint_internal(metadata, amount) + } + + /// CAN ONLY BE CALLED BY coin.move for migration. + public(friend) fun mint_internal( + metadata: Object, + amount: u64 + ): FungibleAsset acquires Supply, ConcurrentSupply { + increase_supply(&metadata, amount); + FungibleAsset { + metadata, + amount + } + } + + /// Mint the specified `amount` of the fungible asset to a destination store. + public fun mint_to(ref: &MintRef, store: Object, amount: u64) + acquires FungibleStore, Supply, ConcurrentSupply, DispatchFunctionStore, ConcurrentFungibleBalance { + deposit_sanity_check(store, false); + deposit_internal(object::object_address(&store), mint(ref, amount)); + } + + /// Enable/disable a store's ability to do direct transfers of the fungible asset. + public fun set_frozen_flag( + ref: &TransferRef, + store: Object, + frozen: bool, + ) acquires FungibleStore { + assert!( + ref.metadata == store_metadata(store), + error::invalid_argument(ETRANSFER_REF_AND_STORE_MISMATCH), + ); + set_frozen_flag_internal(store, frozen) + } + + public(friend) fun set_frozen_flag_internal( + store: Object, + frozen: bool + ) acquires FungibleStore { + let store_addr = object::object_address(&store); + borrow_global_mut(store_addr).frozen = frozen; + + event::emit(Frozen { store: store_addr, frozen }); + } + + /// Burns a fungible asset + public fun burn(ref: &BurnRef, fa: FungibleAsset) acquires Supply, ConcurrentSupply { + assert!( + ref.metadata == metadata_from_asset(&fa), + error::invalid_argument(EBURN_REF_AND_FUNGIBLE_ASSET_MISMATCH) + ); + burn_internal(fa); + } + + /// CAN ONLY BE CALLED BY coin.move for migration. + public(friend) fun burn_internal( + fa: FungibleAsset + ): u64 acquires Supply, ConcurrentSupply { + let FungibleAsset { + metadata, + amount + } = fa; + decrease_supply(&metadata, amount); + amount + } + + /// Burn the `amount` of the fungible asset from the given store. + public fun burn_from( + ref: &BurnRef, + store: Object, + amount: u64 + ) acquires FungibleStore, Supply, ConcurrentSupply, ConcurrentFungibleBalance { + // ref metadata match is checked in burn() call + burn(ref, withdraw_internal(object::object_address(&store), amount)); + } + + public(friend) fun address_burn_from( + ref: &BurnRef, + store_addr: address, + amount: u64 + ) acquires FungibleStore, Supply, ConcurrentSupply, ConcurrentFungibleBalance { + // ref metadata match is checked in burn() call + burn(ref, withdraw_internal(store_addr, amount)); + } + + /// Withdraw `amount` of the fungible asset from the `store` ignoring `frozen`. + public fun withdraw_with_ref( + ref: &TransferRef, + store: Object, + amount: u64 + ): FungibleAsset acquires FungibleStore, ConcurrentFungibleBalance { + assert!( + ref.metadata == store_metadata(store), + error::invalid_argument(ETRANSFER_REF_AND_STORE_MISMATCH), + ); + withdraw_internal(object::object_address(&store), amount) + } + + /// Deposit the fungible asset into the `store` ignoring `frozen`. + public fun deposit_with_ref( + ref: &TransferRef, + store: Object, + fa: FungibleAsset + ) acquires FungibleStore, ConcurrentFungibleBalance { + assert!( + ref.metadata == fa.metadata, + error::invalid_argument(ETRANSFER_REF_AND_FUNGIBLE_ASSET_MISMATCH) + ); + deposit_internal(object::object_address(&store), fa); + } + + /// Transfer `amount` of the fungible asset with `TransferRef` even it is frozen. + public fun transfer_with_ref( + transfer_ref: &TransferRef, + from: Object, + to: Object, + amount: u64, + ) acquires FungibleStore, ConcurrentFungibleBalance { + let fa = withdraw_with_ref(transfer_ref, from, amount); + deposit_with_ref(transfer_ref, to, fa); + } + + /// Mutate specified fields of the fungible asset's `Metadata`. + public fun mutate_metadata( + metadata_ref: &MutateMetadataRef, + name: Option, + symbol: Option, + decimals: Option, + icon_uri: Option, + project_uri: Option, + ) acquires Metadata { + let metadata_address = object::object_address(&metadata_ref.metadata); + let mutable_metadata = borrow_global_mut(metadata_address); + + if (option::is_some(&name)){ + mutable_metadata.name = option::extract(&mut name); + }; + if (option::is_some(&symbol)){ + mutable_metadata.symbol = option::extract(&mut symbol); + }; + if (option::is_some(&decimals)){ + mutable_metadata.decimals = option::extract(&mut decimals); + }; + if (option::is_some(&icon_uri)){ + mutable_metadata.icon_uri = option::extract(&mut icon_uri); + }; + if (option::is_some(&project_uri)){ + mutable_metadata.project_uri = option::extract(&mut project_uri); + }; + } + + /// Create a fungible asset with zero amount. + /// This can be useful when starting a series of computations where the initial value is 0. + public fun zero(metadata: Object): FungibleAsset { + FungibleAsset { + metadata: object::convert(metadata), + amount: 0, + } + } + + /// Extract a given amount from the given fungible asset and return a new one. + public fun extract(fungible_asset: &mut FungibleAsset, amount: u64): FungibleAsset { + assert!(fungible_asset.amount >= amount, error::invalid_argument(EINSUFFICIENT_BALANCE)); + fungible_asset.amount = fungible_asset.amount - amount; + FungibleAsset { + metadata: fungible_asset.metadata, + amount, + } + } + + /// "Merges" the two given fungible assets. The fungible asset passed in as `dst_fungible_asset` will have a value + /// equal to the sum of the two (`dst_fungible_asset` and `src_fungible_asset`). + public fun merge(dst_fungible_asset: &mut FungibleAsset, src_fungible_asset: FungibleAsset) { + let FungibleAsset { metadata, amount } = src_fungible_asset; + assert!(metadata == dst_fungible_asset.metadata, error::invalid_argument(EFUNGIBLE_ASSET_MISMATCH)); + dst_fungible_asset.amount = dst_fungible_asset.amount + amount; + } + + /// Destroy an empty fungible asset. + public fun destroy_zero(fungible_asset: FungibleAsset) { + let FungibleAsset { amount, metadata: _ } = fungible_asset; + assert!(amount == 0, error::invalid_argument(EAMOUNT_IS_NOT_ZERO)); + } + + public(friend) fun deposit_internal(store_addr: address, fa: FungibleAsset) acquires FungibleStore, ConcurrentFungibleBalance { + let FungibleAsset { metadata, amount } = fa; + if (amount == 0) return; + + assert!(exists(store_addr), error::not_found(EFUNGIBLE_STORE_EXISTENCE)); + let store = borrow_global_mut(store_addr); + assert!(metadata == store.metadata, error::invalid_argument(EFUNGIBLE_ASSET_AND_STORE_MISMATCH)); + + if (store.balance == 0 && concurrent_fungible_balance_exists_inline(store_addr)) { + let balance_resource = borrow_global_mut(store_addr); + aggregator_v2::add(&mut balance_resource.balance, amount); + } else { + store.balance = store.balance + amount; + }; + + event::emit(Deposit { store: store_addr, amount }); + } + + /// Extract `amount` of the fungible asset from `store`. + public(friend) fun withdraw_internal( + store_addr: address, + amount: u64, + ): FungibleAsset acquires FungibleStore, ConcurrentFungibleBalance { + assert!(exists(store_addr), error::not_found(EFUNGIBLE_STORE_EXISTENCE)); + + let store = borrow_global_mut(store_addr); + let metadata = store.metadata; + if (amount != 0) { + if (store.balance == 0 && concurrent_fungible_balance_exists_inline(store_addr)) { + let balance_resource = borrow_global_mut(store_addr); + assert!( + aggregator_v2::try_sub(&mut balance_resource.balance, amount), + error::invalid_argument(EINSUFFICIENT_BALANCE) + ); + } else { + assert!(store.balance >= amount, error::invalid_argument(EINSUFFICIENT_BALANCE)); + store.balance = store.balance - amount; + }; + + event::emit(Withdraw { store: store_addr, amount }); + }; + FungibleAsset { metadata, amount } + } + + /// Increase the supply of a fungible asset by minting. + fun increase_supply(metadata: &Object, amount: u64) acquires Supply, ConcurrentSupply { + if (amount == 0) { + return + }; + let metadata_address = object::object_address(metadata); + + if (exists(metadata_address)) { + let supply = borrow_global_mut(metadata_address); + assert!( + aggregator_v2::try_add(&mut supply.current, (amount as u128)), + error::out_of_range(EMAX_SUPPLY_EXCEEDED) + ); + } else if (exists(metadata_address)) { + let supply = borrow_global_mut(metadata_address); + if (option::is_some(&supply.maximum)) { + let max = *option::borrow_mut(&mut supply.maximum); + assert!( + max - supply.current >= (amount as u128), + error::out_of_range(EMAX_SUPPLY_EXCEEDED) + ) + }; + supply.current = supply.current + (amount as u128); + } else { + abort error::not_found(ESUPPLY_NOT_FOUND) + } + } + + /// Decrease the supply of a fungible asset by burning. + fun decrease_supply(metadata: &Object, amount: u64) acquires Supply, ConcurrentSupply { + if (amount == 0) { + return + }; + let metadata_address = object::object_address(metadata); + + if (exists(metadata_address)) { + let supply = borrow_global_mut(metadata_address); + + assert!( + aggregator_v2::try_sub(&mut supply.current, (amount as u128)), + error::out_of_range(ESUPPLY_UNDERFLOW) + ); + } else if (exists(metadata_address)) { + assert!(exists(metadata_address), error::not_found(ESUPPLY_NOT_FOUND)); + let supply = borrow_global_mut(metadata_address); + assert!( + supply.current >= (amount as u128), + error::invalid_state(ESUPPLY_UNDERFLOW) + ); + supply.current = supply.current - (amount as u128); + } else { + assert!(false, error::not_found(ESUPPLY_NOT_FOUND)); + } + } + + inline fun borrow_fungible_metadata( + metadata: &Object + ): &Metadata acquires Metadata { + let addr = object::object_address(metadata); + borrow_global(addr) + } + + inline fun borrow_fungible_metadata_mut( + metadata: &Object + ): &mut Metadata acquires Metadata { + let addr = object::object_address(metadata); + borrow_global_mut(addr) + } + + inline fun borrow_store_resource(store: &Object): &FungibleStore acquires FungibleStore { + let store_addr = object::object_address(store); + assert!(exists(store_addr), error::not_found(EFUNGIBLE_STORE_EXISTENCE)); + borrow_global(store_addr) + } + + public fun upgrade_to_concurrent( + ref: &ExtendRef, + ) acquires Supply { + let metadata_object_address = object::address_from_extend_ref(ref); + let metadata_object_signer = object::generate_signer_for_extending(ref); + assert!( + features::concurrent_fungible_assets_enabled(), + error::invalid_argument(ECONCURRENT_SUPPLY_NOT_ENABLED) + ); + assert!(exists(metadata_object_address), error::not_found(ESUPPLY_NOT_FOUND)); + let Supply { + current, + maximum, + } = move_from(metadata_object_address); + + let unlimited = option::is_none(&maximum); + let supply = ConcurrentSupply { + current: if (unlimited) { + aggregator_v2::create_unbounded_aggregator_with_value(current) + } + else { + aggregator_v2::create_aggregator_with_value(current, option::extract(&mut maximum)) + }, + }; + move_to(&metadata_object_signer, supply); + } + + public entry fun upgrade_store_to_concurrent( + owner: &signer, + store: Object, + ) acquires FungibleStore { + assert!(object::owns(store, signer::address_of(owner)), error::permission_denied(ENOT_STORE_OWNER)); + assert!(!is_frozen(store), error::invalid_argument(ESTORE_IS_FROZEN)); + assert!(allow_upgrade_to_concurrent_fungible_balance(), error::invalid_argument(ECONCURRENT_BALANCE_NOT_ENABLED)); + ensure_store_upgraded_to_concurrent_internal(object::object_address(&store)); + } + + /// Ensure a known `FungibleStore` has `ConcurrentFungibleBalance`. + fun ensure_store_upgraded_to_concurrent_internal( + fungible_store_address: address, + ) acquires FungibleStore { + if (exists(fungible_store_address)) { + return + }; + let store = borrow_global_mut(fungible_store_address); + let balance = aggregator_v2::create_unbounded_aggregator_with_value(store.balance); + store.balance = 0; + let object_signer = create_signer::create_signer(fungible_store_address); + move_to(&object_signer, ConcurrentFungibleBalance { balance }); + } + + #[test_only] + use aptos_framework::account; + + #[test_only] + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + + struct TestToken has key {} + + #[test_only] + public fun create_test_token(creator: &signer): (ConstructorRef, Object) { + account::create_account_for_test(signer::address_of(creator)); + let creator_ref = object::create_named_object(creator, b"TEST"); + let object_signer = object::generate_signer(&creator_ref); + move_to(&object_signer, TestToken {}); + + let token = object::object_from_constructor_ref(&creator_ref); + (creator_ref, token) + } + + #[test_only] + public fun init_test_metadata(constructor_ref: &ConstructorRef): (MintRef, TransferRef, BurnRef, MutateMetadataRef) { + add_fungibility( + constructor_ref, + option::some(100) /* max supply */, + string::utf8(b"TEST"), + string::utf8(b"@@"), + 0, + string::utf8(b"http://www.example.com/favicon.ico"), + string::utf8(b"http://www.example.com"), + ); + let mint_ref = generate_mint_ref(constructor_ref); + let burn_ref = generate_burn_ref(constructor_ref); + let transfer_ref = generate_transfer_ref(constructor_ref); + let mutate_metadata_ref= generate_mutate_metadata_ref(constructor_ref); + (mint_ref, transfer_ref, burn_ref, mutate_metadata_ref) + } + + #[test_only] + public fun create_fungible_asset( + creator: &signer + ): (MintRef, TransferRef, BurnRef, MutateMetadataRef, Object) { + let (creator_ref, token_object) = create_test_token(creator); + let (mint, transfer, burn, mutate_metadata) = init_test_metadata(&creator_ref); + (mint, transfer, burn, mutate_metadata, object::convert(token_object)) + } + + #[test_only] + public fun create_test_store(owner: &signer, metadata: Object): Object { + let owner_addr = signer::address_of(owner); + if (!account::exists_at(owner_addr)) { + account::create_account_for_test(owner_addr); + }; + create_store(&object::create_object_from_account(owner), metadata) + } + + #[test(creator = @0xcafe)] + fun test_metadata_basic_flow(creator: &signer) acquires Metadata, Supply, ConcurrentSupply { + let (creator_ref, metadata) = create_test_token(creator); + init_test_metadata(&creator_ref); + assert!(supply(metadata) == option::some(0), 1); + assert!(maximum(metadata) == option::some(100), 2); + assert!(name(metadata) == string::utf8(b"TEST"), 3); + assert!(symbol(metadata) == string::utf8(b"@@"), 4); + assert!(decimals(metadata) == 0, 5); + assert!(icon_uri(metadata) == string::utf8(b"http://www.example.com/favicon.ico"), 6); + assert!(project_uri(metadata) == string::utf8(b"http://www.example.com"), 7); + + assert!(metadata(metadata) == Metadata { + name: string::utf8(b"TEST"), + symbol: string::utf8(b"@@"), + decimals: 0, + icon_uri: string::utf8(b"http://www.example.com/favicon.ico"), + project_uri: string::utf8(b"http://www.example.com"), + }, 8); + + increase_supply(&metadata, 50); + assert!(supply(metadata) == option::some(50), 9); + decrease_supply(&metadata, 30); + assert!(supply(metadata) == option::some(20), 10); + } + + #[test(creator = @0xcafe)] + #[expected_failure(abort_code = 0x20005, location = Self)] + fun test_supply_overflow(creator: &signer) acquires Supply, ConcurrentSupply { + let (creator_ref, metadata) = create_test_token(creator); + init_test_metadata(&creator_ref); + increase_supply(&metadata, 101); + } + + #[test(creator = @0xcafe)] + fun test_create_and_remove_store(creator: &signer) acquires FungibleStore, FungibleAssetEvents, ConcurrentFungibleBalance { + let (_, _, _, _, metadata) = create_fungible_asset(creator); + let creator_ref = object::create_object_from_account(creator); + create_store(&creator_ref, metadata); + let delete_ref = object::generate_delete_ref(&creator_ref); + remove_store(&delete_ref); + } + + #[test(creator = @0xcafe, aaron = @0xface)] + fun test_e2e_basic_flow( + creator: &signer, + aaron: &signer, + ) acquires FungibleStore, Supply, ConcurrentSupply, DispatchFunctionStore, ConcurrentFungibleBalance, Metadata { + let (mint_ref, transfer_ref, burn_ref, mutate_metadata_ref, test_token) = create_fungible_asset(creator); + let metadata = mint_ref.metadata; + let creator_store = create_test_store(creator, metadata); + let aaron_store = create_test_store(aaron, metadata); + + assert!(supply(test_token) == option::some(0), 1); + // Mint + let fa = mint(&mint_ref, 100); + assert!(supply(test_token) == option::some(100), 2); + // Deposit + deposit(creator_store, fa); + // Withdraw + let fa = withdraw(creator, creator_store, 80); + assert!(supply(test_token) == option::some(100), 3); + deposit(aaron_store, fa); + // Burn + burn_from(&burn_ref, aaron_store, 30); + assert!(supply(test_token) == option::some(70), 4); + // Transfer + transfer(creator, creator_store, aaron_store, 10); + assert!(balance(creator_store) == 10, 5); + assert!(balance(aaron_store) == 60, 6); + + set_frozen_flag(&transfer_ref, aaron_store, true); + assert!(is_frozen(aaron_store), 7); + // Mutate Metadata + mutate_metadata( + &mutate_metadata_ref, + option::some(string::utf8(b"mutated_name")), + option::some(string::utf8(b"mutated_symbol")), + option::none(), + option::none(), + option::none() + ); + assert!(name(metadata) == string::utf8(b"mutated_name"), 8); + assert!(symbol(metadata) == string::utf8(b"mutated_symbol"), 9); + assert!(decimals(metadata) == 0, 10); + assert!(icon_uri(metadata) == string::utf8(b"http://www.example.com/favicon.ico"), 11); + assert!(project_uri(metadata) == string::utf8(b"http://www.example.com"), 12); + } + + #[test(creator = @0xcafe)] + #[expected_failure(abort_code = 0x50003, location = Self)] + fun test_frozen( + creator: &signer + ) acquires FungibleStore, Supply, ConcurrentSupply, DispatchFunctionStore, ConcurrentFungibleBalance { + let (mint_ref, transfer_ref, _burn_ref, _mutate_metadata_ref, _) = create_fungible_asset(creator); + + let creator_store = create_test_store(creator, mint_ref.metadata); + let fa = mint(&mint_ref, 100); + set_frozen_flag(&transfer_ref, creator_store, true); + deposit(creator_store, fa); + } + + #[test(creator = @0xcafe)] + #[expected_failure(abort_code = 0x50003, location = Self)] + fun test_mint_to_frozen( + creator: &signer + ) acquires FungibleStore, ConcurrentFungibleBalance, Supply, ConcurrentSupply, DispatchFunctionStore { + let (mint_ref, transfer_ref, _burn_ref, _mutate_metadata_ref, _) = create_fungible_asset(creator); + + let creator_store = create_test_store(creator, mint_ref.metadata); + set_frozen_flag(&transfer_ref, creator_store, true); + mint_to(&mint_ref, creator_store, 100); + } + + #[test(creator = @0xcafe)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::object)] + fun test_untransferable( + creator: &signer + ) { + let (creator_ref, _) = create_test_token(creator); + let (mint_ref, _, _, _) = init_test_metadata(&creator_ref); + set_untransferable(&creator_ref); + + let creator_store = create_test_store(creator, mint_ref.metadata); + object::transfer(creator, creator_store, @0x456); + } + + #[test(creator = @0xcafe, aaron = @0xface)] + fun test_transfer_with_ref( + creator: &signer, + aaron: &signer, + ) acquires FungibleStore, Supply, ConcurrentSupply, ConcurrentFungibleBalance { + let (mint_ref, transfer_ref, _burn_ref, _mutate_metadata_ref, _) = create_fungible_asset(creator); + let metadata = mint_ref.metadata; + let creator_store = create_test_store(creator, metadata); + let aaron_store = create_test_store(aaron, metadata); + + let fa = mint(&mint_ref, 100); + set_frozen_flag(&transfer_ref, creator_store, true); + set_frozen_flag(&transfer_ref, aaron_store, true); + deposit_with_ref(&transfer_ref, creator_store, fa); + transfer_with_ref(&transfer_ref, creator_store, aaron_store, 80); + assert!(balance(creator_store) == 20, 1); + assert!(balance(aaron_store) == 80, 2); + assert!(!!is_frozen(creator_store), 3); + assert!(!!is_frozen(aaron_store), 4); + } + + #[test(creator = @0xcafe)] + fun test_mutate_metadata( + creator: &signer + ) acquires Metadata { + let (mint_ref, _transfer_ref, _burn_ref, mutate_metadata_ref, _) = create_fungible_asset(creator); + let metadata = mint_ref.metadata; + + mutate_metadata( + &mutate_metadata_ref, + option::some(string::utf8(b"mutated_name")), + option::some(string::utf8(b"mutated_symbol")), + option::some(10), + option::some(string::utf8(b"http://www.mutated-example.com/favicon.ico")), + option::some(string::utf8(b"http://www.mutated-example.com")) + ); + assert!(name(metadata) == string::utf8(b"mutated_name"), 1); + assert!(symbol(metadata) == string::utf8(b"mutated_symbol"), 2); + assert!(decimals(metadata) == 10, 3); + assert!(icon_uri(metadata) == string::utf8(b"http://www.mutated-example.com/favicon.ico"), 4); + assert!(project_uri(metadata) == string::utf8(b"http://www.mutated-example.com"), 5); + } + + #[test(creator = @0xcafe)] + fun test_partial_mutate_metadata( + creator: &signer + ) acquires Metadata { + let (mint_ref, _transfer_ref, _burn_ref, mutate_metadata_ref, _) = create_fungible_asset(creator); + let metadata = mint_ref.metadata; + + mutate_metadata( + &mutate_metadata_ref, + option::some(string::utf8(b"mutated_name")), + option::some(string::utf8(b"mutated_symbol")), + option::none(), + option::none(), + option::none() + ); + assert!(name(metadata) == string::utf8(b"mutated_name"), 8); + assert!(symbol(metadata) == string::utf8(b"mutated_symbol"), 9); + assert!(decimals(metadata) == 0, 10); + assert!(icon_uri(metadata) == string::utf8(b"http://www.example.com/favicon.ico"), 11); + assert!(project_uri(metadata) == string::utf8(b"http://www.example.com"), 12); + } + + #[test(creator = @0xcafe)] + fun test_merge_and_exact(creator: &signer) acquires Supply, ConcurrentSupply { + let (mint_ref, _transfer_ref, burn_ref, _mutate_metadata_ref, _) = create_fungible_asset(creator); + let fa = mint(&mint_ref, 100); + let cash = extract(&mut fa, 80); + assert!(fa.amount == 20, 1); + assert!(cash.amount == 80, 2); + let more_cash = extract(&mut fa, 20); + destroy_zero(fa); + merge(&mut cash, more_cash); + assert!(cash.amount == 100, 3); + burn(&burn_ref, cash); + } + + #[test(creator = @0xcafe)] + #[expected_failure(abort_code = 0x10012, location = Self)] + fun test_add_fungibility_to_deletable_object(creator: &signer) { + account::create_account_for_test(signer::address_of(creator)); + let creator_ref = &object::create_object_from_account(creator); + init_test_metadata(creator_ref); + } + + #[test(creator = @0xcafe, aaron = @0xface)] + #[expected_failure(abort_code = 0x10006, location = Self)] + fun test_fungible_asset_mismatch_when_merge(creator: &signer, aaron: &signer) { + let (_, _, _, _, metadata1) = create_fungible_asset(creator); + let (_, _, _, _, metadata2) = create_fungible_asset(aaron); + let base = FungibleAsset { + metadata: metadata1, + amount: 1, + }; + let addon = FungibleAsset { + metadata: metadata2, + amount: 1 + }; + merge(&mut base, addon); + let FungibleAsset { + metadata: _, + amount: _ + } = base; + } + + #[test(fx = @aptos_framework, creator = @0xcafe)] + fun test_fungible_asset_upgrade(fx: &signer, creator: &signer) acquires Supply, ConcurrentSupply, FungibleStore, ConcurrentFungibleBalance { + let supply_feature = features::get_concurrent_fungible_assets_feature(); + let balance_feature = features::get_concurrent_fungible_balance_feature(); + let default_balance_feature = features::get_default_to_concurrent_fungible_balance_feature(); + + features::change_feature_flags_for_testing(fx, vector[], vector[supply_feature, balance_feature, default_balance_feature]); + + let (creator_ref, token_object) = create_test_token(creator); + let (mint_ref, transfer_ref, _burn, _mutate_metadata_ref) = init_test_metadata(&creator_ref); + let test_token = object::convert(token_object); + assert!(exists(object::object_address(&test_token)), 1); + assert!(!exists(object::object_address(&test_token)), 2); + let creator_store = create_test_store(creator, test_token); + assert!(exists(object::object_address(&creator_store)), 3); + assert!(!exists(object::object_address(&creator_store)), 4); + + let fa = mint(&mint_ref, 30); + assert!(supply(test_token) == option::some(30), 5); + + deposit_with_ref(&transfer_ref, creator_store, fa); + assert!(exists(object::object_address(&creator_store)), 13); + assert!(borrow_store_resource(&creator_store).balance == 30, 14); + assert!(!exists(object::object_address(&creator_store)), 15); + + features::change_feature_flags_for_testing(fx, vector[supply_feature, balance_feature], vector[default_balance_feature]); + + let extend_ref = object::generate_extend_ref(&creator_ref); + // manual conversion of supply + upgrade_to_concurrent(&extend_ref); + assert!(!exists(object::object_address(&test_token)), 6); + assert!(exists(object::object_address(&test_token)), 7); + + // assert conversion of balance + upgrade_store_to_concurrent(creator, creator_store); + let fb = withdraw_with_ref(&transfer_ref, creator_store, 20); + // both store and new balance need to exist. Old balance should be 0. + assert!(exists(object::object_address(&creator_store)), 9); + assert!(borrow_store_resource(&creator_store).balance == 0, 10); + assert!(exists(object::object_address(&creator_store)), 11); + assert!(aggregator_v2::read(&borrow_global(object::object_address(&creator_store)).balance) == 10, 12); + + deposit_with_ref(&transfer_ref, creator_store, fb); + } + + #[test(fx = @aptos_framework, creator = @0xcafe)] + fun test_fungible_asset_default_concurrent(fx: &signer, creator: &signer) acquires Supply, ConcurrentSupply, FungibleStore, ConcurrentFungibleBalance { + let supply_feature = features::get_concurrent_fungible_assets_feature(); + let balance_feature = features::get_concurrent_fungible_balance_feature(); + let default_balance_feature = features::get_default_to_concurrent_fungible_balance_feature(); + + features::change_feature_flags_for_testing(fx, vector[supply_feature, balance_feature, default_balance_feature], vector[]); + + let (creator_ref, token_object) = create_test_token(creator); + let (mint_ref, transfer_ref, _burn, _mutate_metadata_ref) = init_test_metadata(&creator_ref); + let test_token = object::convert(token_object); + assert!(!exists(object::object_address(&test_token)), 1); + assert!(exists(object::object_address(&test_token)), 2); + let creator_store = create_test_store(creator, test_token); + assert!(exists(object::object_address(&creator_store)), 3); + assert!(exists(object::object_address(&creator_store)), 4); + + let fa = mint(&mint_ref, 30); + assert!(supply(test_token) == option::some(30), 5); + + deposit_with_ref(&transfer_ref, creator_store, fa); + + assert!(exists(object::object_address(&creator_store)), 9); + assert!(borrow_store_resource(&creator_store).balance == 0, 10); + assert!(exists(object::object_address(&creator_store)), 11); + assert!(aggregator_v2::read(&borrow_global(object::object_address(&creator_store)).balance) == 30, 12); + } + + #[deprecated] + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + struct FungibleAssetEvents has key { + deposit_events: event::EventHandle, + withdraw_events: event::EventHandle, + frozen_events: event::EventHandle, + } + + #[deprecated] + struct DepositEvent has drop, store { + amount: u64, + } + + #[deprecated] + struct WithdrawEvent has drop, store { + amount: u64, + } + + #[deprecated] + struct FrozenEvent has drop, store { + frozen: bool, + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/gas_schedule.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/gas_schedule.move new file mode 100644 index 000000000..9156c1ae2 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/gas_schedule.move @@ -0,0 +1,176 @@ +/// This module defines structs and methods to initialize the gas schedule, which dictates how much +/// it costs to execute Move on the network. +module aptos_framework::gas_schedule { + use std::bcs; + use std::error; + use std::string::String; + use std::vector; + use aptos_std::aptos_hash; + use aptos_framework::chain_status; + use aptos_framework::config_buffer; + + use aptos_framework::reconfiguration; + use aptos_framework::system_addresses; + use aptos_framework::util::from_bytes; + use aptos_framework::storage_gas::StorageGasConfig; + use aptos_framework::storage_gas; + #[test_only] + use std::bcs::to_bytes; + + friend aptos_framework::genesis; + friend aptos_framework::reconfiguration_with_dkg; + + /// The provided gas schedule bytes are empty or invalid + const EINVALID_GAS_SCHEDULE: u64 = 1; + const EINVALID_GAS_FEATURE_VERSION: u64 = 2; + const EINVALID_GAS_SCHEDULE_HASH: u64 = 3; + + struct GasEntry has store, copy, drop { + key: String, + val: u64, + } + + struct GasSchedule has key, copy, drop { + entries: vector + } + + struct GasScheduleV2 has key, copy, drop, store { + feature_version: u64, + entries: vector, + } + + /// Only called during genesis. + public(friend) fun initialize(aptos_framework: &signer, gas_schedule_blob: vector) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(!vector::is_empty(&gas_schedule_blob), error::invalid_argument(EINVALID_GAS_SCHEDULE)); + + // TODO(Gas): check if gas schedule is consistent + let gas_schedule: GasScheduleV2 = from_bytes(gas_schedule_blob); + move_to(aptos_framework, gas_schedule); + } + + /// Deprecated by `set_for_next_epoch()`. + /// + /// WARNING: calling this while randomness is enabled will trigger a new epoch without randomness! + /// + /// TODO: update all the tests that reference this function, then disable this function. + public fun set_gas_schedule(aptos_framework: &signer, gas_schedule_blob: vector) acquires GasSchedule, GasScheduleV2 { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(!vector::is_empty(&gas_schedule_blob), error::invalid_argument(EINVALID_GAS_SCHEDULE)); + chain_status::assert_genesis(); + + if (exists(@aptos_framework)) { + let gas_schedule = borrow_global_mut(@aptos_framework); + let new_gas_schedule: GasScheduleV2 = from_bytes(gas_schedule_blob); + assert!(new_gas_schedule.feature_version >= gas_schedule.feature_version, + error::invalid_argument(EINVALID_GAS_FEATURE_VERSION)); + // TODO(Gas): check if gas schedule is consistent + *gas_schedule = new_gas_schedule; + } + else { + if (exists(@aptos_framework)) { + _ = move_from(@aptos_framework); + }; + let new_gas_schedule: GasScheduleV2 = from_bytes(gas_schedule_blob); + // TODO(Gas): check if gas schedule is consistent + move_to(aptos_framework, new_gas_schedule); + }; + + // Need to trigger reconfiguration so validator nodes can sync on the updated gas schedule. + reconfiguration::reconfigure(); + } + + /// Set the gas schedule for the next epoch, typically called by on-chain governance. + /// Abort if the version of the given schedule is lower than the current version. + /// + /// Example usage: + /// ``` + /// aptos_framework::gas_schedule::set_for_next_epoch(&framework_signer, some_gas_schedule_blob); + /// aptos_framework::aptos_governance::reconfigure(&framework_signer); + /// ``` + public fun set_for_next_epoch(aptos_framework: &signer, gas_schedule_blob: vector) acquires GasScheduleV2 { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(!vector::is_empty(&gas_schedule_blob), error::invalid_argument(EINVALID_GAS_SCHEDULE)); + let new_gas_schedule: GasScheduleV2 = from_bytes(gas_schedule_blob); + if (exists(@aptos_framework)) { + let cur_gas_schedule = borrow_global(@aptos_framework); + assert!( + new_gas_schedule.feature_version >= cur_gas_schedule.feature_version, + error::invalid_argument(EINVALID_GAS_FEATURE_VERSION) + ); + }; + config_buffer::upsert(new_gas_schedule); + } + + /// Set the gas schedule for the next epoch, typically called by on-chain governance. + /// Abort if the version of the given schedule is lower than the current version. + /// Require a hash of the old gas schedule to be provided and will abort if the hashes mismatch. + public fun set_for_next_epoch_check_hash( + aptos_framework: &signer, + old_gas_schedule_hash: vector, + new_gas_schedule_blob: vector + ) acquires GasScheduleV2 { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(!vector::is_empty(&new_gas_schedule_blob), error::invalid_argument(EINVALID_GAS_SCHEDULE)); + + let new_gas_schedule: GasScheduleV2 = from_bytes(new_gas_schedule_blob); + if (exists(@aptos_framework)) { + let cur_gas_schedule = borrow_global(@aptos_framework); + assert!( + new_gas_schedule.feature_version >= cur_gas_schedule.feature_version, + error::invalid_argument(EINVALID_GAS_FEATURE_VERSION) + ); + let cur_gas_schedule_bytes = bcs::to_bytes(cur_gas_schedule); + let cur_gas_schedule_hash = aptos_hash::sha3_512(cur_gas_schedule_bytes); + assert!( + cur_gas_schedule_hash == old_gas_schedule_hash, + error::invalid_argument(EINVALID_GAS_SCHEDULE_HASH) + ); + }; + + config_buffer::upsert(new_gas_schedule); + } + + /// Only used in reconfigurations to apply the pending `GasScheduleV2`, if there is any. + public(friend) fun on_new_epoch(framework: &signer) acquires GasScheduleV2 { + system_addresses::assert_aptos_framework(framework); + if (config_buffer::does_exist()) { + let new_gas_schedule = config_buffer::extract(); + if (exists(@aptos_framework)) { + *borrow_global_mut(@aptos_framework) = new_gas_schedule; + } else { + move_to(framework, new_gas_schedule); + } + } + } + + public fun set_storage_gas_config(aptos_framework: &signer, config: StorageGasConfig) { + storage_gas::set_config(aptos_framework, config); + // Need to trigger reconfiguration so the VM is guaranteed to load the new gas fee starting from the next + // transaction. + reconfiguration::reconfigure(); + } + + public fun set_storage_gas_config_for_next_epoch(aptos_framework: &signer, config: StorageGasConfig) { + storage_gas::set_config(aptos_framework, config); + } + + #[test(fx = @0x1)] + #[expected_failure(abort_code=0x010002, location = Self)] + fun set_for_next_epoch_should_abort_if_gas_version_is_too_old(fx: signer) acquires GasScheduleV2 { + // Setup. + let old_gas_schedule = GasScheduleV2 { + feature_version: 1000, + entries: vector[], + }; + move_to(&fx, old_gas_schedule); + + // Setting an older version should not work. + let new_gas_schedule = GasScheduleV2 { + feature_version: 999, + entries: vector[], + }; + let new_bytes = to_bytes(&new_gas_schedule); + set_for_next_epoch(&fx, new_bytes); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/genesis.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/genesis.move new file mode 100644 index 000000000..03944b937 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/genesis.move @@ -0,0 +1,559 @@ +module aptos_framework::genesis { + use std::error; + use std::fixed_point32; + use std::vector; + + use aptos_std::simple_map; + + use aptos_framework::account; + use aptos_framework::aggregator_factory; + use aptos_framework::aptos_account; + use aptos_framework::aptos_coin::{Self, AptosCoin}; + use aptos_framework::aptos_governance; + use aptos_framework::native_bridge; + use aptos_framework::block; + use aptos_framework::chain_id; + use aptos_framework::chain_status; + use aptos_framework::coin; + use aptos_framework::consensus_config; + use aptos_framework::execution_config; + use aptos_framework::create_signer::create_signer; + use aptos_framework::gas_schedule; + use aptos_framework::reconfiguration; + use aptos_framework::stake; + use aptos_framework::staking_contract; + use aptos_framework::staking_config; + use aptos_framework::state_storage; + use aptos_framework::storage_gas; + use aptos_framework::timestamp; + use aptos_framework::transaction_fee; + use aptos_framework::transaction_validation; + use aptos_framework::version; + use aptos_framework::vesting; + use aptos_framework::governed_gas_pool; + + const EDUPLICATE_ACCOUNT: u64 = 1; + const EACCOUNT_DOES_NOT_EXIST: u64 = 2; + + struct AccountMap has drop { + account_address: address, + balance: u64, + } + + struct EmployeeAccountMap has copy, drop { + accounts: vector
, + validator: ValidatorConfigurationWithCommission, + vesting_schedule_numerator: vector, + vesting_schedule_denominator: u64, + beneficiary_resetter: address, + } + + struct ValidatorConfiguration has copy, drop { + owner_address: address, + operator_address: address, + voter_address: address, + stake_amount: u64, + consensus_pubkey: vector, + proof_of_possession: vector, + network_addresses: vector, + full_node_network_addresses: vector, + } + + struct ValidatorConfigurationWithCommission has copy, drop { + validator_config: ValidatorConfiguration, + commission_percentage: u64, + join_during_genesis: bool, + } + + /// Genesis step 1: Initialize aptos framework account and core modules on chain. + fun initialize( + gas_schedule: vector, + chain_id: u8, + initial_version: u64, + consensus_config: vector, + execution_config: vector, + epoch_interval_microsecs: u64, + minimum_stake: u64, + maximum_stake: u64, + recurring_lockup_duration_secs: u64, + allow_validator_set_change: bool, + rewards_rate: u64, + rewards_rate_denominator: u64, + voting_power_increase_limit: u64, + ) { + // Initialize the aptos framework account. This is the account where system resources and modules will be + // deployed to. This will be entirely managed by on-chain governance and no entities have the key or privileges + // to use this account. + let (aptos_framework_account, aptos_framework_signer_cap) = account::create_framework_reserved_account(@aptos_framework); + // Initialize account configs on aptos framework account. + account::initialize(&aptos_framework_account); + + transaction_validation::initialize( + &aptos_framework_account, + b"script_prologue", + b"module_prologue", + b"multi_agent_script_prologue", + b"epilogue", + ); + + // Give the decentralized on-chain governance control over the core framework account. + aptos_governance::store_signer_cap(&aptos_framework_account, @aptos_framework, aptos_framework_signer_cap); + + // put reserved framework reserved accounts under aptos governance + let framework_reserved_addresses = vector
[@0x2, @0x3, @0x4, @0x5, @0x6, @0x7, @0x8, @0x9, @0xa]; + while (!vector::is_empty(&framework_reserved_addresses)) { + let address = vector::pop_back
(&mut framework_reserved_addresses); + let (_, framework_signer_cap) = account::create_framework_reserved_account(address); + aptos_governance::store_signer_cap(&aptos_framework_account, address, framework_signer_cap); + }; + + consensus_config::initialize(&aptos_framework_account, consensus_config); + execution_config::set(&aptos_framework_account, execution_config); + version::initialize(&aptos_framework_account, initial_version); + stake::initialize(&aptos_framework_account); + staking_config::initialize( + &aptos_framework_account, + minimum_stake, + maximum_stake, + recurring_lockup_duration_secs, + allow_validator_set_change, + rewards_rate, + rewards_rate_denominator, + voting_power_increase_limit, + ); + storage_gas::initialize(&aptos_framework_account); + gas_schedule::initialize(&aptos_framework_account, gas_schedule); + + // Ensure we can create aggregators for supply, but not enable it for common use just yet. + aggregator_factory::initialize_aggregator_factory(&aptos_framework_account); + coin::initialize_supply_config(&aptos_framework_account); + + chain_id::initialize(&aptos_framework_account, chain_id); + reconfiguration::initialize(&aptos_framework_account); + block::initialize(&aptos_framework_account, epoch_interval_microsecs); + state_storage::initialize(&aptos_framework_account); + timestamp::set_time_has_started(&aptos_framework_account); + native_bridge::initialize(&aptos_framework_account); + } + + /// Genesis step 2: Initialize Aptos coin. + fun initialize_aptos_coin(aptos_framework: &signer) { + let (burn_cap, mint_cap) = aptos_coin::initialize(aptos_framework); + + coin::create_coin_conversion_map(aptos_framework); + coin::create_pairing(aptos_framework); + + // Give stake module MintCapability so it can mint rewards. + stake::store_aptos_coin_mint_cap(aptos_framework, mint_cap); + // Give transaction_fee module BurnCapability so it can burn gas. + transaction_fee::store_aptos_coin_burn_cap(aptos_framework, burn_cap); + // Give transaction_fee module MintCapability so it can mint refunds. + transaction_fee::store_aptos_coin_mint_cap(aptos_framework, mint_cap); + } + + fun initialize_governed_gas_pool( + aptos_framework: &signer, + delegation_pool_creation_seed: vector, + ) { + governed_gas_pool::initialize(aptos_framework, delegation_pool_creation_seed); + } + + /// Only called for testnets and e2e tests. + fun initialize_core_resources_and_aptos_coin( + aptos_framework: &signer, + core_resources_auth_key: vector, + ) { + let (burn_cap, mint_cap) = aptos_coin::initialize(aptos_framework); + + coin::create_coin_conversion_map(aptos_framework); + coin::create_pairing(aptos_framework); + + // Give stake module MintCapability so it can mint rewards. + stake::store_aptos_coin_mint_cap(aptos_framework, mint_cap); + // Give transaction_fee module BurnCapability so it can burn gas. + transaction_fee::store_aptos_coin_burn_cap(aptos_framework, burn_cap); + // Give transaction_fee module MintCapability so it can mint refunds. + transaction_fee::store_aptos_coin_mint_cap(aptos_framework, mint_cap); + let core_resources = account::create_account(@core_resources); + account::rotate_authentication_key_internal(&core_resources, core_resources_auth_key); + aptos_account::register_apt(&core_resources); // registers APT store + aptos_coin::configure_accounts_for_test(aptos_framework, &core_resources, mint_cap); + } + + fun create_accounts(aptos_framework: &signer, accounts: vector) { + let unique_accounts = vector::empty(); + vector::for_each_ref(&accounts, |account_map| { + let account_map: &AccountMap = account_map; + assert!( + !vector::contains(&unique_accounts, &account_map.account_address), + error::already_exists(EDUPLICATE_ACCOUNT), + ); + vector::push_back(&mut unique_accounts, account_map.account_address); + + create_account( + aptos_framework, + account_map.account_address, + account_map.balance, + ); + }); + } + + /// This creates an funds an account if it doesn't exist. + /// If it exists, it just returns the signer. + fun create_account(aptos_framework: &signer, account_address: address, balance: u64): signer { + if (account::exists_at(account_address)) { + create_signer(account_address) + } else { + let account = account::create_account(account_address); + coin::register(&account); + aptos_coin::mint(aptos_framework, account_address, balance); + account + } + } + + fun create_employee_validators( + employee_vesting_start: u64, + employee_vesting_period_duration: u64, + employees: vector, + ) { + let unique_accounts = vector::empty(); + + vector::for_each_ref(&employees, |employee_group| { + let j = 0; + let employee_group: &EmployeeAccountMap = employee_group; + let num_employees_in_group = vector::length(&employee_group.accounts); + + let buy_ins = simple_map::create(); + + while (j < num_employees_in_group) { + let account = vector::borrow(&employee_group.accounts, j); + assert!( + !vector::contains(&unique_accounts, account), + error::already_exists(EDUPLICATE_ACCOUNT), + ); + vector::push_back(&mut unique_accounts, *account); + + let employee = create_signer(*account); + let total = coin::balance(*account); + let coins = coin::withdraw(&employee, total); + simple_map::add(&mut buy_ins, *account, coins); + + j = j + 1; + }; + + let j = 0; + let num_vesting_events = vector::length(&employee_group.vesting_schedule_numerator); + let schedule = vector::empty(); + + while (j < num_vesting_events) { + let numerator = vector::borrow(&employee_group.vesting_schedule_numerator, j); + let event = fixed_point32::create_from_rational(*numerator, employee_group.vesting_schedule_denominator); + vector::push_back(&mut schedule, event); + + j = j + 1; + }; + + let vesting_schedule = vesting::create_vesting_schedule( + schedule, + employee_vesting_start, + employee_vesting_period_duration, + ); + + let admin = employee_group.validator.validator_config.owner_address; + let admin_signer = &create_signer(admin); + let contract_address = vesting::create_vesting_contract( + admin_signer, + &employee_group.accounts, + buy_ins, + vesting_schedule, + admin, + employee_group.validator.validator_config.operator_address, + employee_group.validator.validator_config.voter_address, + employee_group.validator.commission_percentage, + x"", + ); + let pool_address = vesting::stake_pool_address(contract_address); + + if (employee_group.beneficiary_resetter != @0x0) { + vesting::set_beneficiary_resetter(admin_signer, contract_address, employee_group.beneficiary_resetter); + }; + + let validator = &employee_group.validator.validator_config; + assert!( + account::exists_at(validator.owner_address), + error::not_found(EACCOUNT_DOES_NOT_EXIST), + ); + assert!( + account::exists_at(validator.operator_address), + error::not_found(EACCOUNT_DOES_NOT_EXIST), + ); + assert!( + account::exists_at(validator.voter_address), + error::not_found(EACCOUNT_DOES_NOT_EXIST), + ); + if (employee_group.validator.join_during_genesis) { + initialize_validator(pool_address, validator); + }; + }); + } + + fun create_initialize_validators_with_commission( + aptos_framework: &signer, + use_staking_contract: bool, + validators: vector, + ) { + vector::for_each_ref(&validators, |validator| { + let validator: &ValidatorConfigurationWithCommission = validator; + create_initialize_validator(aptos_framework, validator, use_staking_contract); + }); + + // Destroy the aptos framework account's ability to mint coins now that we're done with setting up the initial + // validators. + aptos_coin::destroy_mint_cap(aptos_framework); + + stake::on_new_epoch(); + } + + /// Sets up the initial validator set for the network. + /// The validator "owner" accounts, and their authentication + /// Addresses (and keys) are encoded in the `owners` + /// Each validator signs consensus messages with the private key corresponding to the Ed25519 + /// public key in `consensus_pubkeys`. + /// Finally, each validator must specify the network address + /// (see types/src/network_address/mod.rs) for itself and its full nodes. + /// + /// Network address fields are a vector per account, where each entry is a vector of addresses + /// encoded in a single BCS byte array. + fun create_initialize_validators(aptos_framework: &signer, validators: vector) { + let validators_with_commission = vector::empty(); + vector::for_each_reverse(validators, |validator| { + let validator_with_commission = ValidatorConfigurationWithCommission { + validator_config: validator, + commission_percentage: 0, + join_during_genesis: true, + }; + vector::push_back(&mut validators_with_commission, validator_with_commission); + }); + + create_initialize_validators_with_commission(aptos_framework, false, validators_with_commission); + } + + fun create_initialize_validator( + aptos_framework: &signer, + commission_config: &ValidatorConfigurationWithCommission, + use_staking_contract: bool, + ) { + let validator = &commission_config.validator_config; + + let owner = &create_account(aptos_framework, validator.owner_address, validator.stake_amount); + create_account(aptos_framework, validator.operator_address, 0); + create_account(aptos_framework, validator.voter_address, 0); + + // Initialize the stake pool and join the validator set. + let pool_address = if (use_staking_contract) { + staking_contract::create_staking_contract( + owner, + validator.operator_address, + validator.voter_address, + validator.stake_amount, + commission_config.commission_percentage, + x"", + ); + staking_contract::stake_pool_address(validator.owner_address, validator.operator_address) + } else { + stake::initialize_stake_owner( + owner, + validator.stake_amount, + validator.operator_address, + validator.voter_address, + ); + validator.owner_address + }; + + if (commission_config.join_during_genesis) { + initialize_validator(pool_address, validator); + }; + } + + fun initialize_validator(pool_address: address, validator: &ValidatorConfiguration) { + let operator = &create_signer(validator.operator_address); + + stake::rotate_consensus_key( + operator, + pool_address, + validator.consensus_pubkey, + validator.proof_of_possession, + ); + stake::update_network_and_fullnode_addresses( + operator, + pool_address, + validator.network_addresses, + validator.full_node_network_addresses, + ); + stake::join_validator_set_internal(operator, pool_address); + } + + /// The last step of genesis. + fun set_genesis_end(aptos_framework: &signer) { + chain_status::set_genesis_end(aptos_framework); + } + + #[verify_only] + use std::features; + + #[verify_only] + fun initialize_for_verification( + gas_schedule: vector, + chain_id: u8, + initial_version: u64, + consensus_config: vector, + execution_config: vector, + epoch_interval_microsecs: u64, + minimum_stake: u64, + maximum_stake: u64, + recurring_lockup_duration_secs: u64, + allow_validator_set_change: bool, + rewards_rate: u64, + rewards_rate_denominator: u64, + voting_power_increase_limit: u64, + aptos_framework: &signer, + min_voting_threshold: u128, + required_proposer_stake: u64, + voting_duration_secs: u64, + accounts: vector, + employee_vesting_start: u64, + employee_vesting_period_duration: u64, + employees: vector, + validators: vector + ) { + initialize( + gas_schedule, + chain_id, + initial_version, + consensus_config, + execution_config, + epoch_interval_microsecs, + minimum_stake, + maximum_stake, + recurring_lockup_duration_secs, + allow_validator_set_change, + rewards_rate, + rewards_rate_denominator, + voting_power_increase_limit + ); + features::change_feature_flags_for_verification(aptos_framework, vector[1, 2], vector[]); + initialize_aptos_coin(aptos_framework); + aptos_governance::initialize_for_verification( + aptos_framework, + min_voting_threshold, + required_proposer_stake, + voting_duration_secs + ); + create_accounts(aptos_framework, accounts); + create_employee_validators(employee_vesting_start, employee_vesting_period_duration, employees); + create_initialize_validators_with_commission(aptos_framework, true, validators); + set_genesis_end(aptos_framework); + } + + #[test_only] + public fun setup() { + initialize( + x"000000000000000000", // empty gas schedule + 4u8, // TESTING chain ID + 0, + x"12", + x"13", + 1, + 0, + 1, + 1, + true, + 1, + 1, + 30, + ) + } + + #[test] + fun test_setup() { + setup(); + assert!(account::exists_at(@aptos_framework), 1); + assert!(account::exists_at(@0x2), 1); + assert!(account::exists_at(@0x3), 1); + assert!(account::exists_at(@0x4), 1); + assert!(account::exists_at(@0x5), 1); + assert!(account::exists_at(@0x6), 1); + assert!(account::exists_at(@0x7), 1); + assert!(account::exists_at(@0x8), 1); + assert!(account::exists_at(@0x9), 1); + assert!(account::exists_at(@0xa), 1); + } + + #[test(aptos_framework = @0x1)] + fun test_create_account(aptos_framework: &signer) { + setup(); + initialize_aptos_coin(aptos_framework); + + let addr = @0x121341; // 01 -> 0a are taken + let test_signer_before = create_account(aptos_framework, addr, 15); + let test_signer_after = create_account(aptos_framework, addr, 500); + assert!(test_signer_before == test_signer_after, 0); + assert!(coin::balance(addr) == 15, 1); + } + + #[test(aptos_framework = @0x1)] + fun test_create_accounts(aptos_framework: &signer) { + setup(); + initialize_aptos_coin(aptos_framework); + + // 01 -> 0a are taken + let addr0 = @0x121341; + let addr1 = @0x121345; + + let accounts = vector[ + AccountMap { + account_address: addr0, + balance: 12345, + }, + AccountMap { + account_address: addr1, + balance: 67890, + }, + ]; + + create_accounts(aptos_framework, accounts); + assert!(coin::balance(addr0) == 12345, 0); + assert!(coin::balance(addr1) == 67890, 1); + + create_account(aptos_framework, addr0, 23456); + assert!(coin::balance(addr0) == 12345, 2); + } + + #[test(aptos_framework = @0x1, root = @0xabcd)] + fun test_create_root_account(aptos_framework: &signer) { + use aptos_framework::aggregator_factory; + use aptos_framework::object; + use aptos_framework::primary_fungible_store; + use aptos_framework::fungible_asset::Metadata; + use std::features; + + let feature = features::get_new_accounts_default_to_fa_apt_store_feature(); + features::change_feature_flags_for_testing(aptos_framework, vector[feature], vector[]); + + aggregator_factory::initialize_aggregator_factory_for_test(aptos_framework); + + let (burn_cap, mint_cap) = aptos_coin::initialize(aptos_framework); + aptos_coin::ensure_initialized_with_apt_fa_metadata_for_test(); + + let core_resources = account::create_account(@core_resources); + aptos_account::register_apt(&core_resources); // registers APT store + + let apt_metadata = object::address_to_object(@aptos_fungible_asset); + assert!(primary_fungible_store::primary_store_exists(@core_resources, apt_metadata), 2); + + aptos_coin::configure_accounts_for_test(aptos_framework, &core_resources, mint_cap); + + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/governance_proposal.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/governance_proposal.move new file mode 100644 index 000000000..bae6c7d73 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/governance_proposal.move @@ -0,0 +1,23 @@ +/// Define the GovernanceProposal that will be used as part of on-chain governance by AptosGovernance. +/// +/// This is separate from the AptosGovernance module to avoid circular dependency between AptosGovernance and Stake. +module aptos_framework::governance_proposal { + friend aptos_framework::aptos_governance; + + struct GovernanceProposal has store, drop {} + + /// Create and return a GovernanceProposal resource. Can only be called by AptosGovernance + public(friend) fun create_proposal(): GovernanceProposal { + GovernanceProposal {} + } + + /// Useful for AptosGovernance to create an empty proposal as proof. + public(friend) fun create_empty_proposal(): GovernanceProposal { + create_proposal() + } + + #[test_only] + public fun create_test_proposal(): GovernanceProposal { + create_empty_proposal() + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/governed_gas_pool.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/governed_gas_pool.move new file mode 100644 index 000000000..848cd62fc --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/governed_gas_pool.move @@ -0,0 +1,351 @@ +module aptos_framework::governed_gas_pool { + + friend aptos_framework::transaction_validation; + + use std::vector; + use aptos_framework::account::{Self, SignerCapability, create_signer_with_capability}; + use aptos_framework::system_addresses::{Self}; + // use aptos_framework::primary_fungible_store::{Self}; + use aptos_framework::fungible_asset::{Self}; + use aptos_framework::object::{Self}; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::coin::{Self, Coin}; + use std::features; + use aptos_framework::signer; + use aptos_framework::aptos_account::Self; + #[test_only] + use aptos_framework::coin::{BurnCapability, MintCapability}; + #[test_only] + use aptos_framework::fungible_asset::BurnRef; + #[test_only] + use aptos_framework::aptos_coin::Self; + + const MODULE_SALT: vector = b"aptos_framework::governed_gas_pool"; + + /// The Governed Gas Pool + /// Internally, this is a simply wrapper around a resource account. + struct GovernedGasPool has key { + /// The signer capability of the resource account. + signer_capability: SignerCapability, + } + + /// Address of APT Primary Fungible Store + inline fun primary_fungible_store_address(account: address): address { + object::create_user_derived_object_address(account, @aptos_fungible_asset) + } + + /// Create the seed to derive the resource account address. + fun create_resource_account_seed( + delegation_pool_creation_seed: vector, + ): vector { + let seed = vector::empty(); + // include module salt (before any subseeds) to avoid conflicts with other modules creating resource accounts + vector::append(&mut seed, MODULE_SALT); + // include an additional salt in case the same resource account has already been created + vector::append(&mut seed, delegation_pool_creation_seed); + seed + } + + /// Initializes the governed gas pool around a resource account creation seed. + /// @param aptos_framework The signer of the aptos_framework module. + /// @param delegation_pool_creation_seed The seed to be used to create the resource account hosting the delegation pool. + public fun initialize( + aptos_framework: &signer, + delegation_pool_creation_seed: vector, + ) { + system_addresses::assert_aptos_framework(aptos_framework); + + // generate a seed to be used to create the resource account hosting the delegation pool + let seed = create_resource_account_seed(delegation_pool_creation_seed); + + let (governed_gas_pool_signer, governed_gas_pool_signer_cap) = account::create_resource_account(aptos_framework, seed); + + // register apt + aptos_account::register_apt(&governed_gas_pool_signer); + + move_to(aptos_framework, GovernedGasPool{ + signer_capability: governed_gas_pool_signer_cap, + }); + } + + /// Initialize the governed gas pool as a module + /// @param aptos_framework The signer of the aptos_framework module. + fun init_module(aptos_framework: &signer) { + // Initialize the governed gas pool + let seed : vector = b"aptos_framework::governed_gas_pool"; + initialize(aptos_framework, seed); + } + + /// Borrows the signer of the governed gas pool. + /// @return The signer of the governed gas pool. + fun governed_gas_signer(): signer acquires GovernedGasPool { + let signer_cap = &borrow_global(@aptos_framework).signer_capability; + create_signer_with_capability(signer_cap) + } + + #[view] + /// Gets the address of the governed gas pool. + /// @return The address of the governed gas pool. + public fun governed_gas_pool_address(): address acquires GovernedGasPool { + signer::address_of(&governed_gas_signer()) + } + + /// Funds the destination account with a given amount of coin. + /// @param account The account to be funded. + /// @param amount The amount of coin to be funded. + public fun fund(aptos_framework: &signer, account: address, amount: u64) acquires GovernedGasPool { + // Check that the Aptos framework is the caller + // This is what ensures that funding can only be done by the Aptos framework, + // i.e., via a governance proposal. + system_addresses::assert_aptos_framework(aptos_framework); + let governed_gas_signer = &governed_gas_signer(); + coin::deposit(account, coin::withdraw(governed_gas_signer, amount)); + } + + /// Deposits some coin into the governed gas pool. + /// @param coin The coin to be deposited. + fun deposit(coin: Coin) acquires GovernedGasPool { + let governed_gas_pool_address = governed_gas_pool_address(); + coin::deposit(governed_gas_pool_address, coin); + } + + /// Deposits some coin from an account to the governed gas pool. + /// @param account The account from which the coin is to be deposited. + /// @param amount The amount of coin to be deposited. + fun deposit_from(account: address, amount: u64) acquires GovernedGasPool { + deposit(coin::withdraw_from(account, amount)); + } + + /// Deposits some FA from the fungible store. + /// @param aptos_framework The signer of the aptos_framework module. + /// @param account The account from which the FA is to be deposited. + /// @param amount The amount of FA to be deposited. + fun deposit_from_fungible_store(account: address, amount: u64) acquires GovernedGasPool { + if (amount > 0){ + // compute the governed gas pool store address + let governed_gas_pool_address = governed_gas_pool_address(); + let governed_gas_pool_store_address = primary_fungible_store_address(governed_gas_pool_address); + + // compute the account store address + let account_store_address = primary_fungible_store_address(account); + fungible_asset::deposit_internal( + governed_gas_pool_store_address, + fungible_asset::withdraw_internal( + account_store_address, + amount + ) + ); + } + } + + /// Deposits gas fees into the governed gas pool. + /// @param gas_payer The address of the account that paid the gas fees. + /// @param gas_fee The amount of gas fees to be deposited. + public fun deposit_gas_fee(gas_payer: address, gas_fee: u64) acquires GovernedGasPool { + // get the sender to preserve the signature but do nothing + governed_gas_pool_address(); + } + + /// Deposits gas fees into the governed gas pool. + /// @param gas_payer The address of the account that paid the gas fees. + /// @param gas_fee The amount of gas fees to be deposited. + public(friend) fun deposit_gas_fee_v2(gas_payer: address, gas_fee: u64) acquires GovernedGasPool { + if (features::operations_default_to_fa_apt_store_enabled()) { + deposit_from_fungible_store(gas_payer, gas_fee); + } else { + deposit_from(gas_payer, gas_fee); + }; + } + + #[view] + /// Gets the balance of a specified coin type in the governed gas pool. + /// @return The balance of the coin in the pool. + public fun get_balance(): u64 acquires GovernedGasPool { + let pool_address = governed_gas_pool_address(); + coin::balance(pool_address) + } + + #[test_only] + /// The AptosCoin mint capability + struct AptosCoinMintCapability has key { + mint_cap: MintCapability, + } + + #[test_only] + /// The AptosCoin burn capability + struct AptosCoinBurnCapability has key { + burn_cap: BurnCapability, + } + + #[test_only] + /// The AptosFA burn capabilities + struct AptosFABurnCapabilities has key { + burn_ref: BurnRef, + } + + + #[test_only] + /// Stores the mint capability for AptosCoin. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param mint_cap The mint capability for AptosCoin. + public fun store_aptos_coin_mint_cap(aptos_framework: &signer, mint_cap: MintCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, AptosCoinMintCapability { mint_cap }) + } + + #[test_only] + /// Stores the burn capability for AptosCoin, converting to a fungible asset reference if the feature is enabled. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param burn_cap The burn capability for AptosCoin. + public fun store_aptos_coin_burn_cap(aptos_framework: &signer, burn_cap: BurnCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + if (features::operations_default_to_fa_apt_store_enabled()) { + let burn_ref = coin::convert_and_take_paired_burn_ref(burn_cap); + move_to(aptos_framework, AptosFABurnCapabilities { burn_ref }); + } else { + move_to(aptos_framework, AptosCoinBurnCapability { burn_cap }) + } + } + + #[test_only] + /// Initializes the governed gas pool around a fixed creation seed for testing + /// + /// @param aptos_framework The signer of the aptos_framework module. + public fun initialize_for_test( + aptos_framework: &signer, + ) { + + // initialize the AptosCoin module + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(aptos_framework); + + // Initialize the governed gas pool + let seed : vector = b"test"; + initialize(aptos_framework, seed); + + // add the mint capability to the governed gas pool + store_aptos_coin_mint_cap(aptos_framework, mint_cap); + store_aptos_coin_burn_cap(aptos_framework, burn_cap); + + } + + #[test_only] + /// Mints some coin to an account for testing purposes. + /// + /// @param account The account to which the coin is to be minted. + /// @param amount The amount of coin to be minted. + public fun mint_for_test(account: address, amount: u64) acquires AptosCoinMintCapability { + coin::deposit(account, coin::mint( + amount, + &borrow_global(@aptos_framework).mint_cap + )); + } + + #[test(aptos_framework = @aptos_framework, depositor = @0xdddd)] + /// Deposits some coin into the governed gas pool. + /// + /// @param aptos_framework is the signer of the aptos_framework module. + fun test_governed_gas_pool_deposit(aptos_framework: &signer, depositor: &signer) acquires GovernedGasPool, AptosCoinMintCapability { + + // initialize the modules + initialize_for_test(aptos_framework); + + // create the depositor account and fund it + aptos_account::create_account(signer::address_of(depositor)); + mint_for_test(signer::address_of(depositor), 1000); + + // get the balances for the depositor and the governed gas pool + let depositor_balance = coin::balance(signer::address_of(depositor)); + let governed_gas_pool_balance = coin::balance(governed_gas_pool_address()); + + // deposit some coin into the governed gas pool + deposit_from(signer::address_of(depositor), 100); + + // check the balances after the deposit + assert!(coin::balance(signer::address_of(depositor)) == depositor_balance - 100, 1); + assert!(coin::balance(governed_gas_pool_address()) == governed_gas_pool_balance + 100, 2); + + } + + #[test(aptos_framework = @aptos_framework, depositor = @0xdddd)] + /// Deposits some coin from an account to the governed gas pool as gas fees. + /// + /// @param aptos_framework is the signer of the aptos_framework module. + /// @param depositor is the signer of the account from which the coin is to be deposited. + fun test_governed_gas_pool_deposit_gas_fee(aptos_framework: &signer, depositor: &signer) acquires GovernedGasPool, AptosCoinMintCapability { + + // initialize the modules + initialize_for_test(aptos_framework); + + // create the depositor account and fund it + aptos_account::create_account(signer::address_of(depositor)); + mint_for_test(signer::address_of(depositor), 1000); + + // get the balances for the depositor and the governed gas pool + let depositor_balance = coin::balance(signer::address_of(depositor)); + let governed_gas_pool_balance = coin::balance(governed_gas_pool_address()); + + // deposit some coin into the governed gas pool as gas fees + deposit_gas_fee_v2(signer::address_of(depositor), 100); + + // check the balances after the deposit + assert!(coin::balance(signer::address_of(depositor)) == depositor_balance - 100, 1); + assert!(coin::balance(governed_gas_pool_address()) == governed_gas_pool_balance + 100, 2); + + } + + #[test(aptos_framework = @aptos_framework)] + /// Test for the get_balance view method. + fun test_governed_gas_pool_get_balance(aptos_framework: &signer) acquires GovernedGasPool, AptosCoinMintCapability { + + // initialize the modules + initialize_for_test(aptos_framework); + + // fund the governed gas pool + let governed_gas_pool_address = governed_gas_pool_address(); + mint_for_test(governed_gas_pool_address, 1000); + + // assert the balance is correct + assert!(get_balance() == 1000, 1); + } + + #[test(aptos_framework = @aptos_framework, depositor = @0xdddd, beneficiary = @0xbbbb)] + /// Funds the destination account with a given amount of coin. + /// + /// @param aptos_framework is the signer of the aptos_framework module. + /// @param depositor is the signer of the account from which the coin is to be funded. + /// @param beneficiary is the address of the account to be funded. + fun test_governed_gas_pool_fund(aptos_framework: &signer, depositor: &signer, beneficiary: &signer) acquires GovernedGasPool, AptosCoinMintCapability { + + // initialize the modules + initialize_for_test(aptos_framework); + + // create the depositor account and fund it + aptos_account::create_account(signer::address_of(depositor)); + mint_for_test(signer::address_of(depositor), 1000); + + // get the balances for the depositor and the governed gas pool + let depositor_balance = coin::balance(signer::address_of(depositor)); + let governed_gas_pool_balance = coin::balance(governed_gas_pool_address()); + + // collect gas fees from the depositor + deposit_gas_fee_v2(signer::address_of(depositor), 100); + + // check the balances after the deposit + assert!(coin::balance(signer::address_of(depositor)) == depositor_balance - 100, 1); + assert!(coin::balance(governed_gas_pool_address()) == governed_gas_pool_balance + 100, 2); + + // ensure the beneficiary account has registered with the AptosCoin module + aptos_account::create_account(signer::address_of(beneficiary)); + aptos_account::register_apt(beneficiary); + + // fund the beneficiary account + fund(aptos_framework, signer::address_of(beneficiary), 100); + + // check the balances after the funding + assert!(coin::balance(governed_gas_pool_address()) == governed_gas_pool_balance, 3); + assert!(coin::balance(signer::address_of(beneficiary)) == 100, 4); + + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/guid.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/guid.move new file mode 100644 index 000000000..e6334bbad --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/guid.move @@ -0,0 +1,68 @@ +/// A module for generating globally unique identifiers +module aptos_framework::guid { + friend aptos_framework::account; + friend aptos_framework::object; + + /// A globally unique identifier derived from the sender's address and a counter + struct GUID has drop, store { + id: ID + } + + /// A non-privileged identifier that can be freely created by anyone. Useful for looking up GUID's. + struct ID has copy, drop, store { + /// If creation_num is `i`, this is the `i+1`th GUID created by `addr` + creation_num: u64, + /// Address that created the GUID + addr: address + } + + /// GUID generator must be published ahead of first usage of `create_with_capability` function. + const EGUID_GENERATOR_NOT_PUBLISHED: u64 = 0; + + /// Create and return a new GUID from a trusted module. + public(friend) fun create(addr: address, creation_num_ref: &mut u64): GUID { + let creation_num = *creation_num_ref; + *creation_num_ref = creation_num + 1; + GUID { + id: ID { + creation_num, + addr, + } + } + } + + /// Create a non-privileged id from `addr` and `creation_num` + public fun create_id(addr: address, creation_num: u64): ID { + ID { creation_num, addr } + } + + /// Get the non-privileged ID associated with a GUID + public fun id(guid: &GUID): ID { + guid.id + } + + /// Return the account address that created the GUID + public fun creator_address(guid: &GUID): address { + guid.id.addr + } + + /// Return the account address that created the guid::ID + public fun id_creator_address(id: &ID): address { + id.addr + } + + /// Return the creation number associated with the GUID + public fun creation_num(guid: &GUID): u64 { + guid.id.creation_num + } + + /// Return the creation number associated with the guid::ID + public fun id_creation_num(id: &ID): u64 { + id.creation_num + } + + /// Return true if the GUID's ID is `id` + public fun eq_id(guid: &GUID, id: &ID): bool { + &guid.id == id + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/jwk_consensus_config.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/jwk_consensus_config.move new file mode 100644 index 000000000..bba0276e7 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/jwk_consensus_config.move @@ -0,0 +1,148 @@ +/// Structs and functions related to JWK consensus configurations. +module aptos_framework::jwk_consensus_config { + use std::error; + use std::option; + use std::string::String; + use std::vector; + use aptos_std::copyable_any; + use aptos_std::copyable_any::Any; + use aptos_std::simple_map; + use aptos_framework::config_buffer; + use aptos_framework::system_addresses; + #[test_only] + use std::string; + #[test_only] + use std::string::utf8; + + friend aptos_framework::reconfiguration_with_dkg; + + /// `ConfigV1` creation failed with duplicated providers given. + const EDUPLICATE_PROVIDERS: u64 = 1; + + /// The configuration of the JWK consensus feature. + struct JWKConsensusConfig has drop, key, store { + /// A config variant packed as an `Any`. + /// Currently the variant type is one of the following. + /// - `ConfigOff` + /// - `ConfigV1` + variant: Any, + } + + /// A JWK consensus config variant indicating JWK consensus should not run. + struct ConfigOff has copy, drop, store {} + + struct OIDCProvider has copy, drop, store { + name: String, + config_url: String, + } + + /// A JWK consensus config variant indicating JWK consensus should run to watch a given list of OIDC providers. + struct ConfigV1 has copy, drop, store { + oidc_providers: vector, + } + + /// Initialize the configuration. Used in genesis or governance. + public fun initialize(framework: &signer, config: JWKConsensusConfig) { + system_addresses::assert_aptos_framework(framework); + if (!exists(@aptos_framework)) { + move_to(framework, config); + } + } + + /// This can be called by on-chain governance to update JWK consensus configs for the next epoch. + /// Example usage: + /// ``` + /// use aptos_framework::jwk_consensus_config; + /// use aptos_framework::aptos_governance; + /// // ... + /// let config = jwk_consensus_config::new_v1(vector[]); + /// jwk_consensus_config::set_for_next_epoch(&framework_signer, config); + /// aptos_governance::reconfigure(&framework_signer); + /// ``` + public fun set_for_next_epoch(framework: &signer, config: JWKConsensusConfig) { + system_addresses::assert_aptos_framework(framework); + config_buffer::upsert(config); + } + + /// Only used in reconfigurations to apply the pending `JWKConsensusConfig`, if there is any. + public(friend) fun on_new_epoch(framework: &signer) acquires JWKConsensusConfig { + system_addresses::assert_aptos_framework(framework); + if (config_buffer::does_exist()) { + let new_config = config_buffer::extract(); + if (exists(@aptos_framework)) { + *borrow_global_mut(@aptos_framework) = new_config; + } else { + move_to(framework, new_config); + }; + } + } + + /// Construct a `JWKConsensusConfig` of variant `ConfigOff`. + public fun new_off(): JWKConsensusConfig { + JWKConsensusConfig { + variant: copyable_any::pack( ConfigOff {} ) + } + } + + /// Construct a `JWKConsensusConfig` of variant `ConfigV1`. + /// + /// Abort if the given provider list contains duplicated provider names. + public fun new_v1(oidc_providers: vector): JWKConsensusConfig { + let name_set = simple_map::new(); + vector::for_each_ref(&oidc_providers, |provider| { + let provider: &OIDCProvider = provider; + let (_, old_value) = simple_map::upsert(&mut name_set, provider.name, 0); + if (option::is_some(&old_value)) { + abort(error::invalid_argument(EDUPLICATE_PROVIDERS)) + } + }); + JWKConsensusConfig { + variant: copyable_any::pack( ConfigV1 { oidc_providers } ) + } + } + + /// Construct an `OIDCProvider` object. + public fun new_oidc_provider(name: String, config_url: String): OIDCProvider { + OIDCProvider { name, config_url } + } + + #[test_only] + fun enabled(): bool acquires JWKConsensusConfig { + let variant= borrow_global(@aptos_framework).variant; + let variant_type_name = *string::bytes(copyable_any::type_name(&variant)); + variant_type_name != b"0x1::jwk_consensus_config::ConfigOff" + } + + #[test_only] + fun initialize_for_testing(framework: &signer) { + config_buffer::initialize(framework); + initialize(framework, new_off()); + } + + #[test(framework = @0x1)] + fun init_buffer_apply(framework: signer) acquires JWKConsensusConfig { + initialize_for_testing(&framework); + let config = new_v1(vector[ + new_oidc_provider(utf8(b"Bob"), utf8(b"https://bob.dev")), + new_oidc_provider(utf8(b"Alice"), utf8(b"https://alice.io")), + ]); + set_for_next_epoch(&framework, config); + on_new_epoch(&framework); + assert!(enabled(), 1); + + set_for_next_epoch(&framework, new_off()); + on_new_epoch(&framework); + assert!(!enabled(), 2) + } + + #[test] + #[expected_failure(abort_code = 0x010001, location = Self)] + fun name_uniqueness_in_config_v1() { + new_v1(vector[ + new_oidc_provider(utf8(b"Alice"), utf8(b"https://alice.info")), + new_oidc_provider(utf8(b"Bob"), utf8(b"https://bob.dev")), + new_oidc_provider(utf8(b"Alice"), utf8(b"https://alice.io")), + ]); + + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/jwks.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/jwks.move new file mode 100644 index 000000000..c0bcdc746 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/jwks.move @@ -0,0 +1,776 @@ +/// JWK functions and structs. +/// +/// Note: An important design constraint for this module is that the JWK consensus Rust code is unable to +/// spawn a VM and make a Move function call. Instead, the JWK consensus Rust code will have to directly +/// write some of the resources in this file. As a result, the structs in this file are declared so as to +/// have a simple layout which is easily accessible in Rust. +module aptos_framework::jwks { + use std::error; + use std::option; + use std::option::Option; + use std::string; + use std::string::{String, utf8}; + use std::vector; + use aptos_std::comparator::{compare_u8_vector, is_greater_than, is_equal}; + use aptos_std::copyable_any; + use aptos_std::copyable_any::Any; + use aptos_framework::chain_status; + use aptos_framework::config_buffer; + use aptos_framework::event::emit; + use aptos_framework::reconfiguration; + use aptos_framework::system_addresses; + #[test_only] + use aptos_framework::account::create_account_for_test; + + friend aptos_framework::genesis; + friend aptos_framework::reconfiguration_with_dkg; + + const EUNEXPECTED_EPOCH: u64 = 1; + const EUNEXPECTED_VERSION: u64 = 2; + const EUNKNOWN_PATCH_VARIANT: u64 = 3; + const EUNKNOWN_JWK_VARIANT: u64 = 4; + const EISSUER_NOT_FOUND: u64 = 5; + const EJWK_ID_NOT_FOUND: u64 = 6; + + const ENATIVE_MISSING_RESOURCE_VALIDATOR_SET: u64 = 0x0101; + const ENATIVE_MISSING_RESOURCE_OBSERVED_JWKS: u64 = 0x0102; + const ENATIVE_INCORRECT_VERSION: u64 = 0x0103; + const ENATIVE_MULTISIG_VERIFICATION_FAILED: u64 = 0x0104; + const ENATIVE_NOT_ENOUGH_VOTING_POWER: u64 = 0x0105; + + /// An OIDC provider. + struct OIDCProvider has copy, drop, store { + /// The utf-8 encoded issuer string. E.g., b"https://www.facebook.com". + name: vector, + + /// The ut8-8 encoded OpenID configuration URL of the provider. + /// E.g., b"https://www.facebook.com/.well-known/openid-configuration/". + config_url: vector, + } + + /// A list of OIDC providers whose JWKs should be watched by validators. Maintained by governance proposals. + struct SupportedOIDCProviders has copy, drop, key, store { + providers: vector, + } + + /// An JWK variant that represents the JWKs which were observed but not yet supported by Aptos. + /// Observing `UnsupportedJWK`s means the providers adopted a new key type/format, and the system should be updated. + struct UnsupportedJWK has copy, drop, store { + id: vector, + payload: vector, + } + + /// A JWK variant where `kty` is `RSA`. + struct RSA_JWK has copy, drop, store { + kid: String, + kty: String, + alg: String, + e: String, + n: String, + } + + /// A JSON web key. + struct JWK has copy, drop, store { + /// A `JWK` variant packed as an `Any`. + /// Currently the variant type is one of the following. + /// - `RSA_JWK` + /// - `UnsupportedJWK` + variant: Any, + } + + /// A provider and its `JWK`s. + struct ProviderJWKs has copy, drop, store { + /// The utf-8 encoding of the issuer string (e.g., "https://www.facebook.com"). + issuer: vector, + + /// A version number is needed by JWK consensus to dedup the updates. + /// e.g, when on chain version = 5, multiple nodes can propose an update with version = 6. + /// Bumped every time the JWKs for the current issuer is updated. + /// The Rust authenticator only uses the latest version. + version: u64, + + /// Vector of `JWK`'s sorted by their unique ID (from `get_jwk_id`) in dictionary order. + jwks: vector, + } + + /// Multiple `ProviderJWKs` objects, indexed by issuer and key ID. + struct AllProvidersJWKs has copy, drop, store { + /// Vector of `ProviderJWKs` sorted by `ProviderJWKs::issuer` in dictionary order. + entries: vector, + } + + /// The `AllProvidersJWKs` that validators observed and agreed on. + struct ObservedJWKs has copy, drop, key, store { + jwks: AllProvidersJWKs, + } + + #[event] + /// When `ObservedJWKs` is updated, this event is sent to resync the JWK consensus state in all validators. + struct ObservedJWKsUpdated has drop, store { + epoch: u64, + jwks: AllProvidersJWKs, + } + + /// A small edit or patch that is applied to a `AllProvidersJWKs` to obtain `PatchedJWKs`. + struct Patch has copy, drop, store { + /// A `Patch` variant packed as an `Any`. + /// Currently the variant type is one of the following. + /// - `PatchRemoveAll` + /// - `PatchRemoveIssuer` + /// - `PatchRemoveJWK` + /// - `PatchUpsertJWK` + variant: Any, + } + + /// A `Patch` variant to remove all JWKs. + struct PatchRemoveAll has copy, drop, store {} + + /// A `Patch` variant to remove an issuer and all its JWKs. + struct PatchRemoveIssuer has copy, drop, store { + issuer: vector, + } + + /// A `Patch` variant to remove a specific JWK of an issuer. + struct PatchRemoveJWK has copy, drop, store { + issuer: vector, + jwk_id: vector, + } + + /// A `Patch` variant to upsert a JWK for an issuer. + struct PatchUpsertJWK has copy, drop, store { + issuer: vector, + jwk: JWK, + } + + /// A sequence of `Patch` objects that are applied *one by one* to the `ObservedJWKs`. + /// + /// Maintained by governance proposals. + struct Patches has key { + patches: vector, + } + + /// The result of applying the `Patches` to the `ObservedJWKs`. + /// This is what applications should consume. + struct PatchedJWKs has drop, key { + jwks: AllProvidersJWKs, + } + + // + // Structs end. + // Functions begin. + // + + /// Get a JWK by issuer and key ID from the `PatchedJWKs`. + /// Abort if such a JWK does not exist. + /// More convenient to call from Rust, since it does not wrap the JWK in an `Option`. + public fun get_patched_jwk(issuer: vector, jwk_id: vector): JWK acquires PatchedJWKs { + option::extract(&mut try_get_patched_jwk(issuer, jwk_id)) + } + + /// Get a JWK by issuer and key ID from the `PatchedJWKs`, if it exists. + /// More convenient to call from Move, since it does not abort. + public fun try_get_patched_jwk(issuer: vector, jwk_id: vector): Option acquires PatchedJWKs { + let jwks = &borrow_global(@aptos_framework).jwks; + try_get_jwk_by_issuer(jwks, issuer, jwk_id) + } + + /// Deprecated by `upsert_oidc_provider_for_next_epoch()`. + /// + /// TODO: update all the tests that reference this function, then disable this function. + public fun upsert_oidc_provider(fx: &signer, name: vector, config_url: vector): Option> acquires SupportedOIDCProviders { + system_addresses::assert_aptos_framework(fx); + chain_status::assert_genesis(); + + let provider_set = borrow_global_mut(@aptos_framework); + + let old_config_url= remove_oidc_provider_internal(provider_set, name); + vector::push_back(&mut provider_set.providers, OIDCProvider { name, config_url }); + old_config_url + } + + /// Used in on-chain governances to update the supported OIDC providers, effective starting next epoch. + /// Example usage: + /// ``` + /// aptos_framework::jwks::upsert_oidc_provider_for_next_epoch( + /// &framework_signer, + /// b"https://accounts.google.com", + /// b"https://accounts.google.com/.well-known/openid-configuration" + /// ); + /// aptos_framework::aptos_governance::reconfigure(&framework_signer); + /// ``` + public fun upsert_oidc_provider_for_next_epoch(fx: &signer, name: vector, config_url: vector): Option> acquires SupportedOIDCProviders { + system_addresses::assert_aptos_framework(fx); + + let provider_set = if (config_buffer::does_exist()) { + config_buffer::extract() + } else { + *borrow_global_mut(@aptos_framework) + }; + + let old_config_url = remove_oidc_provider_internal(&mut provider_set, name); + vector::push_back(&mut provider_set.providers, OIDCProvider { name, config_url }); + config_buffer::upsert(provider_set); + old_config_url + } + + /// Deprecated by `remove_oidc_provider_for_next_epoch()`. + /// + /// TODO: update all the tests that reference this function, then disable this function. + public fun remove_oidc_provider(fx: &signer, name: vector): Option> acquires SupportedOIDCProviders { + system_addresses::assert_aptos_framework(fx); + chain_status::assert_genesis(); + + let provider_set = borrow_global_mut(@aptos_framework); + remove_oidc_provider_internal(provider_set, name) + } + + /// Used in on-chain governances to update the supported OIDC providers, effective starting next epoch. + /// Example usage: + /// ``` + /// aptos_framework::jwks::remove_oidc_provider_for_next_epoch( + /// &framework_signer, + /// b"https://accounts.google.com", + /// ); + /// aptos_framework::aptos_governance::reconfigure(&framework_signer); + /// ``` + public fun remove_oidc_provider_for_next_epoch(fx: &signer, name: vector): Option> acquires SupportedOIDCProviders { + system_addresses::assert_aptos_framework(fx); + + let provider_set = if (config_buffer::does_exist()) { + config_buffer::extract() + } else { + *borrow_global_mut(@aptos_framework) + }; + let ret = remove_oidc_provider_internal(&mut provider_set, name); + config_buffer::upsert(provider_set); + ret + } + + /// Only used in reconfigurations to apply the pending `SupportedOIDCProviders`, if there is any. + public(friend) fun on_new_epoch(framework: &signer) acquires SupportedOIDCProviders { + system_addresses::assert_aptos_framework(framework); + if (config_buffer::does_exist()) { + let new_config = config_buffer::extract(); + if (exists(@aptos_framework)) { + *borrow_global_mut(@aptos_framework) = new_config; + } else { + move_to(framework, new_config); + } + } + } + + /// Set the `Patches`. Only called in governance proposals. + public fun set_patches(fx: &signer, patches: vector) acquires Patches, PatchedJWKs, ObservedJWKs { + system_addresses::assert_aptos_framework(fx); + borrow_global_mut(@aptos_framework).patches = patches; + regenerate_patched_jwks(); + } + + /// Create a `Patch` that removes all entries. + public fun new_patch_remove_all(): Patch { + Patch { + variant: copyable_any::pack(PatchRemoveAll {}), + } + } + + /// Create a `Patch` that removes the entry of a given issuer, if exists. + public fun new_patch_remove_issuer(issuer: vector): Patch { + Patch { + variant: copyable_any::pack(PatchRemoveIssuer { issuer }), + } + } + + /// Create a `Patch` that removes the entry of a given issuer, if exists. + public fun new_patch_remove_jwk(issuer: vector, jwk_id: vector): Patch { + Patch { + variant: copyable_any::pack(PatchRemoveJWK { issuer, jwk_id }) + } + } + + /// Create a `Patch` that upserts a JWK into an issuer's JWK set. + public fun new_patch_upsert_jwk(issuer: vector, jwk: JWK): Patch { + Patch { + variant: copyable_any::pack(PatchUpsertJWK { issuer, jwk }) + } + } + + /// Create a `JWK` of variant `RSA_JWK`. + public fun new_rsa_jwk(kid: String, alg: String, e: String, n: String): JWK { + JWK { + variant: copyable_any::pack(RSA_JWK { + kid, + kty: utf8(b"RSA"), + e, + n, + alg, + }), + } + } + + /// Create a `JWK` of variant `UnsupportedJWK`. + public fun new_unsupported_jwk(id: vector, payload: vector): JWK { + JWK { + variant: copyable_any::pack(UnsupportedJWK { id, payload }) + } + } + + /// Initialize some JWK resources. Should only be invoked by genesis. + public fun initialize(fx: &signer) { + system_addresses::assert_aptos_framework(fx); + move_to(fx, SupportedOIDCProviders { providers: vector[] }); + move_to(fx, ObservedJWKs { jwks: AllProvidersJWKs { entries: vector[] } }); + move_to(fx, Patches { patches: vector[] }); + move_to(fx, PatchedJWKs { jwks: AllProvidersJWKs { entries: vector[] } }); + } + + /// Helper function that removes an OIDC provider from the `SupportedOIDCProviders`. + /// Returns the old config URL of the provider, if any, as an `Option`. + fun remove_oidc_provider_internal(provider_set: &mut SupportedOIDCProviders, name: vector): Option> { + let (name_exists, idx) = vector::find(&provider_set.providers, |obj| { + let provider: &OIDCProvider = obj; + provider.name == name + }); + + if (name_exists) { + let old_provider = vector::swap_remove(&mut provider_set.providers, idx); + option::some(old_provider.config_url) + } else { + option::none() + } + } + + /// Only used by validators to publish their observed JWK update. + /// + /// NOTE: It is assumed verification has been done to ensure each update is quorum-certified, + /// and its `version` equals to the on-chain version + 1. + public fun upsert_into_observed_jwks(fx: &signer, provider_jwks_vec: vector) acquires ObservedJWKs, PatchedJWKs, Patches { + system_addresses::assert_aptos_framework(fx); + let observed_jwks = borrow_global_mut(@aptos_framework); + vector::for_each(provider_jwks_vec, |obj| { + let provider_jwks: ProviderJWKs = obj; + upsert_provider_jwks(&mut observed_jwks.jwks, provider_jwks); + }); + + let epoch = reconfiguration::current_epoch(); + emit(ObservedJWKsUpdated { epoch, jwks: observed_jwks.jwks }); + regenerate_patched_jwks(); + } + + /// Only used by governance to delete an issuer from `ObservedJWKs`, if it exists. + /// + /// Return the potentially existing `ProviderJWKs` of the given issuer. + public fun remove_issuer_from_observed_jwks(fx: &signer, issuer: vector): Option acquires ObservedJWKs, PatchedJWKs, Patches { + system_addresses::assert_aptos_framework(fx); + let observed_jwks = borrow_global_mut(@aptos_framework); + let old_value = remove_issuer(&mut observed_jwks.jwks, issuer); + + let epoch = reconfiguration::current_epoch(); + emit(ObservedJWKsUpdated { epoch, jwks: observed_jwks.jwks }); + regenerate_patched_jwks(); + + old_value + } + + /// Regenerate `PatchedJWKs` from `ObservedJWKs` and `Patches` and save the result. + fun regenerate_patched_jwks() acquires PatchedJWKs, Patches, ObservedJWKs { + let jwks = borrow_global(@aptos_framework).jwks; + let patches = borrow_global(@aptos_framework); + vector::for_each_ref(&patches.patches, |obj|{ + let patch: &Patch = obj; + apply_patch(&mut jwks, *patch); + }); + *borrow_global_mut(@aptos_framework) = PatchedJWKs { jwks }; + } + + /// Get a JWK by issuer and key ID from a `AllProvidersJWKs`, if it exists. + fun try_get_jwk_by_issuer(jwks: &AllProvidersJWKs, issuer: vector, jwk_id: vector): Option { + let (issuer_found, index) = vector::find(&jwks.entries, |obj| { + let provider_jwks: &ProviderJWKs = obj; + issuer == provider_jwks.issuer + }); + + if (issuer_found) { + try_get_jwk_by_id(vector::borrow(&jwks.entries, index), jwk_id) + } else { + option::none() + } + } + + /// Get a JWK by key ID from a `ProviderJWKs`, if it exists. + fun try_get_jwk_by_id(provider_jwks: &ProviderJWKs, jwk_id: vector): Option { + let (jwk_id_found, index) = vector::find(&provider_jwks.jwks, |obj|{ + let jwk: &JWK = obj; + jwk_id == get_jwk_id(jwk) + }); + + if (jwk_id_found) { + option::some(*vector::borrow(&provider_jwks.jwks, index)) + } else { + option::none() + } + } + + /// Get the ID of a JWK. + fun get_jwk_id(jwk: &JWK): vector { + let variant_type_name = *string::bytes(copyable_any::type_name(&jwk.variant)); + if (variant_type_name == b"0x1::jwks::RSA_JWK") { + let rsa = copyable_any::unpack(jwk.variant); + *string::bytes(&rsa.kid) + } else if (variant_type_name == b"0x1::jwks::UnsupportedJWK") { + let unsupported = copyable_any::unpack(jwk.variant); + unsupported.id + } else { + abort(error::invalid_argument(EUNKNOWN_JWK_VARIANT)) + } + } + + /// Upsert a `ProviderJWKs` into an `AllProvidersJWKs`. If this upsert replaced an existing entry, return it. + /// Maintains the sorted-by-issuer invariant in `AllProvidersJWKs`. + fun upsert_provider_jwks(jwks: &mut AllProvidersJWKs, provider_jwks: ProviderJWKs): Option { + // NOTE: Using a linear-time search here because we do not expect too many providers. + let found = false; + let index = 0; + let num_entries = vector::length(&jwks.entries); + while (index < num_entries) { + let cur_entry = vector::borrow(&jwks.entries, index); + let comparison = compare_u8_vector(provider_jwks.issuer, cur_entry.issuer); + if (is_greater_than(&comparison)) { + index = index + 1; + } else { + found = is_equal(&comparison); + break + } + }; + + // Now if `found == true`, `index` points to the JWK we want to update/remove; otherwise, `index` points to + // where we want to insert. + let ret = if (found) { + let entry = vector::borrow_mut(&mut jwks.entries, index); + let old_entry = option::some(*entry); + *entry = provider_jwks; + old_entry + } else { + vector::insert(&mut jwks.entries, index, provider_jwks); + option::none() + }; + + ret + } + + /// Remove the entry of an issuer from a `AllProvidersJWKs` and return the entry, if exists. + /// Maintains the sorted-by-issuer invariant in `AllProvidersJWKs`. + fun remove_issuer(jwks: &mut AllProvidersJWKs, issuer: vector): Option { + let (found, index) = vector::find(&jwks.entries, |obj| { + let provider_jwk_set: &ProviderJWKs = obj; + provider_jwk_set.issuer == issuer + }); + + let ret = if (found) { + option::some(vector::remove(&mut jwks.entries, index)) + } else { + option::none() + }; + + ret + } + + /// Upsert a `JWK` into a `ProviderJWKs`. If this upsert replaced an existing entry, return it. + fun upsert_jwk(set: &mut ProviderJWKs, jwk: JWK): Option { + let found = false; + let index = 0; + let num_entries = vector::length(&set.jwks); + while (index < num_entries) { + let cur_entry = vector::borrow(&set.jwks, index); + let comparison = compare_u8_vector(get_jwk_id(&jwk), get_jwk_id(cur_entry)); + if (is_greater_than(&comparison)) { + index = index + 1; + } else { + found = is_equal(&comparison); + break + } + }; + + // Now if `found == true`, `index` points to the JWK we want to update/remove; otherwise, `index` points to + // where we want to insert. + let ret = if (found) { + let entry = vector::borrow_mut(&mut set.jwks, index); + let old_entry = option::some(*entry); + *entry = jwk; + old_entry + } else { + vector::insert(&mut set.jwks, index, jwk); + option::none() + }; + + ret + } + + /// Remove the entry of a key ID from a `ProviderJWKs` and return the entry, if exists. + fun remove_jwk(jwks: &mut ProviderJWKs, jwk_id: vector): Option { + let (found, index) = vector::find(&jwks.jwks, |obj| { + let jwk: &JWK = obj; + jwk_id == get_jwk_id(jwk) + }); + + let ret = if (found) { + option::some(vector::remove(&mut jwks.jwks, index)) + } else { + option::none() + }; + + ret + } + + /// Modify an `AllProvidersJWKs` object with a `Patch`. + /// Maintains the sorted-by-issuer invariant in `AllProvidersJWKs`. + fun apply_patch(jwks: &mut AllProvidersJWKs, patch: Patch) { + let variant_type_name = *string::bytes(copyable_any::type_name(&patch.variant)); + if (variant_type_name == b"0x1::jwks::PatchRemoveAll") { + jwks.entries = vector[]; + } else if (variant_type_name == b"0x1::jwks::PatchRemoveIssuer") { + let cmd = copyable_any::unpack(patch.variant); + remove_issuer(jwks, cmd.issuer); + } else if (variant_type_name == b"0x1::jwks::PatchRemoveJWK") { + let cmd = copyable_any::unpack(patch.variant); + // TODO: This is inefficient: we remove the issuer, modify its JWKs & and reinsert the updated issuer. Why + // not just update it in place? + let existing_jwk_set = remove_issuer(jwks, cmd.issuer); + if (option::is_some(&existing_jwk_set)) { + let jwk_set = option::extract(&mut existing_jwk_set); + remove_jwk(&mut jwk_set, cmd.jwk_id); + upsert_provider_jwks(jwks, jwk_set); + }; + } else if (variant_type_name == b"0x1::jwks::PatchUpsertJWK") { + let cmd = copyable_any::unpack(patch.variant); + // TODO: This is inefficient: we remove the issuer, modify its JWKs & and reinsert the updated issuer. Why + // not just update it in place? + let existing_jwk_set = remove_issuer(jwks, cmd.issuer); + let jwk_set = if (option::is_some(&existing_jwk_set)) { + option::extract(&mut existing_jwk_set) + } else { + ProviderJWKs { + version: 0, + issuer: cmd.issuer, + jwks: vector[], + } + }; + upsert_jwk(&mut jwk_set, cmd.jwk); + upsert_provider_jwks(jwks, jwk_set); + } else { + abort(std::error::invalid_argument(EUNKNOWN_PATCH_VARIANT)) + } + } + + // + // Functions end. + // Tests begin. + // + + #[test_only] + fun initialize_for_test(aptos_framework: &signer) { + create_account_for_test(@aptos_framework); + reconfiguration::initialize_for_test(aptos_framework); + initialize(aptos_framework); + } + + #[test(fx = @aptos_framework)] + fun test_observed_jwks_operations(fx: &signer) acquires ObservedJWKs, PatchedJWKs, Patches { + initialize_for_test(fx); + let jwk_0 = new_unsupported_jwk(b"key_id_0", b"key_payload_0"); + let jwk_1 = new_unsupported_jwk(b"key_id_1", b"key_payload_1"); + let jwk_2 = new_unsupported_jwk(b"key_id_2", b"key_payload_2"); + let jwk_3 = new_unsupported_jwk(b"key_id_3", b"key_payload_3"); + let jwk_4 = new_unsupported_jwk(b"key_id_4", b"key_payload_4"); + let expected = AllProvidersJWKs { entries: vector[] }; + assert!(expected == borrow_global(@aptos_framework).jwks, 1); + + let alice_jwks_v1 = ProviderJWKs { + issuer: b"alice", + version: 1, + jwks: vector[jwk_0, jwk_1], + }; + let bob_jwks_v1 = ProviderJWKs{ + issuer: b"bob", + version: 1, + jwks: vector[jwk_2, jwk_3], + }; + upsert_into_observed_jwks(fx, vector[bob_jwks_v1]); + upsert_into_observed_jwks(fx, vector[alice_jwks_v1]); + let expected = AllProvidersJWKs { entries: vector[ + alice_jwks_v1, + bob_jwks_v1, + ] }; + assert!(expected == borrow_global(@aptos_framework).jwks, 2); + + let alice_jwks_v2 = ProviderJWKs { + issuer: b"alice", + version: 2, + jwks: vector[jwk_1, jwk_4], + }; + upsert_into_observed_jwks(fx, vector[alice_jwks_v2]); + let expected = AllProvidersJWKs { entries: vector[ + alice_jwks_v2, + bob_jwks_v1, + ] }; + assert!(expected == borrow_global(@aptos_framework).jwks, 3); + + remove_issuer_from_observed_jwks(fx, b"alice"); + let expected = AllProvidersJWKs { entries: vector[bob_jwks_v1] }; + assert!(expected == borrow_global(@aptos_framework).jwks, 4); + } + + #[test] + fun test_apply_patch() { + let jwks = AllProvidersJWKs { + entries: vector[ + ProviderJWKs { + issuer: b"alice", + version: 111, + jwks: vector[ + new_rsa_jwk( + utf8(b"e4adfb436b9e197e2e1106af2c842284e4986aff"), // kid + utf8(b"RS256"), // alg + utf8(b"AQAB"), // e + utf8(b"psply8S991RswM0JQJwv51fooFFvZUtYdL8avyKObshyzj7oJuJD8vkf5DKJJF1XOGi6Wv2D-U4b3htgrVXeOjAvaKTYtrQVUG_Txwjebdm2EvBJ4R6UaOULjavcSkb8VzW4l4AmP_yWoidkHq8n6vfHt9alDAONILi7jPDzRC7NvnHQ_x0hkRVh_OAmOJCpkgb0gx9-U8zSBSmowQmvw15AZ1I0buYZSSugY7jwNS2U716oujAiqtRkC7kg4gPouW_SxMleeo8PyRsHpYCfBME66m-P8Zr9Fh1Qgmqg4cWdy_6wUuNc1cbVY_7w1BpHZtZCNeQ56AHUgUFmo2LAQQ"), // n + ), + new_unsupported_jwk(b"key_id_0", b"key_content_0"), + ], + }, + ProviderJWKs { + issuer: b"bob", + version: 222, + jwks: vector[ + new_unsupported_jwk(b"key_id_1", b"key_content_1"), + new_unsupported_jwk(b"key_id_2", b"key_content_2"), + ], + }, + ], + }; + + let patch = new_patch_remove_issuer(b"alice"); + apply_patch(&mut jwks, patch); + assert!(jwks == AllProvidersJWKs { + entries: vector[ + ProviderJWKs { + issuer: b"bob", + version: 222, + jwks: vector[ + new_unsupported_jwk(b"key_id_1", b"key_content_1"), + new_unsupported_jwk(b"key_id_2", b"key_content_2"), + ], + }, + ], + }, 1); + + let patch = new_patch_remove_jwk(b"bob", b"key_id_1"); + apply_patch(&mut jwks, patch); + assert!(jwks == AllProvidersJWKs { + entries: vector[ + ProviderJWKs { + issuer: b"bob", + version: 222, + jwks: vector[ + new_unsupported_jwk(b"key_id_2", b"key_content_2"), + ], + }, + ], + }, 1); + + let patch = new_patch_upsert_jwk(b"carl", new_rsa_jwk( + utf8(b"0ad1fec78504f447bae65bcf5afaedb65eec9e81"), // kid + utf8(b"RS256"), // alg + utf8(b"AQAB"), // e + utf8(b"sm72oBH-R2Rqt4hkjp66tz5qCtq42TMnVgZg2Pdm_zs7_-EoFyNs9sD1MKsZAFaBPXBHDiWywyaHhLgwETLN9hlJIZPzGCEtV3mXJFSYG-8L6t3kyKi9X1lUTZzbmNpE0tf-eMW-3gs3VQSBJQOcQnuiANxbSXwS3PFmi173C_5fDSuC1RoYGT6X3JqLc3DWUmBGucuQjPaUF0w6LMqEIy0W_WYbW7HImwANT6dT52T72md0JWZuAKsRRnRr_bvaUX8_e3K8Pb1K_t3dD6WSLvtmEfUnGQgLynVl3aV5sRYC0Hy_IkRgoxl2fd8AaZT1X_rdPexYpx152Pl_CHJ79Q"), // n + )); + apply_patch(&mut jwks, patch); + let edit = new_patch_upsert_jwk(b"bob", new_unsupported_jwk(b"key_id_2", b"key_content_2b")); + apply_patch(&mut jwks, edit); + let edit = new_patch_upsert_jwk(b"alice", new_unsupported_jwk(b"key_id_3", b"key_content_3")); + apply_patch(&mut jwks, edit); + let edit = new_patch_upsert_jwk(b"alice", new_unsupported_jwk(b"key_id_0", b"key_content_0b")); + apply_patch(&mut jwks, edit); + assert!(jwks == AllProvidersJWKs { + entries: vector[ + ProviderJWKs { + issuer: b"alice", + version: 0, + jwks: vector[ + new_unsupported_jwk(b"key_id_0", b"key_content_0b"), + new_unsupported_jwk(b"key_id_3", b"key_content_3"), + ], + }, + ProviderJWKs { + issuer: b"bob", + version: 222, + jwks: vector[ + new_unsupported_jwk(b"key_id_2", b"key_content_2b"), + ], + }, + ProviderJWKs { + issuer: b"carl", + version: 0, + jwks: vector[ + new_rsa_jwk( + utf8(b"0ad1fec78504f447bae65bcf5afaedb65eec9e81"), // kid + utf8(b"RS256"), // alg + utf8(b"AQAB"), // e + utf8(b"sm72oBH-R2Rqt4hkjp66tz5qCtq42TMnVgZg2Pdm_zs7_-EoFyNs9sD1MKsZAFaBPXBHDiWywyaHhLgwETLN9hlJIZPzGCEtV3mXJFSYG-8L6t3kyKi9X1lUTZzbmNpE0tf-eMW-3gs3VQSBJQOcQnuiANxbSXwS3PFmi173C_5fDSuC1RoYGT6X3JqLc3DWUmBGucuQjPaUF0w6LMqEIy0W_WYbW7HImwANT6dT52T72md0JWZuAKsRRnRr_bvaUX8_e3K8Pb1K_t3dD6WSLvtmEfUnGQgLynVl3aV5sRYC0Hy_IkRgoxl2fd8AaZT1X_rdPexYpx152Pl_CHJ79Q"), // n + ) + ], + }, + ], + }, 1); + + let patch = new_patch_remove_all(); + apply_patch(&mut jwks, patch); + assert!(jwks == AllProvidersJWKs { entries: vector[] }, 1); + } + + #[test(aptos_framework = @aptos_framework)] + fun test_patched_jwks(aptos_framework: signer) acquires ObservedJWKs, PatchedJWKs, Patches { + initialize_for_test(&aptos_framework); + let jwk_0 = new_unsupported_jwk(b"key_id_0", b"key_payload_0"); + let jwk_1 = new_unsupported_jwk(b"key_id_1", b"key_payload_1"); + let jwk_2 = new_unsupported_jwk(b"key_id_2", b"key_payload_2"); + let jwk_3 = new_unsupported_jwk(b"key_id_3", b"key_payload_3"); + let jwk_3b = new_unsupported_jwk(b"key_id_3", b"key_payload_3b"); + + // Fake observation from validators. + upsert_into_observed_jwks(&aptos_framework, vector [ + ProviderJWKs { + issuer: b"alice", + version: 111, + jwks: vector[jwk_0, jwk_1], + }, + ProviderJWKs{ + issuer: b"bob", + version: 222, + jwks: vector[jwk_2, jwk_3], + }, + ]); + assert!(jwk_3 == get_patched_jwk(b"bob", b"key_id_3"), 1); + assert!(option::some(jwk_3) == try_get_patched_jwk(b"bob", b"key_id_3"), 1); + + // Ignore all Bob's keys. + set_patches(&aptos_framework, vector[ + new_patch_remove_issuer(b"bob"), + ]); + assert!(option::none() == try_get_patched_jwk(b"bob", b"key_id_3"), 1); + + // Update one of Bob's key.. + set_patches(&aptos_framework, vector[ + new_patch_upsert_jwk(b"bob", jwk_3b), + ]); + assert!(jwk_3b == get_patched_jwk(b"bob", b"key_id_3"), 1); + assert!(option::some(jwk_3b) == try_get_patched_jwk(b"bob", b"key_id_3"), 1); + + // Wipe everything, then add some keys back. + set_patches(&aptos_framework, vector[ + new_patch_remove_all(), + new_patch_upsert_jwk(b"alice", jwk_1), + new_patch_upsert_jwk(b"bob", jwk_3), + ]); + assert!(jwk_3 == get_patched_jwk(b"bob", b"key_id_3"), 1); + assert!(option::some(jwk_3) == try_get_patched_jwk(b"bob", b"key_id_3"), 1); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/keyless_account.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/keyless_account.move new file mode 100644 index 000000000..269c209b2 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/keyless_account.move @@ -0,0 +1,312 @@ +/// This module is responsible for configuring keyless blockchain accounts which were introduced in +/// [AIP-61](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-61.md). +module aptos_framework::keyless_account { + use std::bn254_algebra; + use std::config_buffer; + use std::option; + use std::option::Option; + use std::signer; + use std::string::String; + use std::vector; + use aptos_std::crypto_algebra; + use aptos_std::ed25519; + use aptos_framework::chain_status; + use aptos_framework::system_addresses; + + // The `aptos_framework::reconfiguration_with_dkg` module needs to be able to call `on_new_epoch`. + friend aptos_framework::reconfiguration_with_dkg; + + /// The training wheels PK needs to be 32 bytes long. + const E_TRAINING_WHEELS_PK_WRONG_SIZE : u64 = 1; + + /// A serialized BN254 G1 point is invalid. + const E_INVALID_BN254_G1_SERIALIZATION: u64 = 2; + + /// A serialized BN254 G2 point is invalid. + const E_INVALID_BN254_G2_SERIALIZATION: u64 = 3; + + #[resource_group(scope = global)] + struct Group {} + + #[resource_group_member(group = aptos_framework::keyless_account::Group)] + /// The 288-byte Groth16 verification key (VK) for the ZK relation that implements keyless accounts + struct Groth16VerificationKey has key, store, drop { + /// 32-byte serialization of `alpha * G`, where `G` is the generator of `G1`. + alpha_g1: vector, + /// 64-byte serialization of `alpha * H`, where `H` is the generator of `G2`. + beta_g2: vector, + /// 64-byte serialization of `gamma * H`, where `H` is the generator of `G2`. + gamma_g2: vector, + /// 64-byte serialization of `delta * H`, where `H` is the generator of `G2`. + delta_g2: vector, + /// `\forall i \in {0, ..., \ell}, 64-byte serialization of gamma^{-1} * (beta * a_i + alpha * b_i + c_i) * H`, where + /// `H` is the generator of `G1` and `\ell` is 1 for the ZK relation. + gamma_abc_g1: vector>, + } + + #[resource_group_member(group = aptos_framework::keyless_account::Group)] + struct Configuration has key, store, drop, copy { + /// An override `aud` for the identity of a recovery service, which will help users recover their keyless accounts + /// associated with dapps or wallets that have disappeared. + /// IMPORTANT: This recovery service **cannot** on its own take over user accounts; a user must first sign in + /// via OAuth in the recovery service in order to allow it to rotate any of that user's keyless accounts. + override_aud_vals: vector, + /// No transaction can have more than this many keyless signatures. + max_signatures_per_txn: u16, + /// How far in the future from the JWT issued at time the EPK expiry can be set. + max_exp_horizon_secs: u64, + /// The training wheels PK, if training wheels are on + training_wheels_pubkey: Option>, + /// The max length of an ephemeral public key supported in our circuit (93 bytes) + max_commited_epk_bytes: u16, + /// The max length of the value of the JWT's `iss` field supported in our circuit (e.g., `"https://accounts.google.com"`) + max_iss_val_bytes: u16, + /// The max length of the JWT field name and value (e.g., `"max_age":"18"`) supported in our circuit + max_extra_field_bytes: u16, + /// The max length of the base64url-encoded JWT header in bytes supported in our circuit + max_jwt_header_b64_bytes: u32, + } + + #[test_only] + public fun initialize_for_test(fx: &signer, vk: Groth16VerificationKey, constants: Configuration) { + system_addresses::assert_aptos_framework(fx); + + move_to(fx, vk); + move_to(fx, constants); + } + + public fun new_groth16_verification_key(alpha_g1: vector, + beta_g2: vector, + gamma_g2: vector, + delta_g2: vector, + gamma_abc_g1: vector> + ): Groth16VerificationKey { + Groth16VerificationKey { + alpha_g1, + beta_g2, + gamma_g2, + delta_g2, + gamma_abc_g1, + } + } + + public fun new_configuration( + override_aud_val: vector, + max_signatures_per_txn: u16, + max_exp_horizon_secs: u64, + training_wheels_pubkey: Option>, + max_commited_epk_bytes: u16, + max_iss_val_bytes: u16, + max_extra_field_bytes: u16, + max_jwt_header_b64_bytes: u32 + ): Configuration { + Configuration { + override_aud_vals: override_aud_val, + max_signatures_per_txn, + max_exp_horizon_secs, + training_wheels_pubkey, + max_commited_epk_bytes, + max_iss_val_bytes, + max_extra_field_bytes, + max_jwt_header_b64_bytes, + } + } + + /// Pre-validate the VK to actively-prevent incorrect VKs from being set on-chain. + fun validate_groth16_vk(vk: &Groth16VerificationKey) { + // Could be leveraged to speed up the VM deserialization of the VK by 2x, since it can assume the points are valid. + assert!(option::is_some(&crypto_algebra::deserialize(&vk.alpha_g1)), E_INVALID_BN254_G1_SERIALIZATION); + assert!(option::is_some(&crypto_algebra::deserialize(&vk.beta_g2)), E_INVALID_BN254_G2_SERIALIZATION); + assert!(option::is_some(&crypto_algebra::deserialize(&vk.gamma_g2)), E_INVALID_BN254_G2_SERIALIZATION); + assert!(option::is_some(&crypto_algebra::deserialize(&vk.delta_g2)), E_INVALID_BN254_G2_SERIALIZATION); + for (i in 0..vector::length(&vk.gamma_abc_g1)) { + assert!(option::is_some(&crypto_algebra::deserialize(vector::borrow(&vk.gamma_abc_g1, i))), E_INVALID_BN254_G1_SERIALIZATION); + }; + } + + /// Sets the Groth16 verification key, only callable during genesis. To call during governance proposals, use + /// `set_groth16_verification_key_for_next_epoch`. + /// + /// WARNING: See `set_groth16_verification_key_for_next_epoch` for caveats. + public fun update_groth16_verification_key(fx: &signer, vk: Groth16VerificationKey) { + system_addresses::assert_aptos_framework(fx); + chain_status::assert_genesis(); + // There should not be a previous resource set here. + move_to(fx, vk); + } + + /// Sets the keyless configuration, only callable during genesis. To call during governance proposals, use + /// `set_configuration_for_next_epoch`. + /// + /// WARNING: See `set_configuration_for_next_epoch` for caveats. + public fun update_configuration(fx: &signer, config: Configuration) { + system_addresses::assert_aptos_framework(fx); + chain_status::assert_genesis(); + // There should not be a previous resource set here. + move_to(fx, config); + } + + #[deprecated] + public fun update_training_wheels(fx: &signer, pk: Option>) acquires Configuration { + system_addresses::assert_aptos_framework(fx); + chain_status::assert_genesis(); + + if (option::is_some(&pk)) { + assert!(vector::length(option::borrow(&pk)) == 32, E_TRAINING_WHEELS_PK_WRONG_SIZE) + }; + + let config = borrow_global_mut(signer::address_of(fx)); + config.training_wheels_pubkey = pk; + } + + #[deprecated] + public fun update_max_exp_horizon(fx: &signer, max_exp_horizon_secs: u64) acquires Configuration { + system_addresses::assert_aptos_framework(fx); + chain_status::assert_genesis(); + + let config = borrow_global_mut(signer::address_of(fx)); + config.max_exp_horizon_secs = max_exp_horizon_secs; + } + + #[deprecated] + public fun remove_all_override_auds(fx: &signer) acquires Configuration { + system_addresses::assert_aptos_framework(fx); + chain_status::assert_genesis(); + + let config = borrow_global_mut(signer::address_of(fx)); + config.override_aud_vals = vector[]; + } + + #[deprecated] + public fun add_override_aud(fx: &signer, aud: String) acquires Configuration { + system_addresses::assert_aptos_framework(fx); + chain_status::assert_genesis(); + + let config = borrow_global_mut(signer::address_of(fx)); + vector::push_back(&mut config.override_aud_vals, aud); + } + + /// Queues up a change to the Groth16 verification key. The change will only be effective after reconfiguration. + /// Only callable via governance proposal. + /// + /// WARNING: To mitigate against DoS attacks, a VK change should be done together with a training wheels PK change, + /// so that old ZKPs for the old VK cannot be replayed as potentially-valid ZKPs. + /// + /// WARNING: If a malicious key is set, this would lead to stolen funds. + public fun set_groth16_verification_key_for_next_epoch(fx: &signer, vk: Groth16VerificationKey) { + system_addresses::assert_aptos_framework(fx); + config_buffer::upsert(vk); + } + + + /// Queues up a change to the keyless configuration. The change will only be effective after reconfiguration. Only + /// callable via governance proposal. + /// + /// WARNING: A malicious `Configuration` could lead to DoS attacks, create liveness issues, or enable a malicious + /// recovery service provider to phish users' accounts. + public fun set_configuration_for_next_epoch(fx: &signer, config: Configuration) { + system_addresses::assert_aptos_framework(fx); + config_buffer::upsert(config); + } + + /// Convenience method to queue up a change to the training wheels PK. The change will only be effective after + /// reconfiguration. Only callable via governance proposal. + /// + /// WARNING: If a malicious key is set, this *could* lead to stolen funds. + public fun update_training_wheels_for_next_epoch(fx: &signer, pk: Option>) acquires Configuration { + system_addresses::assert_aptos_framework(fx); + + // If a PK is being set, validate it first. + if (option::is_some(&pk)) { + let bytes = *option::borrow(&pk); + let vpk = ed25519::new_validated_public_key_from_bytes(bytes); + assert!(option::is_some(&vpk), E_TRAINING_WHEELS_PK_WRONG_SIZE) + }; + + let config = if (config_buffer::does_exist()) { + config_buffer::extract() + } else { + *borrow_global(signer::address_of(fx)) + }; + + config.training_wheels_pubkey = pk; + + set_configuration_for_next_epoch(fx, config); + } + + /// Convenience method to queues up a change to the max expiration horizon. The change will only be effective after + /// reconfiguration. Only callable via governance proposal. + public fun update_max_exp_horizon_for_next_epoch(fx: &signer, max_exp_horizon_secs: u64) acquires Configuration { + system_addresses::assert_aptos_framework(fx); + + let config = if (config_buffer::does_exist()) { + config_buffer::extract() + } else { + *borrow_global(signer::address_of(fx)) + }; + + config.max_exp_horizon_secs = max_exp_horizon_secs; + + set_configuration_for_next_epoch(fx, config); + } + + /// Convenience method to queue up clearing the set of override `aud`'s. The change will only be effective after + /// reconfiguration. Only callable via governance proposal. + /// + /// WARNING: When no override `aud` is set, recovery of keyless accounts associated with applications that disappeared + /// is no longer possible. + public fun remove_all_override_auds_for_next_epoch(fx: &signer) acquires Configuration { + system_addresses::assert_aptos_framework(fx); + + let config = if (config_buffer::does_exist()) { + config_buffer::extract() + } else { + *borrow_global(signer::address_of(fx)) + }; + + config.override_aud_vals = vector[]; + + set_configuration_for_next_epoch(fx, config); + } + + /// Convenience method to queue up an append to to the set of override `aud`'s. The change will only be effective + /// after reconfiguration. Only callable via governance proposal. + /// + /// WARNING: If a malicious override `aud` is set, this *could* lead to stolen funds. + public fun add_override_aud_for_next_epoch(fx: &signer, aud: String) acquires Configuration { + system_addresses::assert_aptos_framework(fx); + + let config = if (config_buffer::does_exist()) { + config_buffer::extract() + } else { + *borrow_global(signer::address_of(fx)) + }; + + vector::push_back(&mut config.override_aud_vals, aud); + + set_configuration_for_next_epoch(fx, config); + } + + /// Only used in reconfigurations to apply the queued up configuration changes, if there are any. + public(friend) fun on_new_epoch(fx: &signer) acquires Groth16VerificationKey, Configuration { + system_addresses::assert_aptos_framework(fx); + + if (config_buffer::does_exist()) { + let vk = config_buffer::extract(); + if (exists(@aptos_framework)) { + *borrow_global_mut(@aptos_framework) = vk; + } else { + move_to(fx, vk); + } + }; + + if (config_buffer::does_exist()) { + let config = config_buffer::extract(); + if (exists(@aptos_framework)) { + *borrow_global_mut(@aptos_framework) = config; + } else { + move_to(fx, config); + } + }; + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/managed_coin.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/managed_coin.move new file mode 100644 index 000000000..d2932ddb4 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/managed_coin.move @@ -0,0 +1,205 @@ +/// ManagedCoin is built to make a simple walkthrough of the Coins module. +/// It contains scripts you will need to initialize, mint, burn, transfer coins. +/// By utilizing this current module, a developer can create his own coin and care less about mint and burn capabilities, +module aptos_framework::managed_coin { + use std::string; + use std::error; + use std::signer; + + use aptos_framework::coin::{Self, BurnCapability, FreezeCapability, MintCapability}; + + // + // Errors + // + + /// Account has no capabilities (burn/mint). + const ENO_CAPABILITIES: u64 = 1; + + // + // Data structures + // + + /// Capabilities resource storing mint and burn capabilities. + /// The resource is stored on the account that initialized coin `CoinType`. + struct Capabilities has key { + burn_cap: BurnCapability, + freeze_cap: FreezeCapability, + mint_cap: MintCapability, + } + + // + // Public functions + // + + /// Withdraw an `amount` of coin `CoinType` from `account` and burn it. + public entry fun burn( + account: &signer, + amount: u64, + ) acquires Capabilities { + let account_addr = signer::address_of(account); + + assert!( + exists>(account_addr), + error::not_found(ENO_CAPABILITIES), + ); + + let capabilities = borrow_global>(account_addr); + + let to_burn = coin::withdraw(account, amount); + coin::burn(to_burn, &capabilities.burn_cap); + } + + /// Initialize new coin `CoinType` in Aptos Blockchain. + /// Mint and Burn Capabilities will be stored under `account` in `Capabilities` resource. + public entry fun initialize( + account: &signer, + name: vector, + symbol: vector, + decimals: u8, + monitor_supply: bool, + ) { + let (burn_cap, freeze_cap, mint_cap) = coin::initialize( + account, + string::utf8(name), + string::utf8(symbol), + decimals, + monitor_supply, + ); + + move_to(account, Capabilities { + burn_cap, + freeze_cap, + mint_cap, + }); + } + + /// Create new coins `CoinType` and deposit them into dst_addr's account. + public entry fun mint( + account: &signer, + dst_addr: address, + amount: u64, + ) acquires Capabilities { + let account_addr = signer::address_of(account); + + assert!( + exists>(account_addr), + error::not_found(ENO_CAPABILITIES), + ); + + let capabilities = borrow_global>(account_addr); + let coins_minted = coin::mint(amount, &capabilities.mint_cap); + coin::deposit(dst_addr, coins_minted); + } + + /// Creating a resource that stores balance of `CoinType` on user's account, withdraw and deposit event handlers. + /// Required if user wants to start accepting deposits of `CoinType` in his account. + public entry fun register(account: &signer) { + coin::register(account); + } + + // + // Tests + // + + #[test_only] + use std::option; + + #[test_only] + use aptos_framework::aggregator_factory; + + #[test_only] + struct FakeMoney {} + + #[test(source = @0xa11ce, destination = @0xb0b, mod_account = @0x1)] + public entry fun test_end_to_end( + source: signer, + destination: signer, + mod_account: signer + ) acquires Capabilities { + let source_addr = signer::address_of(&source); + let destination_addr = signer::address_of(&destination); + aptos_framework::account::create_account_for_test(source_addr); + aptos_framework::account::create_account_for_test(destination_addr); + aptos_framework::account::create_account_for_test(signer::address_of(&mod_account)); + aggregator_factory::initialize_aggregator_factory_for_test(&mod_account); + + initialize( + &mod_account, + b"Fake Money", + b"FMD", + 10, + true + ); + assert!(coin::is_coin_initialized(), 0); + + coin::register(&mod_account); + register(&source); + register(&destination); + + mint(&mod_account, source_addr, 50); + mint(&mod_account, destination_addr, 10); + assert!(coin::balance(source_addr) == 50, 1); + assert!(coin::balance(destination_addr) == 10, 2); + + let supply = coin::supply(); + assert!(option::is_some(&supply), 1); + assert!(option::extract(&mut supply) == 60, 2); + + coin::transfer(&source, destination_addr, 10); + assert!(coin::balance(source_addr) == 40, 3); + assert!(coin::balance(destination_addr) == 20, 4); + + coin::transfer(&source, signer::address_of(&mod_account), 40); + burn(&mod_account, 40); + + assert!(coin::balance(source_addr) == 0, 1); + + let new_supply = coin::supply(); + assert!(option::extract(&mut new_supply) == 20, 2); + } + + #[test(source = @0xa11ce, destination = @0xb0b, mod_account = @0x1)] + #[expected_failure(abort_code = 0x60001, location = Self)] + public entry fun fail_mint( + source: signer, + destination: signer, + mod_account: signer, + ) acquires Capabilities { + let source_addr = signer::address_of(&source); + + aptos_framework::account::create_account_for_test(source_addr); + aptos_framework::account::create_account_for_test(signer::address_of(&destination)); + aptos_framework::account::create_account_for_test(signer::address_of(&mod_account)); + aggregator_factory::initialize_aggregator_factory_for_test(&mod_account); + + initialize(&mod_account, b"Fake money", b"FMD", 1, true); + coin::register(&mod_account); + register(&source); + register(&destination); + + mint(&destination, source_addr, 100); + } + + #[test(source = @0xa11ce, destination = @0xb0b, mod_account = @0x1)] + #[expected_failure(abort_code = 0x60001, location = Self)] + public entry fun fail_burn( + source: signer, + destination: signer, + mod_account: signer, + ) acquires Capabilities { + let source_addr = signer::address_of(&source); + + aptos_framework::account::create_account_for_test(source_addr); + aptos_framework::account::create_account_for_test(signer::address_of(&destination)); + aptos_framework::account::create_account_for_test(signer::address_of(&mod_account)); + aggregator_factory::initialize_aggregator_factory_for_test(&mod_account); + + initialize(&mod_account, b"Fake money", b"FMD", 1, true); + coin::register(&mod_account); + register(&source); + register(&destination); + + mint(&mod_account, source_addr, 100); + burn(&destination, 10); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/multisig_account.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/multisig_account.move new file mode 100644 index 000000000..6ea72d7e0 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/multisig_account.move @@ -0,0 +1,2477 @@ +/// Enhanced multisig account standard on Aptos. This is different from the native multisig scheme support enforced via +/// the account's auth key. +/// +/// This module allows creating a flexible and powerful multisig account with seamless support for updating owners +/// without changing the auth key. Users can choose to store transaction payloads waiting for owner signatures on chain +/// or off chain (primary consideration is decentralization/transparency vs gas cost). +/// +/// The multisig account is a resource account underneath. By default, it has no auth key and can only be controlled via +/// the special multisig transaction flow. However, owners can create a transaction to change the auth key to match a +/// private key off chain if so desired. +/// +/// Transactions need to be executed in order of creation, similar to transactions for a normal Aptos account (enforced +/// with account nonce). +/// +/// The flow is like below: +/// 1. Owners can create a new multisig account by calling create (signer is default single owner) or with +/// create_with_owners where multiple initial owner addresses can be specified. This is different (and easier) from +/// the native multisig scheme where the owners' public keys have to be specified. Here, only addresses are needed. +/// 2. Owners can be added/removed any time by calling add_owners or remove_owners. The transactions to do still need +/// to follow the k-of-n scheme specified for the multisig account. +/// 3. To create a new transaction, an owner can call create_transaction with the transaction payload. This will store +/// the full transaction payload on chain, which adds decentralization (censorship is not possible as the data is +/// available on chain) and makes it easier to fetch all transactions waiting for execution. If saving gas is desired, +/// an owner can alternatively call create_transaction_with_hash where only the payload hash is stored. Later execution +/// will be verified using the hash. Only owners can create transactions and a transaction id (incremeting id) will be +/// assigned. +/// 4. To approve or reject a transaction, other owners can call approve() or reject() with the transaction id. +/// 5. If there are enough approvals, any owner can execute the transaction using the special MultisigTransaction type +/// with the transaction id if the full payload is already stored on chain or with the transaction payload if only a +/// hash is stored. Transaction execution will first check with this module that the transaction payload has gotten +/// enough signatures. If so, it will be executed as the multisig account. The owner who executes will pay for gas. +/// 6. If there are enough rejections, any owner can finalize the rejection by calling execute_rejected_transaction(). +/// +/// Note that this multisig account model is not designed to use with a large number of owners. The more owners there +/// are, the more expensive voting on transactions will become. If a large number of owners is designed, such as in a +/// flat governance structure, clients are encouraged to write their own modules on top of this multisig account module +/// and implement the governance voting logic on top. +module aptos_framework::multisig_account { + use aptos_framework::account::{Self, SignerCapability, new_event_handle, create_resource_address}; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::chain_id; + use aptos_framework::create_signer::create_signer; + use aptos_framework::coin; + use aptos_framework::event::{EventHandle, emit_event, emit}; + use aptos_framework::timestamp::now_seconds; + use aptos_std::simple_map::{Self, SimpleMap}; + use aptos_std::table::{Self, Table}; + use std::bcs::to_bytes; + use std::error; + use std::hash::sha3_256; + use std::option::{Self, Option}; + use std::signer::address_of; + use std::string::String; + use std::vector; + + /// The salt used to create a resource account during multisig account creation. + /// This is used to avoid conflicts with other modules that also create resource accounts with the same owner + /// account. + const DOMAIN_SEPARATOR: vector = b"aptos_framework::multisig_account"; + + // Any error codes > 2000 can be thrown as part of transaction prologue. + /// Owner list cannot contain the same address more than once. + const EDUPLICATE_OWNER: u64 = 1; + /// Specified account is not a multisig account. + const EACCOUNT_NOT_MULTISIG: u64 = 2002; + /// Account executing this operation is not an owner of the multisig account. + const ENOT_OWNER: u64 = 2003; + /// Transaction payload cannot be empty. + const EPAYLOAD_CANNOT_BE_EMPTY: u64 = 4; + /// Multisig account must have at least one owner. + const ENOT_ENOUGH_OWNERS: u64 = 5; + /// Transaction with specified id cannot be found. + const ETRANSACTION_NOT_FOUND: u64 = 2006; + /// Provided target function does not match the hash stored in the on-chain transaction. + const EPAYLOAD_DOES_NOT_MATCH_HASH: u64 = 2008; + /// Transaction has not received enough approvals to be executed. + const ENOT_ENOUGH_APPROVALS: u64 = 2009; + /// Provided target function does not match the payload stored in the on-chain transaction. + const EPAYLOAD_DOES_NOT_MATCH: u64 = 2010; + /// Transaction has not received enough rejections to be officially rejected. + const ENOT_ENOUGH_REJECTIONS: u64 = 10; + /// Number of signatures required must be more than zero and at most the total number of owners. + const EINVALID_SIGNATURES_REQUIRED: u64 = 11; + /// Payload hash must be exactly 32 bytes (sha3-256). + const EINVALID_PAYLOAD_HASH: u64 = 12; + /// The multisig account itself cannot be an owner. + const EOWNER_CANNOT_BE_MULTISIG_ACCOUNT_ITSELF: u64 = 13; + /// Multisig accounts has not been enabled on this current network yet. + const EMULTISIG_ACCOUNTS_NOT_ENABLED_YET: u64 = 14; + /// The number of metadata keys and values don't match. + const ENUMBER_OF_METADATA_KEYS_AND_VALUES_DONT_MATCH: u64 = 15; + /// The specified metadata contains duplicate attributes (keys). + const EDUPLICATE_METADATA_KEY: u64 = 16; + /// The sequence number provided is invalid. It must be between [1, next pending transaction - 1]. + const EINVALID_SEQUENCE_NUMBER: u64 = 17; + /// Provided owners to remove and new owners overlap. + const EOWNERS_TO_REMOVE_NEW_OWNERS_OVERLAP: u64 = 18; + /// The number of pending transactions has exceeded the maximum allowed. + const EMAX_PENDING_TRANSACTIONS_EXCEEDED: u64 = 19; + /// The multisig v2 enhancement feature is not enabled. + const EMULTISIG_V2_ENHANCEMENT_NOT_ENABLED: u64 = 20; + + + const ZERO_AUTH_KEY: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; + + const MAX_PENDING_TRANSACTIONS: u64 = 20; + + /// Represents a multisig account's configurations and transactions. + /// This will be stored in the multisig account (created as a resource account separate from any owner accounts). + struct MultisigAccount has key { + // The list of all owner addresses. + owners: vector
, + // The number of signatures required to pass a transaction (k in k-of-n). + num_signatures_required: u64, + // Map from transaction id (incrementing id) to transactions to execute for this multisig account. + // Already executed transactions are deleted to save on storage but can always be accessed via events. + transactions: Table, + // The sequence number assigned to the last executed or rejected transaction. Used to enforce in-order + // executions of proposals, similar to sequence number for a normal (single-user) account. + last_executed_sequence_number: u64, + // The sequence number to assign to the next transaction. This is not always last_executed_sequence_number + 1 + // as there can be multiple pending transactions. The number of pending transactions should be equal to + // next_sequence_number - (last_executed_sequence_number + 1). + next_sequence_number: u64, + // The signer capability controlling the multisig (resource) account. This can be exchanged for the signer. + // Currently not used as the MultisigTransaction can validate and create a signer directly in the VM but + // this can be useful to have for on-chain composability in the future. + signer_cap: Option, + // The multisig account's metadata such as name, description, etc. This can be updated through the multisig + // transaction flow (i.e. self-update). + // Note: Attributes can be arbitrarily set by the multisig account and thus will only be used for off-chain + // display purposes only. They don't change any on-chain semantics of the multisig account. + metadata: SimpleMap>, + + // Events. + add_owners_events: EventHandle, + remove_owners_events: EventHandle, + update_signature_required_events: EventHandle, + create_transaction_events: EventHandle, + vote_events: EventHandle, + execute_rejected_transaction_events: EventHandle, + execute_transaction_events: EventHandle, + transaction_execution_failed_events: EventHandle, + metadata_updated_events: EventHandle, + } + + /// A transaction to be executed in a multisig account. + /// This must contain either the full transaction payload or its hash (stored as bytes). + struct MultisigTransaction has copy, drop, store { + payload: Option>, + payload_hash: Option>, + // Mapping from owner adress to vote (yes for approve, no for reject). Uses a simple map to deduplicate. + votes: SimpleMap, + // The owner who created this transaction. + creator: address, + // The timestamp in seconds when the transaction was created. + creation_time_secs: u64, + } + + /// Contains information about execution failure. + struct ExecutionError has copy, drop, store { + // The module where the error occurs. + abort_location: String, + // There are 3 error types, stored as strings: + // 1. VMError. Indicates an error from the VM, e.g. out of gas, invalid auth key, etc. + // 2. MoveAbort. Indicates an abort, e.g. assertion failure, from inside the executed Move code. + // 3. MoveExecutionFailure. Indicates an error from Move code where the VM could not continue. For example, + // arithmetic failures. + error_type: String, + // The detailed error code explaining which error occurred. + error_code: u64, + } + + /// Used only for verifying multisig account creation on top of existing accounts. + struct MultisigAccountCreationMessage has copy, drop { + // Chain id is included to prevent cross-chain replay. + chain_id: u8, + // Account address is included to prevent cross-account replay (when multiple accounts share the same auth key). + account_address: address, + // Sequence number is not needed for replay protection as the multisig account can only be created once. + // But it's included to ensure timely execution of account creation. + sequence_number: u64, + // The list of owners for the multisig account. + owners: vector
, + // The number of signatures required (signature threshold). + num_signatures_required: u64, + } + + /// Used only for verifying multisig account creation on top of existing accounts and rotating the auth key to 0x0. + struct MultisigAccountCreationWithAuthKeyRevocationMessage has copy, drop { + // Chain id is included to prevent cross-chain replay. + chain_id: u8, + // Account address is included to prevent cross-account replay (when multiple accounts share the same auth key). + account_address: address, + // Sequence number is not needed for replay protection as the multisig account can only be created once. + // But it's included to ensure timely execution of account creation. + sequence_number: u64, + // The list of owners for the multisig account. + owners: vector
, + // The number of signatures required (signature threshold). + num_signatures_required: u64, + } + + /// Event emitted when new owners are added to the multisig account. + struct AddOwnersEvent has drop, store { + owners_added: vector
, + } + + #[event] + struct AddOwners has drop, store { + multisig_account: address, + owners_added: vector
, + } + + /// Event emitted when new owners are removed from the multisig account. + struct RemoveOwnersEvent has drop, store { + owners_removed: vector
, + } + + #[event] + struct RemoveOwners has drop, store { + multisig_account: address, + owners_removed: vector
, + } + + /// Event emitted when the number of signatures required is updated. + struct UpdateSignaturesRequiredEvent has drop, store { + old_num_signatures_required: u64, + new_num_signatures_required: u64, + } + + #[event] + struct UpdateSignaturesRequired has drop, store { + multisig_account: address, + old_num_signatures_required: u64, + new_num_signatures_required: u64, + } + + /// Event emitted when a transaction is created. + struct CreateTransactionEvent has drop, store { + creator: address, + sequence_number: u64, + transaction: MultisigTransaction, + } + + #[event] + struct CreateTransaction has drop, store { + multisig_account: address, + creator: address, + sequence_number: u64, + transaction: MultisigTransaction, + } + + /// Event emitted when an owner approves or rejects a transaction. + struct VoteEvent has drop, store { + owner: address, + sequence_number: u64, + approved: bool, + } + + #[event] + struct Vote has drop, store { + multisig_account: address, + owner: address, + sequence_number: u64, + approved: bool, + } + + /// Event emitted when a transaction is officially rejected because the number of rejections has reached the + /// number of signatures required. + struct ExecuteRejectedTransactionEvent has drop, store { + sequence_number: u64, + num_rejections: u64, + executor: address, + } + + #[event] + struct ExecuteRejectedTransaction has drop, store { + multisig_account: address, + sequence_number: u64, + num_rejections: u64, + executor: address, + } + + /// Event emitted when a transaction is executed. + struct TransactionExecutionSucceededEvent has drop, store { + executor: address, + sequence_number: u64, + transaction_payload: vector, + num_approvals: u64, + } + + #[event] + struct TransactionExecutionSucceeded has drop, store { + multisig_account: address, + executor: address, + sequence_number: u64, + transaction_payload: vector, + num_approvals: u64, + } + + /// Event emitted when a transaction's execution failed. + struct TransactionExecutionFailedEvent has drop, store { + executor: address, + sequence_number: u64, + transaction_payload: vector, + num_approvals: u64, + execution_error: ExecutionError, + } + + #[event] + struct TransactionExecutionFailed has drop, store { + multisig_account: address, + executor: address, + sequence_number: u64, + transaction_payload: vector, + num_approvals: u64, + execution_error: ExecutionError, + } + + /// Event emitted when a transaction's metadata is updated. + struct MetadataUpdatedEvent has drop, store { + old_metadata: SimpleMap>, + new_metadata: SimpleMap>, + } + + #[event] + struct MetadataUpdated has drop, store { + multisig_account: address, + old_metadata: SimpleMap>, + new_metadata: SimpleMap>, + } + + ////////////////////////// View functions /////////////////////////////// + + #[view] + /// Return the multisig account's metadata. + public fun metadata(multisig_account: address): SimpleMap> acquires MultisigAccount { + borrow_global(multisig_account).metadata + } + + #[view] + /// Return the number of signatures required to execute or execute-reject a transaction in the provided + /// multisig account. + public fun num_signatures_required(multisig_account: address): u64 acquires MultisigAccount { + borrow_global(multisig_account).num_signatures_required + } + + #[view] + /// Return a vector of all of the provided multisig account's owners. + public fun owners(multisig_account: address): vector
acquires MultisigAccount { + borrow_global(multisig_account).owners + } + + #[view] + /// Return true if the provided owner is an owner of the provided multisig account. + public fun is_owner(owner: address, multisig_account: address): bool acquires MultisigAccount { + vector::contains(&borrow_global(multisig_account).owners, &owner) + } + + #[view] + /// Return the transaction with the given transaction id. + public fun get_transaction( + multisig_account: address, + sequence_number: u64, + ): MultisigTransaction acquires MultisigAccount { + let multisig_account_resource = borrow_global(multisig_account); + assert!( + sequence_number > 0 && sequence_number < multisig_account_resource.next_sequence_number, + error::invalid_argument(EINVALID_SEQUENCE_NUMBER), + ); + *table::borrow(&multisig_account_resource.transactions, sequence_number) + } + + #[view] + /// Return all pending transactions. + public fun get_pending_transactions( + multisig_account: address + ): vector acquires MultisigAccount { + let pending_transactions: vector = vector[]; + let multisig_account = borrow_global(multisig_account); + let i = multisig_account.last_executed_sequence_number + 1; + let next_sequence_number = multisig_account.next_sequence_number; + while (i < next_sequence_number) { + vector::push_back(&mut pending_transactions, *table::borrow(&multisig_account.transactions, i)); + i = i + 1; + }; + pending_transactions + } + + #[view] + /// Return the payload for the next transaction in the queue. + public fun get_next_transaction_payload( + multisig_account: address, provided_payload: vector): vector acquires MultisigAccount { + let multisig_account_resource = borrow_global(multisig_account); + let sequence_number = multisig_account_resource.last_executed_sequence_number + 1; + let transaction = table::borrow(&multisig_account_resource.transactions, sequence_number); + + if (option::is_some(&transaction.payload)) { + *option::borrow(&transaction.payload) + } else { + provided_payload + } + } + + #[view] + /// Return true if the transaction with given transaction id can be executed now. + public fun can_be_executed(multisig_account: address, sequence_number: u64): bool acquires MultisigAccount { + assert_valid_sequence_number(multisig_account, sequence_number); + let (num_approvals, _) = num_approvals_and_rejections(multisig_account, sequence_number); + sequence_number == last_resolved_sequence_number(multisig_account) + 1 && + num_approvals >= num_signatures_required(multisig_account) + } + + #[view] + /// Return true if the owner can execute the transaction with given transaction id now. + public fun can_execute(owner: address, multisig_account: address, sequence_number: u64): bool acquires MultisigAccount { + assert_valid_sequence_number(multisig_account, sequence_number); + let (num_approvals, _) = num_approvals_and_rejections(multisig_account, sequence_number); + if (!has_voted_for_approval(multisig_account, sequence_number, owner)) { + num_approvals = num_approvals + 1; + }; + is_owner(owner, multisig_account) && + sequence_number == last_resolved_sequence_number(multisig_account) + 1 && + num_approvals >= num_signatures_required(multisig_account) + } + + #[view] + /// Return true if the transaction with given transaction id can be officially rejected. + public fun can_be_rejected(multisig_account: address, sequence_number: u64): bool acquires MultisigAccount { + assert_valid_sequence_number(multisig_account, sequence_number); + let (_, num_rejections) = num_approvals_and_rejections(multisig_account, sequence_number); + sequence_number == last_resolved_sequence_number(multisig_account) + 1 && + num_rejections >= num_signatures_required(multisig_account) + } + + #[view] + /// Return true if the owner can execute the "rejected" transaction with given transaction id now. + public fun can_reject(owner: address, multisig_account: address, sequence_number: u64): bool acquires MultisigAccount { + assert_valid_sequence_number(multisig_account, sequence_number); + let (_, num_rejections) = num_approvals_and_rejections(multisig_account, sequence_number); + if (!has_voted_for_rejection(multisig_account, sequence_number, owner)) { + num_rejections = num_rejections + 1; + }; + is_owner(owner, multisig_account) && + sequence_number == last_resolved_sequence_number(multisig_account) + 1 && + num_rejections >= num_signatures_required(multisig_account) + } + + #[view] + /// Return the predicted address for the next multisig account if created from the given creator address. + public fun get_next_multisig_account_address(creator: address): address { + let owner_nonce = account::get_sequence_number(creator); + create_resource_address(&creator, create_multisig_account_seed(to_bytes(&owner_nonce))) + } + + #[view] + /// Return the id of the last transaction that was executed (successful or failed) or removed. + public fun last_resolved_sequence_number(multisig_account: address): u64 acquires MultisigAccount { + let multisig_account_resource = borrow_global_mut(multisig_account); + multisig_account_resource.last_executed_sequence_number + } + + #[view] + /// Return the id of the next transaction created. + public fun next_sequence_number(multisig_account: address): u64 acquires MultisigAccount { + let multisig_account_resource = borrow_global_mut(multisig_account); + multisig_account_resource.next_sequence_number + } + + #[view] + /// Return a bool tuple indicating whether an owner has voted and if so, whether they voted yes or no. + public fun vote( + multisig_account: address, sequence_number: u64, owner: address): (bool, bool) acquires MultisigAccount { + let multisig_account_resource = borrow_global_mut(multisig_account); + assert!( + sequence_number > 0 && sequence_number < multisig_account_resource.next_sequence_number, + error::invalid_argument(EINVALID_SEQUENCE_NUMBER), + ); + let transaction = table::borrow(&multisig_account_resource.transactions, sequence_number); + let votes = &transaction.votes; + let voted = simple_map::contains_key(votes, &owner); + let vote = voted && *simple_map::borrow(votes, &owner); + (voted, vote) + } + + #[view] + public fun available_transaction_queue_capacity(multisig_account: address): u64 acquires MultisigAccount { + let multisig_account_resource = borrow_global_mut(multisig_account); + let num_pending_transactions = multisig_account_resource.next_sequence_number - multisig_account_resource.last_executed_sequence_number - 1; + if (num_pending_transactions > MAX_PENDING_TRANSACTIONS) { + 0 + } else { + MAX_PENDING_TRANSACTIONS - num_pending_transactions + } + } + + ////////////////////////// Multisig account creation functions /////////////////////////////// + + /// Creates a new multisig account on top of an existing account. + /// + /// This offers a migration path for an existing account with a multi-ed25519 auth key (native multisig account). + /// In order to ensure a malicious module cannot obtain backdoor control over an existing account, a signed message + /// with a valid signature from the account's auth key is required. + /// + /// Note that this does not revoke auth key-based control over the account. Owners should separately rotate the auth + /// key after they are fully migrated to the new multisig account. Alternatively, they can call + /// create_with_existing_account_and_revoke_auth_key instead. + public entry fun create_with_existing_account( + multisig_address: address, + owners: vector
, + num_signatures_required: u64, + account_scheme: u8, + account_public_key: vector, + create_multisig_account_signed_message: vector, + metadata_keys: vector, + metadata_values: vector>, + ) acquires MultisigAccount { + // Verify that the `MultisigAccountCreationMessage` has the right information and is signed by the account + // owner's key. + let proof_challenge = MultisigAccountCreationMessage { + chain_id: chain_id::get(), + account_address: multisig_address, + sequence_number: account::get_sequence_number(multisig_address), + owners, + num_signatures_required, + }; + account::verify_signed_message( + multisig_address, + account_scheme, + account_public_key, + create_multisig_account_signed_message, + proof_challenge, + ); + + // We create the signer for the multisig account here since this is required to add the MultisigAccount resource + // This should be safe and authorized because we have verified the signed message from the existing account + // that authorizes creating a multisig account with the specified owners and signature threshold. + let multisig_account = &create_signer(multisig_address); + create_with_owners_internal( + multisig_account, + owners, + num_signatures_required, + option::none(), + metadata_keys, + metadata_values, + ); + } + + /// Creates a new multisig account on top of an existing account and immediately rotate the origin auth key to 0x0. + /// + /// Note: If the original account is a resource account, this does not revoke all control over it as if any + /// SignerCapability of the resource account still exists, it can still be used to generate the signer for the + /// account. + public entry fun create_with_existing_account_and_revoke_auth_key( + multisig_address: address, + owners: vector
, + num_signatures_required: u64, + account_scheme: u8, + account_public_key: vector, + create_multisig_account_signed_message: vector, + metadata_keys: vector, + metadata_values: vector>, + ) acquires MultisigAccount { + // Verify that the `MultisigAccountCreationMessage` has the right information and is signed by the account + // owner's key. + let proof_challenge = MultisigAccountCreationWithAuthKeyRevocationMessage { + chain_id: chain_id::get(), + account_address: multisig_address, + sequence_number: account::get_sequence_number(multisig_address), + owners, + num_signatures_required, + }; + account::verify_signed_message( + multisig_address, + account_scheme, + account_public_key, + create_multisig_account_signed_message, + proof_challenge, + ); + + // We create the signer for the multisig account here since this is required to add the MultisigAccount resource + // This should be safe and authorized because we have verified the signed message from the existing account + // that authorizes creating a multisig account with the specified owners and signature threshold. + let multisig_account = &create_signer(multisig_address); + create_with_owners_internal( + multisig_account, + owners, + num_signatures_required, + option::none(), + metadata_keys, + metadata_values, + ); + + // Rotate the account's auth key to 0x0, which effectively revokes control via auth key. + let multisig_address = address_of(multisig_account); + account::rotate_authentication_key_internal(multisig_account, ZERO_AUTH_KEY); + // This also needs to revoke any signer capability or rotation capability that exists for the account to + // completely remove all access to the account. + if (account::is_signer_capability_offered(multisig_address)) { + account::revoke_any_signer_capability(multisig_account); + }; + if (account::is_rotation_capability_offered(multisig_address)) { + account::revoke_any_rotation_capability(multisig_account); + }; + } + + /// Creates a new multisig account and add the signer as a single owner. + public entry fun create( + owner: &signer, + num_signatures_required: u64, + metadata_keys: vector, + metadata_values: vector>, + ) acquires MultisigAccount { + create_with_owners(owner, vector[], num_signatures_required, metadata_keys, metadata_values); + } + + /// Creates a new multisig account with the specified additional owner list and signatures required. + /// + /// @param additional_owners The owner account who calls this function cannot be in the additional_owners and there + /// cannot be any duplicate owners in the list. + /// @param num_signatures_required The number of signatures required to execute a transaction. Must be at least 1 and + /// at most the total number of owners. + public entry fun create_with_owners( + owner: &signer, + additional_owners: vector
, + num_signatures_required: u64, + metadata_keys: vector, + metadata_values: vector>, + ) acquires MultisigAccount { + let (multisig_account, multisig_signer_cap) = create_multisig_account(owner); + vector::push_back(&mut additional_owners, address_of(owner)); + create_with_owners_internal( + &multisig_account, + additional_owners, + num_signatures_required, + option::some(multisig_signer_cap), + metadata_keys, + metadata_values, + ); + } + + /// Like `create_with_owners`, but removes the calling account after creation. + /// + /// This is for creating a vanity multisig account from a bootstrapping account that should not + /// be an owner after the vanity multisig address has been secured. + public entry fun create_with_owners_then_remove_bootstrapper( + bootstrapper: &signer, + owners: vector
, + num_signatures_required: u64, + metadata_keys: vector, + metadata_values: vector>, + ) acquires MultisigAccount { + let bootstrapper_address = address_of(bootstrapper); + create_with_owners( + bootstrapper, + owners, + num_signatures_required, + metadata_keys, + metadata_values + ); + update_owner_schema( + get_next_multisig_account_address(bootstrapper_address), + vector[], + vector[bootstrapper_address], + option::none() + ); + } + + fun create_with_owners_internal( + multisig_account: &signer, + owners: vector
, + num_signatures_required: u64, + multisig_account_signer_cap: Option, + metadata_keys: vector, + metadata_values: vector>, + ) acquires MultisigAccount { + assert!(features::multisig_accounts_enabled(), error::unavailable(EMULTISIG_ACCOUNTS_NOT_ENABLED_YET)); + assert!( + num_signatures_required > 0 && num_signatures_required <= vector::length(&owners), + error::invalid_argument(EINVALID_SIGNATURES_REQUIRED), + ); + + let multisig_address = address_of(multisig_account); + validate_owners(&owners, multisig_address); + move_to(multisig_account, MultisigAccount { + owners, + num_signatures_required, + transactions: table::new(), + metadata: simple_map::create>(), + // First transaction will start at id 1 instead of 0. + last_executed_sequence_number: 0, + next_sequence_number: 1, + signer_cap: multisig_account_signer_cap, + add_owners_events: new_event_handle(multisig_account), + remove_owners_events: new_event_handle(multisig_account), + update_signature_required_events: new_event_handle(multisig_account), + create_transaction_events: new_event_handle(multisig_account), + vote_events: new_event_handle(multisig_account), + execute_rejected_transaction_events: new_event_handle(multisig_account), + execute_transaction_events: new_event_handle(multisig_account), + transaction_execution_failed_events: new_event_handle(multisig_account), + metadata_updated_events: new_event_handle(multisig_account), + }); + + update_metadata_internal(multisig_account, metadata_keys, metadata_values, false); + } + + ////////////////////////// Self-updates /////////////////////////////// + + /// Similar to add_owners, but only allow adding one owner. + entry fun add_owner(multisig_account: &signer, new_owner: address) acquires MultisigAccount { + add_owners(multisig_account, vector[new_owner]); + } + + /// Add new owners to the multisig account. This can only be invoked by the multisig account itself, through the + /// proposal flow. + /// + /// Note that this function is not public so it can only be invoked directly instead of via a module or script. This + /// ensures that a multisig transaction cannot lead to another module obtaining the multisig signer and using it to + /// maliciously alter the owners list. + entry fun add_owners( + multisig_account: &signer, new_owners: vector
) acquires MultisigAccount { + update_owner_schema( + address_of(multisig_account), + new_owners, + vector[], + option::none() + ); + } + + /// Add owners then update number of signatures required, in a single operation. + entry fun add_owners_and_update_signatures_required( + multisig_account: &signer, + new_owners: vector
, + new_num_signatures_required: u64 + ) acquires MultisigAccount { + update_owner_schema( + address_of(multisig_account), + new_owners, + vector[], + option::some(new_num_signatures_required) + ); + } + + /// Similar to remove_owners, but only allow removing one owner. + entry fun remove_owner( + multisig_account: &signer, owner_to_remove: address) acquires MultisigAccount { + remove_owners(multisig_account, vector[owner_to_remove]); + } + + /// Remove owners from the multisig account. This can only be invoked by the multisig account itself, through the + /// proposal flow. + /// + /// This function skips any owners who are not in the multisig account's list of owners. + /// Note that this function is not public so it can only be invoked directly instead of via a module or script. This + /// ensures that a multisig transaction cannot lead to another module obtaining the multisig signer and using it to + /// maliciously alter the owners list. + entry fun remove_owners( + multisig_account: &signer, owners_to_remove: vector
) acquires MultisigAccount { + update_owner_schema( + address_of(multisig_account), + vector[], + owners_to_remove, + option::none() + ); + } + + /// Swap an owner in for an old one, without changing required signatures. + entry fun swap_owner( + multisig_account: &signer, + to_swap_in: address, + to_swap_out: address + ) acquires MultisigAccount { + update_owner_schema( + address_of(multisig_account), + vector[to_swap_in], + vector[to_swap_out], + option::none() + ); + } + + /// Swap owners in and out, without changing required signatures. + entry fun swap_owners( + multisig_account: &signer, + to_swap_in: vector
, + to_swap_out: vector
+ ) acquires MultisigAccount { + update_owner_schema( + address_of(multisig_account), + to_swap_in, + to_swap_out, + option::none() + ); + } + + /// Swap owners in and out, updating number of required signatures. + entry fun swap_owners_and_update_signatures_required( + multisig_account: &signer, + new_owners: vector
, + owners_to_remove: vector
, + new_num_signatures_required: u64 + ) acquires MultisigAccount { + update_owner_schema( + address_of(multisig_account), + new_owners, + owners_to_remove, + option::some(new_num_signatures_required) + ); + } + + /// Update the number of signatures required to execute transaction in the specified multisig account. + /// + /// This can only be invoked by the multisig account itself, through the proposal flow. + /// Note that this function is not public so it can only be invoked directly instead of via a module or script. This + /// ensures that a multisig transaction cannot lead to another module obtaining the multisig signer and using it to + /// maliciously alter the number of signatures required. + entry fun update_signatures_required( + multisig_account: &signer, new_num_signatures_required: u64) acquires MultisigAccount { + update_owner_schema( + address_of(multisig_account), + vector[], + vector[], + option::some(new_num_signatures_required) + ); + } + + /// Allow the multisig account to update its own metadata. Note that this overrides the entire existing metadata. + /// If any attributes are not specified in the metadata, they will be removed! + /// + /// This can only be invoked by the multisig account itself, through the proposal flow. + /// Note that this function is not public so it can only be invoked directly instead of via a module or script. This + /// ensures that a multisig transaction cannot lead to another module obtaining the multisig signer and using it to + /// maliciously alter the number of signatures required. + entry fun update_metadata( + multisig_account: &signer, keys: vector, values: vector>) acquires MultisigAccount { + update_metadata_internal(multisig_account, keys, values, true); + } + + fun update_metadata_internal( + multisig_account: &signer, + keys: vector, + values: vector>, + emit_event: bool, + ) acquires MultisigAccount { + let num_attributes = vector::length(&keys); + assert!( + num_attributes == vector::length(&values), + error::invalid_argument(ENUMBER_OF_METADATA_KEYS_AND_VALUES_DONT_MATCH), + ); + + let multisig_address = address_of(multisig_account); + assert_multisig_account_exists(multisig_address); + let multisig_account_resource = borrow_global_mut(multisig_address); + let old_metadata = multisig_account_resource.metadata; + multisig_account_resource.metadata = simple_map::create>(); + let metadata = &mut multisig_account_resource.metadata; + let i = 0; + while (i < num_attributes) { + let key = *vector::borrow(&keys, i); + let value = *vector::borrow(&values, i); + assert!( + !simple_map::contains_key(metadata, &key), + error::invalid_argument(EDUPLICATE_METADATA_KEY), + ); + + simple_map::add(metadata, key, value); + i = i + 1; + }; + + if (emit_event) { + if (std::features::module_event_migration_enabled()) { + emit( + MetadataUpdated { + multisig_account: multisig_address, + old_metadata, + new_metadata: multisig_account_resource.metadata, + } + ) + }; + emit_event( + &mut multisig_account_resource.metadata_updated_events, + MetadataUpdatedEvent { + old_metadata, + new_metadata: multisig_account_resource.metadata, + } + ); + }; + } + + ////////////////////////// Multisig transaction flow /////////////////////////////// + + /// Create a multisig transaction, which will have one approval initially (from the creator). + public entry fun create_transaction( + owner: &signer, + multisig_account: address, + payload: vector, + ) acquires MultisigAccount { + assert!(vector::length(&payload) > 0, error::invalid_argument(EPAYLOAD_CANNOT_BE_EMPTY)); + + assert_multisig_account_exists(multisig_account); + assert_is_owner(owner, multisig_account); + + let creator = address_of(owner); + let transaction = MultisigTransaction { + payload: option::some(payload), + payload_hash: option::none>(), + votes: simple_map::create(), + creator, + creation_time_secs: now_seconds(), + }; + add_transaction(creator, multisig_account, transaction); + } + + /// Create a multisig transaction with a transaction hash instead of the full payload. + /// This means the payload will be stored off chain for gas saving. Later, during execution, the executor will need + /// to provide the full payload, which will be validated against the hash stored on-chain. + public entry fun create_transaction_with_hash( + owner: &signer, + multisig_account: address, + payload_hash: vector, + ) acquires MultisigAccount { + // Payload hash is a sha3-256 hash, so it must be exactly 32 bytes. + assert!(vector::length(&payload_hash) == 32, error::invalid_argument(EINVALID_PAYLOAD_HASH)); + + assert_multisig_account_exists(multisig_account); + assert_is_owner(owner, multisig_account); + + let creator = address_of(owner); + let transaction = MultisigTransaction { + payload: option::none>(), + payload_hash: option::some(payload_hash), + votes: simple_map::create(), + creator, + creation_time_secs: now_seconds(), + }; + add_transaction(creator, multisig_account, transaction); + } + + /// Approve a multisig transaction. + public entry fun approve_transaction( + owner: &signer, multisig_account: address, sequence_number: u64) acquires MultisigAccount { + vote_transanction(owner, multisig_account, sequence_number, true); + } + + /// Reject a multisig transaction. + public entry fun reject_transaction( + owner: &signer, multisig_account: address, sequence_number: u64) acquires MultisigAccount { + vote_transanction(owner, multisig_account, sequence_number, false); + } + + /// Generic function that can be used to either approve or reject a multisig transaction + /// Retained for backward compatibility: the function with the typographical error in its name + /// will continue to be an accessible entry point. + public entry fun vote_transanction( + owner: &signer, multisig_account: address, sequence_number: u64, approved: bool) acquires MultisigAccount { + assert_multisig_account_exists(multisig_account); + let multisig_account_resource = borrow_global_mut(multisig_account); + assert_is_owner_internal(owner, multisig_account_resource); + + assert!( + table::contains(&multisig_account_resource.transactions, sequence_number), + error::not_found(ETRANSACTION_NOT_FOUND), + ); + let transaction = table::borrow_mut(&mut multisig_account_resource.transactions, sequence_number); + let votes = &mut transaction.votes; + let owner_addr = address_of(owner); + + if (simple_map::contains_key(votes, &owner_addr)) { + *simple_map::borrow_mut(votes, &owner_addr) = approved; + } else { + simple_map::add(votes, owner_addr, approved); + }; + + if (std::features::module_event_migration_enabled()) { + emit( + Vote { + multisig_account, + owner: owner_addr, + sequence_number, + approved, + } + ); + }; + emit_event( + &mut multisig_account_resource.vote_events, + VoteEvent { + owner: owner_addr, + sequence_number, + approved, + } + ); + } + + /// Generic function that can be used to either approve or reject a multisig transaction + public entry fun vote_transaction( + owner: &signer, multisig_account: address, sequence_number: u64, approved: bool) acquires MultisigAccount { + assert!(features::multisig_v2_enhancement_feature_enabled(), error::invalid_state(EMULTISIG_V2_ENHANCEMENT_NOT_ENABLED)); + vote_transanction(owner, multisig_account, sequence_number, approved); + } + + /// Generic function that can be used to either approve or reject a batch of transactions within a specified range. + public entry fun vote_transactions( + owner: &signer, multisig_account: address, starting_sequence_number: u64, final_sequence_number: u64, approved: bool) acquires MultisigAccount { + assert!(features::multisig_v2_enhancement_feature_enabled(), error::invalid_state(EMULTISIG_V2_ENHANCEMENT_NOT_ENABLED)); + let sequence_number = starting_sequence_number; + while(sequence_number <= final_sequence_number) { + vote_transanction(owner, multisig_account, sequence_number, approved); + sequence_number = sequence_number + 1; + } + } + + /// Remove the next transaction if it has sufficient owner rejections. + public entry fun execute_rejected_transaction( + owner: &signer, + multisig_account: address, + ) acquires MultisigAccount { + assert_multisig_account_exists(multisig_account); + assert_is_owner(owner, multisig_account); + + let sequence_number = last_resolved_sequence_number(multisig_account) + 1; + let owner_addr = address_of(owner); + if (features::multisig_v2_enhancement_feature_enabled()) { + // Implicitly vote for rejection if the owner has not voted for rejection yet. + if (!has_voted_for_rejection(multisig_account, sequence_number, owner_addr)) { + reject_transaction(owner, multisig_account, sequence_number); + } + }; + + let multisig_account_resource = borrow_global_mut(multisig_account); + let (_, num_rejections) = remove_executed_transaction(multisig_account_resource); + assert!( + num_rejections >= multisig_account_resource.num_signatures_required, + error::invalid_state(ENOT_ENOUGH_REJECTIONS), + ); + + if (std::features::module_event_migration_enabled()) { + emit( + ExecuteRejectedTransaction { + multisig_account, + sequence_number, + num_rejections, + executor: address_of(owner), + } + ); + }; + emit_event( + &mut multisig_account_resource.execute_rejected_transaction_events, + ExecuteRejectedTransactionEvent { + sequence_number, + num_rejections, + executor: owner_addr, + } + ); + } + + /// Remove the next transactions until the final_sequence_number if they have sufficient owner rejections. + public entry fun execute_rejected_transactions( + owner: &signer, + multisig_account: address, + final_sequence_number: u64, + ) acquires MultisigAccount { + assert!(features::multisig_v2_enhancement_feature_enabled(), error::invalid_state(EMULTISIG_V2_ENHANCEMENT_NOT_ENABLED)); + assert!(last_resolved_sequence_number(multisig_account) < final_sequence_number, error::invalid_argument(EINVALID_SEQUENCE_NUMBER)); + assert!(final_sequence_number < next_sequence_number(multisig_account), error::invalid_argument(EINVALID_SEQUENCE_NUMBER)); + while(last_resolved_sequence_number(multisig_account) < final_sequence_number) { + execute_rejected_transaction(owner, multisig_account); + } + } + + ////////////////////////// To be called by VM only /////////////////////////////// + + /// Called by the VM as part of transaction prologue, which is invoked during mempool transaction validation and as + /// the first step of transaction execution. + /// + /// Transaction payload is optional if it's already stored on chain for the transaction. + fun validate_multisig_transaction( + owner: &signer, multisig_account: address, payload: vector) acquires MultisigAccount { + assert_multisig_account_exists(multisig_account); + assert_is_owner(owner, multisig_account); + let sequence_number = last_resolved_sequence_number(multisig_account) + 1; + assert_transaction_exists(multisig_account, sequence_number); + + if (features::multisig_v2_enhancement_feature_enabled()) { + assert!( + can_execute(address_of(owner), multisig_account, sequence_number), + error::invalid_argument(ENOT_ENOUGH_APPROVALS), + ); + } + else { + assert!( + can_be_executed(multisig_account, sequence_number), + error::invalid_argument(ENOT_ENOUGH_APPROVALS), + ); + }; + + // If the transaction payload is not stored on chain, verify that the provided payload matches the hashes stored + // on chain. + let multisig_account_resource = borrow_global(multisig_account); + let transaction = table::borrow(&multisig_account_resource.transactions, sequence_number); + if (option::is_some(&transaction.payload_hash)) { + let payload_hash = option::borrow(&transaction.payload_hash); + assert!( + sha3_256(payload) == *payload_hash, + error::invalid_argument(EPAYLOAD_DOES_NOT_MATCH_HASH), + ); + }; + + // If the transaction payload is stored on chain and there is a provided payload, + // verify that the provided payload matches the stored payload. + if (features::abort_if_multisig_payload_mismatch_enabled() + && option::is_some(&transaction.payload) + && !vector::is_empty(&payload) + ) { + let stored_payload = option::borrow(&transaction.payload); + assert!( + payload == *stored_payload, + error::invalid_argument(EPAYLOAD_DOES_NOT_MATCH), + ); + } + } + + /// Post-execution cleanup for a successful multisig transaction execution. + /// This function is private so no other code can call this beside the VM itself as part of MultisigTransaction. + fun successful_transaction_execution_cleanup( + executor: address, + multisig_account: address, + transaction_payload: vector, + ) acquires MultisigAccount { + let num_approvals = transaction_execution_cleanup_common(executor, multisig_account); + let multisig_account_resource = borrow_global_mut(multisig_account); + if (std::features::module_event_migration_enabled()) { + emit( + TransactionExecutionSucceeded { + multisig_account, + sequence_number: multisig_account_resource.last_executed_sequence_number, + transaction_payload, + num_approvals, + executor, + } + ); + }; + emit_event( + &mut multisig_account_resource.execute_transaction_events, + TransactionExecutionSucceededEvent { + sequence_number: multisig_account_resource.last_executed_sequence_number, + transaction_payload, + num_approvals, + executor, + } + ); + } + + /// Post-execution cleanup for a failed multisig transaction execution. + /// This function is private so no other code can call this beside the VM itself as part of MultisigTransaction. + fun failed_transaction_execution_cleanup( + executor: address, + multisig_account: address, + transaction_payload: vector, + execution_error: ExecutionError, + ) acquires MultisigAccount { + let num_approvals = transaction_execution_cleanup_common(executor, multisig_account); + let multisig_account_resource = borrow_global_mut(multisig_account); + if (std::features::module_event_migration_enabled()) { + emit( + TransactionExecutionFailed { + multisig_account, + executor, + sequence_number: multisig_account_resource.last_executed_sequence_number, + transaction_payload, + num_approvals, + execution_error, + } + ); + }; + emit_event( + &mut multisig_account_resource.transaction_execution_failed_events, + TransactionExecutionFailedEvent { + executor, + sequence_number: multisig_account_resource.last_executed_sequence_number, + transaction_payload, + num_approvals, + execution_error, + } + ); + } + + ////////////////////////// Private functions /////////////////////////////// + + inline fun transaction_execution_cleanup_common(executor: address, multisig_account: address): u64 acquires MultisigAccount { + let sequence_number = last_resolved_sequence_number(multisig_account) + 1; + let implicit_approval = !has_voted_for_approval(multisig_account, sequence_number, executor); + + let multisig_account_resource = borrow_global_mut(multisig_account); + let (num_approvals, _) = remove_executed_transaction(multisig_account_resource); + + if (features::multisig_v2_enhancement_feature_enabled() && implicit_approval) { + if (std::features::module_event_migration_enabled()) { + emit( + Vote { + multisig_account, + owner: executor, + sequence_number, + approved: true, + } + ); + }; + num_approvals = num_approvals + 1; + emit_event( + &mut multisig_account_resource.vote_events, + VoteEvent { + owner: executor, + sequence_number, + approved: true, + } + ); + }; + + num_approvals + } + + // Remove the next transaction in the queue as it's been executed and return the number of approvals it had. + fun remove_executed_transaction(multisig_account_resource: &mut MultisigAccount): (u64, u64) { + let sequence_number = multisig_account_resource.last_executed_sequence_number + 1; + let transaction = table::remove(&mut multisig_account_resource.transactions, sequence_number); + multisig_account_resource.last_executed_sequence_number = sequence_number; + num_approvals_and_rejections_internal(&multisig_account_resource.owners, &transaction) + } + + inline fun add_transaction( + creator: address, + multisig_account: address, + transaction: MultisigTransaction + ) { + if (features::multisig_v2_enhancement_feature_enabled()) { + assert!( + available_transaction_queue_capacity(multisig_account) > 0, + error::invalid_state(EMAX_PENDING_TRANSACTIONS_EXCEEDED) + ); + }; + + let multisig_account_resource = borrow_global_mut(multisig_account); + + // The transaction creator also automatically votes for the transaction. + simple_map::add(&mut transaction.votes, creator, true); + + let sequence_number = multisig_account_resource.next_sequence_number; + multisig_account_resource.next_sequence_number = sequence_number + 1; + table::add(&mut multisig_account_resource.transactions, sequence_number, transaction); + if (std::features::module_event_migration_enabled()) { + emit( + CreateTransaction { multisig_account: multisig_account, creator, sequence_number, transaction } + ); + }; + emit_event( + &mut multisig_account_resource.create_transaction_events, + CreateTransactionEvent { creator, sequence_number, transaction }, + ); + } + + fun create_multisig_account(owner: &signer): (signer, SignerCapability) { + let owner_nonce = account::get_sequence_number(address_of(owner)); + let (multisig_signer, multisig_signer_cap) = + account::create_resource_account(owner, create_multisig_account_seed(to_bytes(&owner_nonce))); + // Register the account to receive APT as this is not done by default as part of the resource account creation + // flow. + if (!coin::is_account_registered(address_of(&multisig_signer))) { + coin::register(&multisig_signer); + }; + + (multisig_signer, multisig_signer_cap) + } + + fun create_multisig_account_seed(seed: vector): vector { + // Generate a seed that will be used to create the resource account that hosts the multisig account. + let multisig_account_seed = vector::empty(); + vector::append(&mut multisig_account_seed, DOMAIN_SEPARATOR); + vector::append(&mut multisig_account_seed, seed); + + multisig_account_seed + } + + fun validate_owners(owners: &vector
, multisig_account: address) { + let distinct_owners: vector
= vector[]; + vector::for_each_ref(owners, |owner| { + let owner = *owner; + assert!(owner != multisig_account, error::invalid_argument(EOWNER_CANNOT_BE_MULTISIG_ACCOUNT_ITSELF)); + let (found, _) = vector::index_of(&distinct_owners, &owner); + assert!(!found, error::invalid_argument(EDUPLICATE_OWNER)); + vector::push_back(&mut distinct_owners, owner); + }); + } + + inline fun assert_is_owner_internal(owner: &signer, multisig_account: &MultisigAccount) { + assert!( + vector::contains(&multisig_account.owners, &address_of(owner)), + error::permission_denied(ENOT_OWNER), + ); + } + + inline fun assert_is_owner(owner: &signer, multisig_account: address) acquires MultisigAccount { + let multisig_account_resource = borrow_global(multisig_account); + assert_is_owner_internal(owner, multisig_account_resource); + } + + inline fun num_approvals_and_rejections_internal(owners: &vector
, transaction: &MultisigTransaction): (u64, u64) { + let num_approvals = 0; + let num_rejections = 0; + + let votes = &transaction.votes; + vector::for_each_ref(owners, |owner| { + if (simple_map::contains_key(votes, owner)) { + if (*simple_map::borrow(votes, owner)) { + num_approvals = num_approvals + 1; + } else { + num_rejections = num_rejections + 1; + }; + } + }); + + (num_approvals, num_rejections) + } + + inline fun num_approvals_and_rejections(multisig_account: address, sequence_number: u64): (u64, u64) acquires MultisigAccount { + let multisig_account_resource = borrow_global(multisig_account); + let transaction = table::borrow(&multisig_account_resource.transactions, sequence_number); + num_approvals_and_rejections_internal(&multisig_account_resource.owners, transaction) + } + + inline fun has_voted_for_approval(multisig_account: address, sequence_number: u64, owner: address): bool acquires MultisigAccount { + let (voted, vote) = vote(multisig_account, sequence_number, owner); + voted && vote + } + + inline fun has_voted_for_rejection(multisig_account: address, sequence_number: u64, owner: address): bool acquires MultisigAccount { + let (voted, vote) = vote(multisig_account, sequence_number, owner); + voted && !vote + } + + inline fun assert_multisig_account_exists(multisig_account: address) { + assert!(exists(multisig_account), error::invalid_state(EACCOUNT_NOT_MULTISIG)); + } + + inline fun assert_valid_sequence_number(multisig_account: address, sequence_number: u64) acquires MultisigAccount { + let multisig_account_resource = borrow_global(multisig_account); + assert!( + sequence_number > 0 && sequence_number < multisig_account_resource.next_sequence_number, + error::invalid_argument(EINVALID_SEQUENCE_NUMBER), + ); + } + + inline fun assert_transaction_exists(multisig_account: address, sequence_number: u64) acquires MultisigAccount { + let multisig_account_resource = borrow_global(multisig_account); + assert!( + table::contains(&multisig_account_resource.transactions, sequence_number), + error::not_found(ETRANSACTION_NOT_FOUND), + ); + } + + /// Add new owners, remove owners to remove, update signatures required. + fun update_owner_schema( + multisig_address: address, + new_owners: vector
, + owners_to_remove: vector
, + optional_new_num_signatures_required: Option, + ) acquires MultisigAccount { + assert_multisig_account_exists(multisig_address); + let multisig_account_ref_mut = + borrow_global_mut(multisig_address); + // Verify no overlap between new owners and owners to remove. + vector::for_each_ref(&new_owners, |new_owner_ref| { + assert!( + !vector::contains(&owners_to_remove, new_owner_ref), + error::invalid_argument(EOWNERS_TO_REMOVE_NEW_OWNERS_OVERLAP) + ) + }); + // If new owners provided, try to add them and emit an event. + if (vector::length(&new_owners) > 0) { + vector::append(&mut multisig_account_ref_mut.owners, new_owners); + validate_owners( + &multisig_account_ref_mut.owners, + multisig_address + ); + if (std::features::module_event_migration_enabled()) { + emit(AddOwners { multisig_account: multisig_address, owners_added: new_owners }); + }; + emit_event( + &mut multisig_account_ref_mut.add_owners_events, + AddOwnersEvent { owners_added: new_owners } + ); + }; + // If owners to remove provided, try to remove them. + if (vector::length(&owners_to_remove) > 0) { + let owners_ref_mut = &mut multisig_account_ref_mut.owners; + let owners_removed = vector[]; + vector::for_each_ref(&owners_to_remove, |owner_to_remove_ref| { + let (found, index) = + vector::index_of(owners_ref_mut, owner_to_remove_ref); + if (found) { + vector::push_back( + &mut owners_removed, + vector::swap_remove(owners_ref_mut, index) + ); + } + }); + // Only emit event if owner(s) actually removed. + if (vector::length(&owners_removed) > 0) { + if (std::features::module_event_migration_enabled()) { + emit( + RemoveOwners { multisig_account: multisig_address, owners_removed } + ); + }; + emit_event( + &mut multisig_account_ref_mut.remove_owners_events, + RemoveOwnersEvent { owners_removed } + ); + } + }; + // If new signature count provided, try to update count. + if (option::is_some(&optional_new_num_signatures_required)) { + let new_num_signatures_required = + option::extract(&mut optional_new_num_signatures_required); + assert!( + new_num_signatures_required > 0, + error::invalid_argument(EINVALID_SIGNATURES_REQUIRED) + ); + let old_num_signatures_required = + multisig_account_ref_mut.num_signatures_required; + // Only apply update and emit event if a change indicated. + if (new_num_signatures_required != old_num_signatures_required) { + multisig_account_ref_mut.num_signatures_required = + new_num_signatures_required; + if (std::features::module_event_migration_enabled()) { + emit( + UpdateSignaturesRequired { + multisig_account: multisig_address, + old_num_signatures_required, + new_num_signatures_required, + } + ); + }; + emit_event( + &mut multisig_account_ref_mut.update_signature_required_events, + UpdateSignaturesRequiredEvent { + old_num_signatures_required, + new_num_signatures_required, + } + ); + } + }; + // Verify number of owners. + let num_owners = vector::length(&multisig_account_ref_mut.owners); + assert!( + num_owners >= multisig_account_ref_mut.num_signatures_required, + error::invalid_state(ENOT_ENOUGH_OWNERS) + ); + } + + ////////////////////////// Tests /////////////////////////////// + + #[test_only] + use aptos_framework::aptos_account::create_account; + #[test_only] + use aptos_framework::timestamp; + #[test_only] + use aptos_std::from_bcs; + #[test_only] + use aptos_std::multi_ed25519; + #[test_only] + use std::string::utf8; + use std::features; + #[test_only] + use aptos_framework::aptos_coin; + #[test_only] + use aptos_framework::coin::{destroy_mint_cap, destroy_burn_cap}; + + #[test_only] + const PAYLOAD: vector = vector[1, 2, 3]; + #[test_only] + const ERROR_TYPE: vector = b"MoveAbort"; + #[test_only] + const ABORT_LOCATION: vector = b"abort_location"; + #[test_only] + const ERROR_CODE: u64 = 10; + + #[test_only] + fun execution_error(): ExecutionError { + ExecutionError { + abort_location: utf8(ABORT_LOCATION), + error_type: utf8(ERROR_TYPE), + error_code: ERROR_CODE, + } + } + + #[test_only] + fun setup() { + let framework_signer = &create_signer(@0x1); + features::change_feature_flags_for_testing( + framework_signer, vector[features::get_multisig_accounts_feature(), features::get_multisig_v2_enhancement_feature(), features::get_abort_if_multisig_payload_mismatch_feature()], vector[]); + timestamp::set_time_has_started_for_testing(framework_signer); + chain_id::initialize_for_test(framework_signer, 1); + let (burn, mint) = aptos_coin::initialize_for_test(framework_signer); + destroy_mint_cap(mint); + destroy_burn_cap(burn); + } + + #[test_only] + fun setup_disabled() { + let framework_signer = &create_signer(@0x1); + features::change_feature_flags_for_testing( + framework_signer, vector[], vector[features::get_multisig_accounts_feature()]); + timestamp::set_time_has_started_for_testing(framework_signer); + chain_id::initialize_for_test(framework_signer, 1); + let (burn, mint) = aptos_coin::initialize_for_test(framework_signer); + destroy_mint_cap(mint); + destroy_burn_cap(burn); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_end_to_end( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + // Create three transactions. + create_transaction(owner_1, multisig_account, PAYLOAD); + create_transaction(owner_2, multisig_account, PAYLOAD); + create_transaction_with_hash(owner_3, multisig_account, sha3_256(PAYLOAD)); + assert!(get_pending_transactions(multisig_account) == vector[ + get_transaction(multisig_account, 1), + get_transaction(multisig_account, 2), + get_transaction(multisig_account, 3), + ], 0); + + // Owner 3 doesn't need to explicitly approve as they created the transaction. + approve_transaction(owner_1, multisig_account, 3); + // Third transaction has 2 approvals but cannot be executed out-of-order. + assert!(!can_be_executed(multisig_account, 3), 0); + + // Owner 1 doesn't need to explicitly approve as they created the transaction. + approve_transaction(owner_2, multisig_account, 1); + // First transaction has 2 approvals so it can be executed. + assert!(can_be_executed(multisig_account, 1), 1); + // First transaction was executed successfully. + successful_transaction_execution_cleanup(owner_2_addr, multisig_account, vector[]); + assert!(get_pending_transactions(multisig_account) == vector[ + get_transaction(multisig_account, 2), + get_transaction(multisig_account, 3), + ], 0); + + reject_transaction(owner_1, multisig_account, 2); + reject_transaction(owner_3, multisig_account, 2); + // Second transaction has 1 approval (owner 3) and 2 rejections (owners 1 & 2) and thus can be removed. + assert!(can_be_rejected(multisig_account, 2), 2); + execute_rejected_transaction(owner_1, multisig_account); + assert!(get_pending_transactions(multisig_account) == vector[ + get_transaction(multisig_account, 3), + ], 0); + + // Third transaction can be executed now but execution fails. + failed_transaction_execution_cleanup(owner_3_addr, multisig_account, PAYLOAD, execution_error()); + assert!(get_pending_transactions(multisig_account) == vector[], 0); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_end_to_end_with_implicit_votes( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + // Create three transactions. + create_transaction(owner_1, multisig_account, PAYLOAD); + create_transaction(owner_2, multisig_account, PAYLOAD); + assert!(get_pending_transactions(multisig_account) == vector[ + get_transaction(multisig_account, 1), + get_transaction(multisig_account, 2), + ], 0); + + reject_transaction(owner_2, multisig_account, 1); + // Owner 2 can execute the transaction, implicitly voting to approve it, + // which overrides their previous vote for rejection. + assert!(can_execute(owner_2_addr, multisig_account, 1), 1); + // First transaction was executed successfully. + successful_transaction_execution_cleanup(owner_2_addr, multisig_account,vector[]); + assert!(get_pending_transactions(multisig_account) == vector[ + get_transaction(multisig_account, 2), + ], 0); + + reject_transaction(owner_1, multisig_account, 2); + // Owner 3 can execute-reject the transaction, implicitly voting to reject it. + assert!(can_reject(owner_3_addr, multisig_account, 2), 2); + execute_rejected_transaction(owner_3, multisig_account); + assert!(get_pending_transactions(multisig_account) == vector[], 0); + } + + #[test(owner = @0x123)] + public entry fun test_create_with_single_owner(owner: &signer) acquires MultisigAccount { + setup(); + let owner_addr = address_of(owner); + create_account(owner_addr); + create(owner, 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(owner_addr); + assert_multisig_account_exists(multisig_account); + assert!(owners(multisig_account) == vector[owner_addr], 0); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_create_with_as_many_sigs_required_as_num_owners( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + create_account(owner_1_addr); + create_with_owners(owner_1, vector[address_of(owner_2), address_of(owner_3)], 3, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + assert_multisig_account_exists(multisig_account); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x1000B, location = Self)] + public entry fun test_create_with_zero_signatures_required_should_fail( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner, 0, vector[], vector[]); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x1000B, location = Self)] + public entry fun test_create_with_too_many_signatures_required_should_fail( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner, 2, vector[], vector[]); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + #[expected_failure(abort_code = 0x10001, location = Self)] + public entry fun test_create_with_duplicate_owners_should_fail( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner_1)); + create_with_owners( + owner_1, + vector[ + // Duplicate owner 2 addresses. + address_of(owner_2), + address_of(owner_3), + address_of(owner_2), + ], + 2, + vector[], + vector[]); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0xD000E, location = Self)] + public entry fun test_create_with_without_feature_flag_enabled_should_fail( + owner: &signer) acquires MultisigAccount { + setup_disabled(); + create_account(address_of(owner)); + create(owner, 2, vector[], vector[]); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + #[expected_failure(abort_code = 0x10001, location = Self)] + public entry fun test_create_with_creator_in_additional_owners_list_should_fail( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner_1)); + create_with_owners(owner_1, vector[ + // Duplicate owner 1 addresses. + address_of(owner_1), + address_of(owner_2), + address_of(owner_3), + ], 2, + vector[], + vector[], + ); + } + + #[test] + public entry fun test_create_multisig_account_on_top_of_existing_multi_ed25519_account() + acquires MultisigAccount { + setup(); + let (curr_sk, curr_pk) = multi_ed25519::generate_keys(2, 3); + let pk_unvalidated = multi_ed25519::public_key_to_unvalidated(&curr_pk); + let auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&pk_unvalidated); + let multisig_address = from_bcs::to_address(auth_key); + create_account(multisig_address); + + let expected_owners = vector[@0x123, @0x124, @0x125]; + let proof = MultisigAccountCreationMessage { + chain_id: chain_id::get(), + account_address: multisig_address, + sequence_number: account::get_sequence_number(multisig_address), + owners: expected_owners, + num_signatures_required: 2, + }; + let signed_proof = multi_ed25519::sign_struct(&curr_sk, proof); + create_with_existing_account( + multisig_address, + expected_owners, + 2, + 1, // MULTI_ED25519_SCHEME + multi_ed25519::unvalidated_public_key_to_bytes(&pk_unvalidated), + multi_ed25519::signature_to_bytes(&signed_proof), + vector[], + vector[], + ); + assert_multisig_account_exists(multisig_address); + assert!(owners(multisig_address) == expected_owners, 0); + } + + #[test] + public entry fun test_create_multisig_account_on_top_of_existing_multi_ed25519_account_and_revoke_auth_key() + acquires MultisigAccount { + setup(); + let (curr_sk, curr_pk) = multi_ed25519::generate_keys(2, 3); + let pk_unvalidated = multi_ed25519::public_key_to_unvalidated(&curr_pk); + let auth_key = multi_ed25519::unvalidated_public_key_to_authentication_key(&pk_unvalidated); + let multisig_address = from_bcs::to_address(auth_key); + create_account(multisig_address); + + // Create both a signer capability and rotation capability offers + account::set_rotation_capability_offer(multisig_address, @0x123); + account::set_signer_capability_offer(multisig_address, @0x123); + + let expected_owners = vector[@0x123, @0x124, @0x125]; + let proof = MultisigAccountCreationWithAuthKeyRevocationMessage { + chain_id: chain_id::get(), + account_address: multisig_address, + sequence_number: account::get_sequence_number(multisig_address), + owners: expected_owners, + num_signatures_required: 2, + }; + let signed_proof = multi_ed25519::sign_struct(&curr_sk, proof); + create_with_existing_account_and_revoke_auth_key( + multisig_address, + expected_owners, + 2, + 1, // MULTI_ED25519_SCHEME + multi_ed25519::unvalidated_public_key_to_bytes(&pk_unvalidated), + multi_ed25519::signature_to_bytes(&signed_proof), + vector[], + vector[], + ); + assert_multisig_account_exists(multisig_address); + assert!(owners(multisig_address) == expected_owners, 0); + assert!(account::get_authentication_key(multisig_address) == ZERO_AUTH_KEY, 1); + // Verify that all capability offers have been wiped. + assert!(!account::is_rotation_capability_offered(multisig_address), 2); + assert!(!account::is_signer_capability_offered(multisig_address), 3); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_update_signatures_required( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + create_account(owner_1_addr); + create_with_owners(owner_1, vector[address_of(owner_2), address_of(owner_3)], 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + assert!(num_signatures_required(multisig_account) == 1, 0); + update_signatures_required(&create_signer(multisig_account), 2); + assert!(num_signatures_required(multisig_account) == 2, 1); + // As many signatures required as number of owners (3). + update_signatures_required(&create_signer(multisig_account), 3); + assert!(num_signatures_required(multisig_account) == 3, 2); + } + + #[test(owner = @0x123)] + public entry fun test_update_metadata(owner: &signer) acquires MultisigAccount { + setup(); + let owner_addr = address_of(owner); + create_account(owner_addr); + create(owner, 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(owner_addr); + update_metadata( + &create_signer(multisig_account), + vector[utf8(b"key1"), utf8(b"key2")], + vector[vector[1], vector[2]], + ); + let updated_metadata = metadata(multisig_account); + assert!(simple_map::length(&updated_metadata) == 2, 0); + assert!(simple_map::borrow(&updated_metadata, &utf8(b"key1")) == &vector[1], 0); + assert!(simple_map::borrow(&updated_metadata, &utf8(b"key2")) == &vector[2], 0); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x1000B, location = Self)] + public entry fun test_update_with_zero_signatures_required_should_fail( + owner: & signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner, 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + update_signatures_required(&create_signer(multisig_account), 0); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x30005, location = Self)] + public entry fun test_update_with_too_many_signatures_required_should_fail( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner, 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + update_signatures_required(&create_signer(multisig_account), 2); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_add_owners( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner_1)); + create(owner_1, 1, vector[], vector[]); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + let multisig_signer = &create_signer(multisig_account); + assert!(owners(multisig_account) == vector[owner_1_addr], 0); + // Adding an empty vector of new owners should be no-op. + add_owners(multisig_signer, vector[]); + assert!(owners(multisig_account) == vector[owner_1_addr], 1); + add_owners(multisig_signer, vector[owner_2_addr, owner_3_addr]); + assert!(owners(multisig_account) == vector[owner_1_addr, owner_2_addr, owner_3_addr], 2); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_remove_owners( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + let multisig_signer = &create_signer(multisig_account); + assert!(owners(multisig_account) == vector[owner_2_addr, owner_3_addr, owner_1_addr], 0); + // Removing an empty vector of owners should be no-op. + remove_owners(multisig_signer, vector[]); + assert!(owners(multisig_account) == vector[owner_2_addr, owner_3_addr, owner_1_addr], 1); + remove_owners(multisig_signer, vector[owner_2_addr]); + assert!(owners(multisig_account) == vector[owner_1_addr, owner_3_addr], 2); + // Removing owners that don't exist should be no-op. + remove_owners(multisig_signer, vector[@0x130]); + assert!(owners(multisig_account) == vector[owner_1_addr, owner_3_addr], 3); + // Removing with duplicate owners should still work. + remove_owners(multisig_signer, vector[owner_3_addr, owner_3_addr, owner_3_addr]); + assert!(owners(multisig_account) == vector[owner_1_addr], 4); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + #[expected_failure(abort_code = 0x30005, location = Self)] + public entry fun test_remove_all_owners_should_fail( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + assert!(owners(multisig_account) == vector[owner_2_addr, owner_3_addr, owner_1_addr], 0); + let multisig_signer = &create_signer(multisig_account); + remove_owners(multisig_signer, vector[owner_1_addr, owner_2_addr, owner_3_addr]); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + #[expected_failure(abort_code = 0x30005, location = Self)] + public entry fun test_remove_owners_with_fewer_remaining_than_signature_threshold_should_fail( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + let multisig_signer = &create_signer(multisig_account); + // Remove 2 owners so there's one left, which is less than the signature threshold of 2. + remove_owners(multisig_signer, vector[owner_2_addr, owner_3_addr]); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_create_transaction( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction(owner_1, multisig_account, PAYLOAD); + let transaction = get_transaction(multisig_account, 1); + assert!(transaction.creator == owner_1_addr, 0); + assert!(option::is_some(&transaction.payload), 1); + assert!(option::is_none(&transaction.payload_hash), 2); + let payload = option::extract(&mut transaction.payload); + assert!(payload == PAYLOAD, 4); + // Automatic yes vote from creator. + assert!(simple_map::length(&transaction.votes) == 1, 5); + assert!(*simple_map::borrow(&transaction.votes, &owner_1_addr), 5); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x10004, location = Self)] + public entry fun test_create_transaction_with_empty_payload_should_fail( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner, 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create_transaction(owner, multisig_account, vector[]); + } + + #[test(owner = @0x123, non_owner = @0x124)] + #[expected_failure(abort_code = 0x507D3, location = Self)] + public entry fun test_create_transaction_with_non_owner_should_fail( + owner: &signer, non_owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner, 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create_transaction(non_owner, multisig_account, PAYLOAD); + } + + #[test(owner = @0x123)] + public entry fun test_create_transaction_with_hashes( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner, 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create_transaction_with_hash(owner, multisig_account, sha3_256(PAYLOAD)); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x1000C, location = Self)] + public entry fun test_create_transaction_with_empty_hash_should_fail( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner, 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create_transaction_with_hash(owner, multisig_account, vector[]); + } + + #[test(owner = @0x123, non_owner = @0x124)] + #[expected_failure(abort_code = 0x507D3, location = Self)] + public entry fun test_create_transaction_with_hashes_and_non_owner_should_fail( + owner: &signer, non_owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + create(owner, 1, vector[], vector[]); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create_transaction_with_hash(non_owner, multisig_account, sha3_256(PAYLOAD)); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_approve_transaction( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction(owner_1, multisig_account, PAYLOAD); + approve_transaction(owner_2, multisig_account, 1); + approve_transaction(owner_3, multisig_account, 1); + let transaction = get_transaction(multisig_account, 1); + assert!(simple_map::length(&transaction.votes) == 3, 0); + assert!(*simple_map::borrow(&transaction.votes, &owner_1_addr), 1); + assert!(*simple_map::borrow(&transaction.votes, &owner_2_addr), 2); + assert!(*simple_map::borrow(&transaction.votes, &owner_3_addr), 3); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_validate_transaction_should_not_consider_removed_owners( + owner_1: &signer, owner_2: &signer, owner_3: & signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + // Owner 1 and 2 approved but then owner 1 got removed. + create_transaction(owner_1, multisig_account, PAYLOAD); + approve_transaction(owner_2, multisig_account, 1); + // Before owner 1 is removed, the transaction technically has sufficient approvals. + assert!(can_be_executed(multisig_account, 1), 0); + let multisig_signer = &create_signer(multisig_account); + remove_owners(multisig_signer, vector[owner_1_addr]); + // Now that owner 1 is removed, their approval should be invalidated and the transaction no longer + // has enough approvals to be executed. + assert!(!can_be_executed(multisig_account, 1), 1); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x607D6, location = Self)] + public entry fun test_approve_transaction_with_invalid_sequence_number_should_fail( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + // Transaction is created with id 1. + create_transaction(owner, multisig_account, PAYLOAD); + approve_transaction(owner, multisig_account, 2); + } + + #[test(owner = @0x123, non_owner = @0x124)] + #[expected_failure(abort_code = 0x507D3, location = Self)] + public entry fun test_approve_transaction_with_non_owner_should_fail( + owner: &signer, non_owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + // Transaction is created with id 1. + create_transaction(owner, multisig_account, PAYLOAD); + approve_transaction(non_owner, multisig_account, 1); + } + + #[test(owner = @0x123)] + public entry fun test_approval_transaction_after_rejecting( + owner: &signer) acquires MultisigAccount { + setup(); + let owner_addr = address_of(owner); + create_account(owner_addr); + let multisig_account = get_next_multisig_account_address(owner_addr); + create(owner, 1, vector[], vector[]); + + create_transaction(owner, multisig_account, PAYLOAD); + reject_transaction(owner, multisig_account, 1); + approve_transaction(owner, multisig_account, 1); + let transaction = get_transaction(multisig_account, 1); + assert!(*simple_map::borrow(&transaction.votes, &owner_addr), 1); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_reject_transaction( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction(owner_1, multisig_account, PAYLOAD); + reject_transaction(owner_1, multisig_account, 1); + reject_transaction(owner_2, multisig_account, 1); + reject_transaction(owner_3, multisig_account, 1); + let transaction = get_transaction(multisig_account, 1); + assert!(simple_map::length(&transaction.votes) == 3, 0); + assert!(!*simple_map::borrow(&transaction.votes, &owner_1_addr), 1); + assert!(!*simple_map::borrow(&transaction.votes, &owner_2_addr), 2); + assert!(!*simple_map::borrow(&transaction.votes, &owner_3_addr), 3); + } + + #[test(owner = @0x123)] + public entry fun test_reject_transaction_after_approving( + owner: &signer) acquires MultisigAccount { + setup(); + let owner_addr = address_of(owner); + create_account(owner_addr); + let multisig_account = get_next_multisig_account_address(owner_addr); + create(owner, 1, vector[], vector[]); + + create_transaction(owner, multisig_account, PAYLOAD); + reject_transaction(owner, multisig_account, 1); + let transaction = get_transaction(multisig_account, 1); + assert!(!*simple_map::borrow(&transaction.votes, &owner_addr), 1); + } + + #[test(owner = @0x123)] + #[expected_failure(abort_code = 0x607D6, location = Self)] + public entry fun test_reject_transaction_with_invalid_sequence_number_should_fail( + owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + // Transaction is created with id 1. + create_transaction(owner, multisig_account, PAYLOAD); + reject_transaction(owner, multisig_account, 2); + } + + #[test(owner = @0x123, non_owner = @0x124)] + #[expected_failure(abort_code = 0x507D3, location = Self)] + public entry fun test_reject_transaction_with_non_owner_should_fail( + owner: &signer, non_owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + reject_transaction(non_owner, multisig_account, 1); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_execute_transaction_successful( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction(owner_1, multisig_account, PAYLOAD); + // Owner 1 doesn't need to explicitly approve as they created the transaction. + approve_transaction(owner_2, multisig_account, 1); + assert!(can_be_executed(multisig_account, 1), 1); + assert!(table::contains(&borrow_global(multisig_account).transactions, 1), 0); + successful_transaction_execution_cleanup(owner_3_addr, multisig_account, vector[]); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_execute_transaction_failed( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction(owner_1, multisig_account, PAYLOAD); + // Owner 1 doesn't need to explicitly approve as they created the transaction. + approve_transaction(owner_2, multisig_account, 1); + assert!(can_be_executed(multisig_account, 1), 1); + assert!(table::contains(&borrow_global(multisig_account).transactions, 1), 0); + failed_transaction_execution_cleanup(owner_3_addr, multisig_account, vector[], execution_error()); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_execute_transaction_with_full_payload( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction_with_hash(owner_3, multisig_account, sha3_256(PAYLOAD)); + // Owner 3 doesn't need to explicitly approve as they created the transaction. + approve_transaction(owner_1, multisig_account, 1); + assert!(can_be_executed(multisig_account, 1), 1); + assert!(table::contains(&borrow_global(multisig_account).transactions, 1), 0); + successful_transaction_execution_cleanup(owner_3_addr, multisig_account, PAYLOAD); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + public entry fun test_execute_rejected_transaction( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction(owner_1, multisig_account, PAYLOAD); + reject_transaction(owner_2, multisig_account, 1); + reject_transaction(owner_3, multisig_account, 1); + assert!(can_be_rejected(multisig_account, 1), 1); + assert!(table::contains(&borrow_global(multisig_account).transactions, 1), 0); + execute_rejected_transaction(owner_3, multisig_account); + } + + #[test(owner = @0x123, non_owner = @0x124)] + #[expected_failure(abort_code = 0x507D3, location = Self)] + public entry fun test_execute_rejected_transaction_with_non_owner_should_fail( + owner: &signer, non_owner: &signer) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + + create_transaction(owner, multisig_account, PAYLOAD); + reject_transaction(owner, multisig_account, 1); + execute_rejected_transaction(non_owner, multisig_account); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + #[expected_failure(abort_code = 0x3000A, location = Self)] + public entry fun test_execute_rejected_transaction_without_sufficient_rejections_should_fail( + owner_1: &signer, owner_2: &signer, owner_3: &signer) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_account = get_next_multisig_account_address(owner_1_addr); + create_with_owners(owner_1, vector[owner_2_addr, owner_3_addr], 2, vector[], vector[]); + + create_transaction(owner_1, multisig_account, PAYLOAD); + approve_transaction(owner_2, multisig_account, 1); + execute_rejected_transaction(owner_3, multisig_account); + } + + #[test( + owner_1 = @0x123, + owner_2 = @0x124, + owner_3 = @0x125 + )] + #[expected_failure(abort_code = 0x10012, location = Self)] + fun test_update_owner_schema_overlap_should_fail( + owner_1: &signer, + owner_2: &signer, + owner_3: &signer + ) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_address = get_next_multisig_account_address(owner_1_addr); + create_with_owners( + owner_1, + vector[owner_2_addr, owner_3_addr], + 2, + vector[], + vector[] + ); + update_owner_schema( + multisig_address, + vector[owner_1_addr], + vector[owner_1_addr], + option::none() + ); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + #[expected_failure(abort_code = 196627, location = Self)] + fun test_max_pending_transaction_limit_should_fail( + owner_1: &signer, + owner_2: &signer, + owner_3: &signer + ) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_address = get_next_multisig_account_address(owner_1_addr); + create_with_owners( + owner_1, + vector[owner_2_addr, owner_3_addr], + 2, + vector[], + vector[] + ); + + let remaining_iterations = MAX_PENDING_TRANSACTIONS + 1; + while (remaining_iterations > 0) { + create_transaction(owner_1, multisig_address, PAYLOAD); + remaining_iterations = remaining_iterations - 1; + } + } + + #[test_only] + fun create_transaction_with_eviction( + owner: &signer, + multisig_account: address, + payload: vector, + ) acquires MultisigAccount { + while(available_transaction_queue_capacity(multisig_account) == 0) { + execute_rejected_transaction(owner, multisig_account) + }; + create_transaction(owner, multisig_account, payload); + } + + #[test_only] + fun vote_all_transactions( + owner: &signer, multisig_account: address, approved: bool) acquires MultisigAccount { + let starting_sequence_number = last_resolved_sequence_number(multisig_account) + 1; + let final_sequence_number = next_sequence_number(multisig_account) - 1; + vote_transactions(owner, multisig_account, starting_sequence_number, final_sequence_number, approved); + } + + #[test(owner_1 = @0x123, owner_2 = @0x124, owner_3 = @0x125)] + fun test_dos_mitigation_end_to_end( + owner_1: &signer, + owner_2: &signer, + owner_3: &signer + ) acquires MultisigAccount { + setup(); + let owner_1_addr = address_of(owner_1); + let owner_2_addr = address_of(owner_2); + let owner_3_addr = address_of(owner_3); + create_account(owner_1_addr); + let multisig_address = get_next_multisig_account_address(owner_1_addr); + create_with_owners( + owner_1, + vector[owner_2_addr, owner_3_addr], + 2, + vector[], + vector[] + ); + + // owner_3 is compromised and creates a bunch of bogus transactions. + let remaining_iterations = MAX_PENDING_TRANSACTIONS; + while (remaining_iterations > 0) { + create_transaction(owner_3, multisig_address, PAYLOAD); + remaining_iterations = remaining_iterations - 1; + }; + + // No one can create a transaction anymore because the transaction queue is full. + assert!(available_transaction_queue_capacity(multisig_address) == 0, 0); + + // owner_1 and owner_2 vote "no" on all transactions. + vote_all_transactions(owner_1, multisig_address, false); + vote_all_transactions(owner_2, multisig_address, false); + + // owner_1 evicts a transaction and creates a transaction to remove the compromised owner. + // Note that `PAYLOAD` is a placeholder and is not actually executed in this unit test. + create_transaction_with_eviction(owner_1, multisig_address, PAYLOAD); + + // owner_2 approves the eviction transaction. + approve_transaction(owner_2, multisig_address, 11); + + // owner_1 flushes the transaction queue except for the eviction transaction. + execute_rejected_transactions(owner_1, multisig_address, 10); + + // execute the eviction transaction to remove the compromised owner. + assert!(can_be_executed(multisig_address, 11), 0); + } + + #[test(owner = @0x123, non_owner = @0x234)] + #[expected_failure(abort_code = 329683, location = Self)] + public entry fun test_create_transaction_should_fail_if_not_owner( + owner: &signer, + non_owner: &signer + ) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + // Transaction is created with id 1. + create_transaction(non_owner, multisig_account, PAYLOAD); + } + + #[test(owner = @0x123, non_owner = @0x234)] + #[expected_failure(abort_code = 329683, location = Self)] + public entry fun test_create_transaction_with_hash_should_fail_if_not_owner( + owner: &signer, + non_owner: &signer + ) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + // Transaction is created with id 1. + create_transaction_with_hash(non_owner, multisig_account, sha3_256(PAYLOAD)); + } + + #[test(owner = @0x123, non_owner = @0x234)] + #[expected_failure(abort_code = 329683, location = Self)] + public entry fun test_reject_transaction_should_fail_if_not_owner( + owner: &signer, + non_owner: &signer + ) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + // Transaction is created with id 1. + create_transaction(owner, multisig_account, PAYLOAD); + reject_transaction(non_owner, multisig_account, 1); + } + + + #[test(owner = @0x123, non_owner = @0x234)] + #[expected_failure(abort_code = 329683, location = Self)] + public entry fun test_approve_transaction_should_fail_if_not_owner( + owner: &signer, + non_owner: &signer + ) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + // Transaction is created with id 1. + create_transaction(owner, multisig_account, PAYLOAD); + approve_transaction(non_owner, multisig_account, 1); + } + + #[test(owner = @0x123, non_owner = @0x234)] + #[expected_failure(abort_code = 329683, location = Self)] + public entry fun test_vote_transaction_should_fail_if_not_owner( + owner: &signer, + non_owner: &signer + ) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + // Transaction is created with id 1. + create_transaction(owner, multisig_account, PAYLOAD); + vote_transaction(non_owner, multisig_account, 1, true); + } + + #[test(owner = @0x123, non_owner = @0x234)] + #[expected_failure(abort_code = 329683, location = Self)] + public entry fun test_vote_transactions_should_fail_if_not_owner( + owner: &signer, + non_owner: &signer + ) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + // Transaction is created with id 1. + create_transaction(owner, multisig_account, PAYLOAD); + vote_transactions(non_owner, multisig_account, 1, 1, true); + } + + #[test(owner = @0x123, non_owner = @0x234)] + #[expected_failure(abort_code = 329683, location = Self)] + public entry fun test_execute_rejected_transaction_should_fail_if_not_owner( + owner: &signer, + non_owner: &signer + ) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + // Transaction is created with id 1. + create_transaction(owner, multisig_account, PAYLOAD); + reject_transaction(owner, multisig_account, 1); + execute_rejected_transaction(non_owner, multisig_account); + } + + + #[test(owner = @0x123, non_owner = @0x234)] + #[expected_failure(abort_code = 329683, location = Self)] + public entry fun test_execute_rejected_transactions_should_fail_if_not_owner( + owner: &signer, + non_owner: &signer + ) acquires MultisigAccount { + setup(); + create_account(address_of(owner)); + let multisig_account = get_next_multisig_account_address(address_of(owner)); + create(owner, 1, vector[], vector[]); + // Transaction is created with id 1. + create_transaction(owner, multisig_account, PAYLOAD); + reject_transaction(owner, multisig_account, 1); + execute_rejected_transactions(non_owner, multisig_account, 1); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/native_bridge.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/native_bridge.move new file mode 100644 index 000000000..401d34c48 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/native_bridge.move @@ -0,0 +1,1150 @@ +module aptos_framework::native_bridge { + + use std::features; + use aptos_std::smart_table::{Self, SmartTable}; + use aptos_framework::ethereum::{Self, EthereumAddress}; + use aptos_framework::account; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::signer; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + #[test_only] + use aptos_framework::aptos_account; + #[test_only] + use aptos_framework::ethereum::valid_eip55; + use std::bcs; + use std::vector; + use aptos_std::aptos_hash::keccak256; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::coin::{Self, BurnCapability, MintCapability}; + use aptos_framework::fungible_asset::{BurnRef, MintRef}; + #[test_only] + use aptos_framework::aptos_coin; + + const ETRANSFER_ALREADY_PROCESSED: u64 = 1; + const EINVALID_BRIDGE_TRANSFER_ID: u64 = 2; + const EEVENT_NOT_FOUND: u64 = 3; + const EINVALID_NONCE: u64 = 4; + const EINVALID_AMOUNT: u64 = 5; + const ENONCE_NOT_FOUND: u64 = 6; + const EZERO_AMOUNT: u64 = 7; + const ENATIVE_BRIDGE_NOT_ENABLED: u64 = 8; + const EINCORRECT_NONCE: u64 = 9; + const EID_NOT_FOUND: u64 = 10; + const EINVALID_BRIDGE_RELAYER: u64 = 11; + const ESAME_FEE: u64 = 0x2; + const EINVALID_VALUE: u64 = 0x3; + const ERATE_LIMIT_EXCEEDED: u64 = 0x4; + + friend aptos_framework::genesis; + + #[event] + /// Event emitted when the bridge relayer is updated. + struct BridgeConfigRelayerUpdated has store, drop { + old_relayer: address, + new_relayer: address, + } + + #[event] + /// An event triggered upon change of bridgefee + struct BridgeFeeChangedEvent has store, drop { + old_bridge_fee: u64, + new_bridge_fee: u64, + } + + #[event] + /// An event triggered upon change of insurance budget divider + struct BridgeInsuranceBudgetDividerChangedEvent has store, drop { + old_insurance_budget_divider: u64, + new_insurance_budget_divider: u64, + } + + #[event] + /// An event triggered upon change of insurance fund + struct BridgeInsuranceFundChangedEvent has store, drop { + old_insurance_fund: address, + new_insurance_fund: address, + } + + #[event] + /// An event triggered upon initiating a bridge transfer + struct BridgeTransferInitiatedEvent has store, drop { + bridge_transfer_id: vector, + initiator: address, + recipient: vector, + amount: u64, + nonce: u64, + } + + #[event] + /// An event triggered upon completing a bridge transfer + struct BridgeTransferCompletedEvent has store, drop { + bridge_transfer_id: vector, + initiator: vector, + recipient: address, + amount: u64, + nonce: u64, + } + + /// This struct will store the event handles for bridge events. + struct BridgeEvents has key, store { + bridge_transfer_initiated_events: EventHandle, + bridge_transfer_completed_events: EventHandle, + } + + struct AptosCoinBurnCapability has key { + burn_cap: BurnCapability, + } + + struct AptosCoinMintCapability has key { + mint_cap: MintCapability, + } + + struct AptosFABurnCapabilities has key { + burn_ref: BurnRef, + } + + struct AptosFAMintCapabilities has key { + burn_ref: MintRef, + } + + /// A nonce to ensure the uniqueness of bridge transfers + struct Nonce has key { + value: u64 + } + + struct OutboundRateLimitBudget has key, store { + day: SmartTable, + } + + struct InboundRateLimitBudget has key, store { + day: SmartTable, + } + + /// A smart table wrapper + struct SmartTableWrapper has key, store { + inner: SmartTable, + } + + /// Details on the outbound transfer + struct OutboundTransfer has store, copy { + bridge_transfer_id: vector, + initiator: address, + recipient: EthereumAddress, + amount: u64, + } + + struct BridgeConfig has key { + bridge_relayer: address, + insurance_fund: address, + insurance_budget_divider: u64, + bridge_fee: u64, + } + + /// Initializes the module and stores the `EventHandle`s in the resource. + public fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + + let bridge_config = BridgeConfig { + bridge_relayer: signer::address_of(aptos_framework), + insurance_fund: signer::address_of(aptos_framework), + insurance_budget_divider: 4, + bridge_fee: 40_000_000_000, + }; + move_to(aptos_framework, bridge_config); + + // Ensure the nonce is not already initialized + assert!( + !exists(signer::address_of(aptos_framework)), + 2 + ); + + // Create the Nonce resource with an initial value of 0 + move_to(aptos_framework, Nonce { + value: 0 + }); + + + move_to(aptos_framework, BridgeEvents { + bridge_transfer_initiated_events: account::new_event_handle(aptos_framework), + bridge_transfer_completed_events: account::new_event_handle(aptos_framework), + }); + system_addresses::assert_aptos_framework(aptos_framework); + + let outbound_rate_limit_budget = OutboundRateLimitBudget { + day: smart_table::new(), + }; + + move_to(aptos_framework, outbound_rate_limit_budget); + + + let inbound_rate_limit_budget = InboundRateLimitBudget { + day: smart_table::new(), + }; + + move_to(aptos_framework, inbound_rate_limit_budget); + + let nonces_to_details = SmartTableWrapper { + inner: smart_table::new(), + }; + + move_to(aptos_framework, nonces_to_details); + + let ids_to_inbound_nonces = SmartTableWrapper, u64> { + inner: smart_table::new(), + }; + + move_to(aptos_framework, ids_to_inbound_nonces); + } + + /// Converts a u64 to a 32-byte vector. + /// + /// @param value The u64 value to convert. + /// @return A 32-byte vector containing the u64 value in little-endian order. + /// + /// How BCS works: https://github.com/zefchain/bcs?tab=readme-ov-file#booleans-and-integers + /// + /// @example: a u64 value 0x12_34_56_78_ab_cd_ef_00 is converted to a 32-byte vector: + /// [0x00, 0x00, ..., 0x00, 0x12, 0x34, 0x56, 0x78, 0xab, 0xcd, 0xef, 0x00] + public(friend) fun normalize_u64_to_32_bytes(value: &u64): vector { + let r = bcs::to_bytes(&(*value as u256)); + // BCS returns the bytes in reverse order, so we reverse the result. + vector::reverse(&mut r); + r + } + + /// Checks if a bridge transfer ID is associated with an inbound nonce. + /// @param bridge_transfer_id The bridge transfer ID. + /// @return `true` if the ID is associated with an existing inbound nonce, `false` otherwise. + public(friend) fun is_inbound_nonce_set(bridge_transfer_id: vector): bool acquires SmartTableWrapper { + let table = borrow_global, u64>>(@aptos_framework); + smart_table::contains(&table.inner, bridge_transfer_id) + } + + /// Creates bridge transfer details with validation. + /// + /// @param initiator The initiating party of the transfer. + /// @param recipient The receiving party of the transfer. + /// @param amount The amount to be transferred. + /// @param nonce The unique nonce for the transfer. + /// @return A `BridgeTransferDetails` object. + /// @abort If the amount is zero or locks are invalid. + public(friend) fun create_details(initiator: address, recipient: EthereumAddress, amount: u64, nonce: u64) + : OutboundTransfer { + assert!(amount > 0, EZERO_AMOUNT); + + // Create a bridge transfer ID algorithmically + let combined_bytes = vector::empty(); + vector::append(&mut combined_bytes, bcs::to_bytes(&initiator)); + vector::append(&mut combined_bytes, bcs::to_bytes(&recipient)); + vector::append(&mut combined_bytes, bcs::to_bytes(&amount)); + vector::append(&mut combined_bytes, bcs::to_bytes(&nonce)); + let bridge_transfer_id = keccak256(combined_bytes); + + OutboundTransfer { + bridge_transfer_id, + initiator, + recipient, + amount, + } + } + + /// Record details of an initiated transfer for quick lookup of details, mapping bridge transfer ID to transfer details + /// + /// @param bridge_transfer_id Bridge transfer ID. + /// @param details The bridge transfer details + public(friend) fun add(nonce: u64, details: OutboundTransfer) acquires SmartTableWrapper { + assert!(features::abort_native_bridge_enabled(), ENATIVE_BRIDGE_NOT_ENABLED); + + let table = borrow_global_mut>(@aptos_framework); + smart_table::add(&mut table.inner, nonce, details); + } + + /// Record details of a completed transfer, mapping bridge transfer ID to inbound nonce + /// + /// @param bridge_transfer_id Bridge transfer ID. + /// @param details The bridge transfer details + public(friend) fun set_bridge_transfer_id_to_inbound_nonce(bridge_transfer_id: vector, inbound_nonce: u64) acquires SmartTableWrapper { + assert!(features::abort_native_bridge_enabled(), ENATIVE_BRIDGE_NOT_ENABLED); + + assert_valid_bridge_transfer_id(&bridge_transfer_id); + let table = borrow_global_mut, u64>>(@aptos_framework); + smart_table::add(&mut table.inner, bridge_transfer_id, inbound_nonce); + } + + /// Asserts that the bridge transfer ID is valid. + /// + /// @param bridge_transfer_id The bridge transfer ID to validate. + /// @abort If the ID is invalid. + public(friend) fun assert_valid_bridge_transfer_id(bridge_transfer_id: &vector) { + assert!(vector::length(bridge_transfer_id) == 32, EINVALID_BRIDGE_TRANSFER_ID); + } + + /// Generates a unique outbound bridge transfer ID based on transfer details and nonce. + /// + /// @param details The bridge transfer details. + /// @return The generated bridge transfer ID. + public(friend) fun bridge_transfer_id(initiator: address, recipient: EthereumAddress, amount: u64, nonce: u64) : vector { + // Serialize each param + let initiator_bytes = bcs::to_bytes
(&initiator); + let recipient_bytes = ethereum::get_inner_ethereum_address(recipient); + let amount_bytes = normalize_u64_to_32_bytes(&amount); + let nonce_bytes = normalize_u64_to_32_bytes(&nonce); + //Contatenate then hash and return bridge transfer ID + let combined_bytes = vector::empty(); + vector::append(&mut combined_bytes, initiator_bytes); + vector::append(&mut combined_bytes, recipient_bytes); + vector::append(&mut combined_bytes, amount_bytes); + vector::append(&mut combined_bytes, nonce_bytes); + keccak256(combined_bytes) + } + + #[view] + /// Retrieves the address of the current bridge relayer. + /// + /// @return The address of the current bridge relayer. + public fun bridge_relayer(): address acquires BridgeConfig { + borrow_global_mut(@aptos_framework).bridge_relayer + } + + #[view] + /// Retrieves the address of the current insurance fund. + /// + /// @return The address of the current insurance fund. + public fun insurance_fund(): address acquires BridgeConfig { + borrow_global_mut(@aptos_framework).insurance_fund + } + + #[view] + /// Retrieves the current insurance budget divider. + /// + /// @return The current insurance budget divider. + public fun insurance_budget_divider(): u64 acquires BridgeConfig { + borrow_global_mut(@aptos_framework).insurance_budget_divider + } + + #[view] + /// Retrieves the current bridge fee. + /// + /// @return The current bridge fee. + public fun bridge_fee(): u64 acquires BridgeConfig { + borrow_global_mut(@aptos_framework).bridge_fee + } + + #[view] + /// Gets the bridge transfer details (`OutboundTransfer`) from the given nonce. + /// @param nonce The nonce of the bridge transfer. + /// @return The `OutboundTransfer` struct containing the transfer details. + /// @abort If the nonce is not found in the smart table. + public fun get_bridge_transfer_details_from_nonce(nonce: u64): OutboundTransfer acquires SmartTableWrapper { + let table = borrow_global>(@aptos_framework); + + // Check if the nonce exists in the table + assert!(smart_table::contains(&table.inner, nonce), ENONCE_NOT_FOUND); + + // If it exists, return the associated `OutboundTransfer` details + *smart_table::borrow(&table.inner, nonce) + } + + #[view] + /// Gets inbound `nonce` from `bridge_transfer_id` + /// @param bridge_transfer_id The ID bridge transfer. + /// @return the nonce + /// @abort If the nonce is not found in the smart table. + public fun get_inbound_nonce_from_bridge_transfer_id(bridge_transfer_id: vector): u64 acquires SmartTableWrapper { + let table = borrow_global, u64>>(@aptos_framework); + + // Check if the nonce exists in the table + assert!(smart_table::contains(&table.inner, bridge_transfer_id), ENONCE_NOT_FOUND); + + // If it exists, return the associated nonce + *smart_table::borrow(&table.inner, bridge_transfer_id) + } + + /// Increment and get the current nonce + fun increment_and_get_nonce(): u64 acquires Nonce { + let nonce_ref = borrow_global_mut(@aptos_framework); + nonce_ref.value = nonce_ref.value + 1; + nonce_ref.value + } + + #[test_only] + /// Initializes the native bridge for testing purposes + /// + /// @param aptos_framework The signer representing the Aptos framework. + public fun initialize_for_test(aptos_framework: &signer) { + account::create_account_for_test(@aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_native_bridge_feature()], + vector[] + ); + initialize(aptos_framework); + + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(aptos_framework); + + store_aptos_coin_mint_cap(aptos_framework, mint_cap); + store_aptos_coin_burn_cap(aptos_framework, burn_cap); + } + + /// Stores the burn capability for AptosCoin, converting to a fungible asset reference if the feature is enabled. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param burn_cap The burn capability for AptosCoin. + public fun store_aptos_coin_burn_cap(aptos_framework: &signer, burn_cap: BurnCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + if (features::operations_default_to_fa_apt_store_enabled()) { + let burn_ref = coin::convert_and_take_paired_burn_ref(burn_cap); + move_to(aptos_framework, AptosFABurnCapabilities { burn_ref }); + } else { + move_to(aptos_framework, AptosCoinBurnCapability { burn_cap }) + } + } + + /// Stores the mint capability for AptosCoin. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param mint_cap The mint capability for AptosCoin. + public fun store_aptos_coin_mint_cap(aptos_framework: &signer, mint_cap: MintCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, AptosCoinMintCapability { mint_cap }) + } + + /// Mints a specified amount of AptosCoin to a recipient's address. + /// + /// @param core_resource The signer representing the core resource account. + /// @param recipient The address of the recipient to mint coins to. + /// @param amount The amount of AptosCoin to mint. + public fun mint_to(aptos_framework: &signer, recipient: address, amount: u64) acquires AptosCoinMintCapability { + system_addresses::assert_aptos_framework(aptos_framework); + mint_internal(recipient, amount); + } + + /// Mints a specified amount of AptosCoin to a recipient's address. + /// + /// @param recipient The address of the recipient to mint coins to. + /// @param amount The amount of AptosCoin to mint. + /// @abort If the mint capability is not available. + public(friend) fun mint(recipient: address, amount: u64) acquires AptosCoinMintCapability { + assert!(features::abort_native_bridge_enabled(), ENATIVE_BRIDGE_NOT_ENABLED); + + mint_internal(recipient, amount); + } + + /// Mints a specified amount of AptosCoin to a recipient's address. + /// + /// @param recipient The address of the recipient to mint coins to. + /// @param amount The amount of AptosCoin to mint. + fun mint_internal(recipient: address, amount: u64) acquires AptosCoinMintCapability { + coin::deposit(recipient, coin::mint( + amount, + &borrow_global(@aptos_framework).mint_cap + )); + } + + /// Burns a specified amount of AptosCoin from an address. + /// + /// @param core_resource The signer representing the core resource account. + /// @param from The address from which to burn AptosCoin. + /// @param amount The amount of AptosCoin to burn. + /// @abort If the burn capability is not available. + public fun burn_from(aptos_framework: &signer, from: address, amount: u64) acquires AptosCoinBurnCapability { + system_addresses::assert_aptos_framework(aptos_framework); + burn_internal(from, amount); + } + + /// Burns a specified amount of AptosCoin from an address. + /// + /// @param from The address from which to burn AptosCoin. + /// @param amount The amount of AptosCoin to burn. + /// @abort If the burn capability is not available. + public(friend) fun burn(from: address, amount: u64) acquires AptosCoinBurnCapability { + assert!(features::abort_native_bridge_enabled(), ENATIVE_BRIDGE_NOT_ENABLED); + + burn_internal(from, amount); + } + + /// Burns a specified amount of AptosCoin from an address. + /// + /// @param from The address from which to burn AptosCoin. + /// @param amount The amount of AptosCoin to burn. + fun burn_internal(from: address, amount: u64) acquires AptosCoinBurnCapability { + coin::burn_from( + from, + amount, + &borrow_global(@aptos_framework).burn_cap, + ); + } + + /// Initiate a bridge transfer of MOVE from Movement to Ethereum + /// Anyone can initiate a bridge transfer from the source chain + /// The amount is burnt from the initiator and the module-level nonce is incremented + /// @param initiator The initiator's Ethereum address as a vector of bytes. + /// @param recipient The address of the recipient on the Aptos blockchain. + /// @param amount The amount of assets to be locked. + public entry fun initiate_bridge_transfer( + initiator: &signer, + recipient: vector, + amount: u64 + ) acquires BridgeEvents, Nonce, AptosCoinBurnCapability, AptosCoinMintCapability, SmartTableWrapper, OutboundRateLimitBudget, BridgeConfig { + let initiator_address = signer::address_of(initiator); + let ethereum_address = ethereum::ethereum_address_20_bytes(recipient); + + // Ensure the amount is enough for the bridge fee and charge for it + let new_amount = charge_bridge_fee(amount); + + assert_outbound_rate_limit_budget_not_exceeded(new_amount); + + // Increment and retrieve the nonce + let nonce = increment_and_get_nonce(); + + // Create bridge transfer details + let details = create_details( + initiator_address, + ethereum_address, + new_amount, + nonce + ); + + let bridge_transfer_id = bridge_transfer_id( + initiator_address, + ethereum_address, + new_amount, + nonce + ); + + // Add the transfer details to storage + add(nonce, details); + + // Burn the amount from the initiator + burn_internal(initiator_address, amount); + + let bridge_events = borrow_global_mut(@aptos_framework); + + // Emit an event with nonce + event::emit_event( + &mut bridge_events.bridge_transfer_initiated_events, + BridgeTransferInitiatedEvent { + bridge_transfer_id, + initiator: initiator_address, + recipient, + amount: new_amount, + nonce, + } + ); + } + + /// Completes a bridge transfer on the destination chain. + /// + /// @param caller The signer representing the bridge relayer. + /// @param initiator The initiator's Ethereum address as a vector of bytes. + /// @param bridge_transfer_id The unique identifier for the bridge transfer. + /// @param recipient The address of the recipient on the Aptos blockchain. + /// @param amount The amount of assets to be locked. + /// @param nonce The unique nonce for the transfer. + /// @abort If the caller is not the bridge relayer or the transfer has already been processed. + public entry fun complete_bridge_transfer( + caller: &signer, + bridge_transfer_id: vector, + initiator: vector, + recipient: address, + amount: u64, + nonce: u64 + ) acquires BridgeEvents, AptosCoinMintCapability, SmartTableWrapper, InboundRateLimitBudget, BridgeConfig { + // Ensure the caller is the bridge relayer + assert_is_caller_relayer(caller); + assert_inbound_rate_limit_budget_not_exceeded(amount); + + // Check if the bridge transfer ID is already associated with an inbound nonce + let inbound_nonce_exists = is_inbound_nonce_set(bridge_transfer_id); + assert!(!inbound_nonce_exists, ETRANSFER_ALREADY_PROCESSED); + assert!(nonce > 0, EINVALID_NONCE); + + // Validate the bridge_transfer_id by reconstructing the hash + let recipient_bytes = bcs::to_bytes(&recipient); + let amount_bytes = normalize_u64_to_32_bytes(&amount); + let nonce_bytes = normalize_u64_to_32_bytes(&nonce); + + let combined_bytes = vector::empty(); + vector::append(&mut combined_bytes, initiator); + vector::append(&mut combined_bytes, recipient_bytes); + vector::append(&mut combined_bytes, amount_bytes); + vector::append(&mut combined_bytes, nonce_bytes); + + assert!(keccak256(combined_bytes) == bridge_transfer_id, EINVALID_BRIDGE_TRANSFER_ID); + + // Record the transfer as completed by associating the bridge_transfer_id with the inbound nonce + set_bridge_transfer_id_to_inbound_nonce(bridge_transfer_id, nonce); + + // Mint to the recipient + mint_internal(recipient, amount); + + // Emit the event + let bridge_events = borrow_global_mut(@aptos_framework); + event::emit_event( + &mut bridge_events.bridge_transfer_completed_events, + BridgeTransferCompletedEvent { + bridge_transfer_id, + initiator, + recipient, + amount, + nonce, + }, + ); + } + + /// Charge bridge fee to the initiate bridge transfer. + /// + /// @param initiator The signer representing the initiator. + /// @param amount The amount to be charged. + /// @return The new amount after deducting the bridge fee. + fun charge_bridge_fee(amount: u64) : u64 acquires AptosCoinMintCapability, BridgeConfig { + let bridge_fee = bridge_fee(); + let bridge_relayer = bridge_relayer(); + assert!(amount > bridge_fee, EINVALID_AMOUNT); + let new_amount = amount - bridge_fee; + mint_internal(bridge_relayer, bridge_fee); + new_amount + } + + /// Updates the bridge relayer, requiring governance validation. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param new_relayer The new address to be set as the bridge relayer. + /// @abort If the current relayer is the same as the new relayer. + public fun update_bridge_relayer(aptos_framework: &signer, new_relayer: address + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + let bridge_config = borrow_global_mut(@aptos_framework); + let old_relayer = bridge_config.bridge_relayer; + assert!(old_relayer != new_relayer, EINVALID_BRIDGE_RELAYER); + + bridge_config.bridge_relayer = new_relayer; + + event::emit( + BridgeConfigRelayerUpdated { + old_relayer, + new_relayer, + }, + ); + } + + /// Updates the bridge fee, requiring relayer validation. + /// + /// @param relayer The signer representing the Relayer. + /// @param new_bridge_fee The new bridge fee to be set. + /// @abort If the new bridge fee is the same as the old bridge fee. + public entry fun update_bridge_fee(relayer: &signer, new_bridge_fee: u64 + ) acquires BridgeConfig { + assert_is_caller_relayer(relayer); + let bridge_config = borrow_global_mut(@aptos_framework); + let old_bridge_fee = bridge_config.bridge_fee; + assert!(old_bridge_fee != new_bridge_fee, ESAME_FEE); + bridge_config.bridge_fee = new_bridge_fee; + + event::emit( + BridgeFeeChangedEvent { + old_bridge_fee, + new_bridge_fee, + }, + ); + } + + /// Updates the insurance fund, requiring governance validation. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param new_insurance_fund The new insurance fund to be set. + /// @abort If the new insurance fund is the same as the old insurance fund. + public entry fun update_insurance_fund(aptos_framework: &signer, new_insurance_fund: address + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + let bridge_config = borrow_global_mut(@aptos_framework); + let old_insurance_fund = bridge_config.insurance_fund; + assert!(old_insurance_fund != new_insurance_fund, EINVALID_VALUE); + bridge_config.insurance_fund = new_insurance_fund; + + event::emit( + BridgeInsuranceFundChangedEvent { + old_insurance_fund, + new_insurance_fund, + }, + ); + } + + /// Updates the insurance budget divider, requiring governance validation. + /// + /// @param aptos_framework The signer representing the Aptos framework. + /// @param new_insurance_budget_divider The new insurance budget divider to be set. + /// @abort If the new insurance budget divider is the same as the old insurance budget divider. + public entry fun update_insurance_budget_divider(aptos_framework: &signer, new_insurance_budget_divider: u64 + ) acquires BridgeConfig { + system_addresses::assert_aptos_framework(aptos_framework); + // Ensure the new insurance budget divider is greater than 1 and different from the old one + // Assumes symmetric Insurance Funds on both L1 and L2 + assert!(new_insurance_budget_divider > 1, EINVALID_VALUE); + + let bridge_config = borrow_global_mut(@aptos_framework); + let old_insurance_budget_divider = bridge_config.insurance_budget_divider; + assert!(old_insurance_budget_divider != new_insurance_budget_divider, EINVALID_VALUE); + + bridge_config.insurance_budget_divider = new_insurance_budget_divider; + + event::emit( + BridgeInsuranceBudgetDividerChangedEvent { + old_insurance_budget_divider, + new_insurance_budget_divider, + }, + ); + } + + /// Asserts that the caller is the current bridge relayer. + /// + /// @param caller The signer whose authority is being checked. + /// @abort If the caller is not the current bridge relayer. + public(friend) fun assert_is_caller_relayer(caller: &signer + ) acquires BridgeConfig { + assert!(borrow_global(@aptos_framework).bridge_relayer == signer::address_of(caller), EINVALID_BRIDGE_RELAYER); + } + + /// Asserts that the rate limit budget is not exceeded. + /// + /// @param amount The amount to be transferred. + fun assert_outbound_rate_limit_budget_not_exceeded(amount: u64) acquires OutboundRateLimitBudget, BridgeConfig { + let insurance_fund = borrow_global(@aptos_framework).insurance_fund; + let insurance_budget_divider = borrow_global(@aptos_framework).insurance_budget_divider; + let table = borrow_global_mut(@aptos_framework); + + let day = timestamp::now_seconds() / 86400; + let current_budget = smart_table::borrow_mut_with_default(&mut table.day, day, 0); + smart_table::upsert(&mut table.day, day, *current_budget + amount); + let rate_limit = coin::balance(insurance_fund) / insurance_budget_divider; + assert!(*smart_table::borrow(&table.day, day) < rate_limit, ERATE_LIMIT_EXCEEDED); + } + + /// Asserts that the rate limit budget is not exceeded. + /// + /// @param amount The amount to be transferred. + fun assert_inbound_rate_limit_budget_not_exceeded(amount: u64) acquires InboundRateLimitBudget, BridgeConfig { + let insurance_fund = borrow_global(@aptos_framework).insurance_fund; + let insurance_budget_divider = borrow_global(@aptos_framework).insurance_budget_divider; + let table = borrow_global_mut(@aptos_framework); + + let day = timestamp::now_seconds() / 86400; + let current_budget = smart_table::borrow_mut_with_default(&mut table.day, day, 0); + smart_table::upsert(&mut table.day, day, *current_budget + amount); + let rate_limit = coin::balance(insurance_fund) / insurance_budget_divider; + assert!(*smart_table::borrow(&table.day, day) < rate_limit, ERATE_LIMIT_EXCEEDED); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests initialization of the bridge configuration. + fun test_initialization(aptos_framework: &signer) { + initialize_for_test(aptos_framework); + assert!(exists(@aptos_framework), 0); + } + + #[test(aptos_framework = @aptos_framework, new_relayer = @0xcafe)] + /// Tests updating the bridge relayer and emitting the corresponding event. + fun test_update_bridge_relayer(aptos_framework: &signer, new_relayer: address + ) acquires BridgeConfig { + initialize_for_test(aptos_framework); + update_bridge_relayer(aptos_framework, new_relayer); + + assert!( + event::was_event_emitted( + &BridgeConfigRelayerUpdated { + old_relayer: @aptos_framework, + new_relayer, + } + ), 0); + + assert!(bridge_relayer() == new_relayer, 0); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests updating the insurance budget divider and emitting the corresponding event. + fun test_update_insurance_budget_divider(aptos_framework: &signer + ) acquires BridgeConfig { + initialize_for_test(aptos_framework); + let old_insurance_budget_divider = insurance_budget_divider(); + let new_insurance_budget_divider = 5; + update_insurance_budget_divider(aptos_framework, new_insurance_budget_divider); + + assert!( + event::was_event_emitted( + &BridgeInsuranceBudgetDividerChangedEvent { + old_insurance_budget_divider: old_insurance_budget_divider, + new_insurance_budget_divider: new_insurance_budget_divider, + } + ), 0); + + assert!(insurance_budget_divider() == new_insurance_budget_divider, 0); + } + + #[test(aptos_framework = @aptos_framework, new_insurance_fund = @0xdead)] + /// Tests updating the insurance fund and emitting the corresponding event. + fun test_update_insurance_fund(aptos_framework: &signer, new_insurance_fund: address + ) acquires BridgeConfig { + initialize_for_test(aptos_framework); + update_insurance_fund(aptos_framework, new_insurance_fund); + + assert!( + event::was_event_emitted( + &BridgeInsuranceFundChangedEvent { + old_insurance_fund: @aptos_framework, + new_insurance_fund: new_insurance_fund, + } + ), 0); + + assert!(insurance_fund() == new_insurance_fund, 0); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests updating the bridge relayer and emitting the corresponding event. + fun test_update_bridge_fee(aptos_framework: &signer + ) acquires BridgeConfig { + let new_fee = 100; + initialize_for_test(aptos_framework); + let old_bridge_fee = bridge_fee(); + update_bridge_fee(aptos_framework, new_fee); + + assert!( + event::was_event_emitted( + &BridgeFeeChangedEvent { + old_bridge_fee: old_bridge_fee, + new_bridge_fee: new_fee, + } + ), 0); + + assert!(bridge_fee() == new_fee, 0); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad, new_relayer = @0xcafe)] + #[expected_failure(abort_code = 0x50003, location = 0x1::system_addresses)] + /// Tests that updating the bridge relayer with an invalid signer fails. + fun test_failing_update_bridge_relayer(aptos_framework: &signer, bad: &signer, new_relayer: address + ) acquires BridgeConfig { + initialize_for_test(aptos_framework); + update_bridge_relayer(bad, new_relayer); + } + + #[test(aptos_framework = @aptos_framework)] + /// Tests that the correct relayer is validated successfully. + fun test_is_valid_relayer(aptos_framework: &signer) acquires BridgeConfig { + initialize_for_test(aptos_framework); + assert_is_caller_relayer(aptos_framework); + } + + #[test(aptos_framework = @aptos_framework, bad = @0xbad)] + #[expected_failure(abort_code = 11, location = Self)] + /// Tests that an incorrect relayer is not validated and results in an abort. + fun test_is_not_valid_relayer(aptos_framework: &signer, bad: &signer) acquires BridgeConfig { + initialize_for_test(aptos_framework); + assert_is_caller_relayer(bad); + } + + #[test(aptos_framework = @aptos_framework, relayer = @0xcafe, sender = @0x726563697069656e740000000000000000000000000000000000000000000000, insurance_fund = @0xbeaf)] + fun test_initiate_bridge_transfer_happy_path( + sender: &signer, + aptos_framework: &signer, + relayer: &signer, + insurance_fund: &signer + ) acquires BridgeEvents, Nonce, AptosCoinMintCapability, AptosCoinBurnCapability, SmartTableWrapper, OutboundRateLimitBudget, BridgeConfig { + let sender_address = signer::address_of(sender); + let relayer_address = signer::address_of(relayer); + initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + let amount = 1000; + let bridge_fee = 40; + update_bridge_fee(aptos_framework, bridge_fee); + let insurance_fund_address = signer::address_of(insurance_fund); + aptos_account::create_account(insurance_fund_address); + update_insurance_fund(aptos_framework, insurance_fund_address); + + // grant the insurance fund 4 * amount of coins + mint(insurance_fund_address, amount * 4 + 4); + + timestamp::set_time_has_started_for_testing(aptos_framework); + + + // Update the bridge relayer so it can receive the bridge fee + update_bridge_relayer(aptos_framework, relayer_address); + let bridge_relayer = bridge_relayer(); + aptos_account::create_account(bridge_relayer); + + // Mint coins to the sender to ensure they have sufficient balance + let account_balance = amount + 1; + // Mint some coins + mint_internal(sender_address, account_balance); + + // Specify the recipient and transfer amount + let recipient = ethereum::eth_address_20_bytes(); + + // Perform the bridge transfer + initiate_bridge_transfer( + sender, + recipient, + amount + ); + + let bridge_events = borrow_global(@aptos_framework); + let initiated_events = event::emitted_events_by_handle( + &bridge_events.bridge_transfer_initiated_events + ); + assert!(vector::length(&initiated_events) == 1, EEVENT_NOT_FOUND); + let first_elem = vector::borrow(&initiated_events, 0); + assert!(first_elem.amount == amount - bridge_fee, 0); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff, relayer = @0xcafe, insurance_fund = @0xbeaf)] + #[expected_failure(abort_code = 0x10006, location = 0x1::coin)] + fun test_initiate_bridge_transfer_insufficient_balance( + sender: &signer, + aptos_framework: &signer, + relayer: &signer, + insurance_fund: &signer + ) acquires BridgeEvents, Nonce, AptosCoinBurnCapability, AptosCoinMintCapability, SmartTableWrapper, OutboundRateLimitBudget, BridgeConfig { + let sender_address = signer::address_of(sender); + let relayer_address = signer::address_of(relayer); + let insurance_fund_address = signer::address_of(insurance_fund); + initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + + let recipient = ethereum::eth_address_20_bytes(); + let amount = 1000; + let bridge_fee = 40; + aptos_account::create_account(insurance_fund_address); + update_insurance_fund(aptos_framework, insurance_fund_address); + + + // grant the insurance fund 4 * amount of coins + mint(insurance_fund_address, amount * 4 + 4); + + timestamp::set_time_has_started_for_testing(aptos_framework); + update_bridge_fee(aptos_framework, bridge_fee); + + // Update the bridge relayer so it can receive the bridge fee + update_bridge_relayer(aptos_framework, relayer_address); + let bridge_relayer = bridge_relayer(); + aptos_account::create_account(bridge_relayer); + + initiate_bridge_transfer( + sender, + recipient, + amount + ); + } + + #[test(aptos_framework = @aptos_framework)] + fun test_complete_bridge_transfer(aptos_framework: &signer) acquires BridgeEvents, AptosCoinMintCapability, SmartTableWrapper, InboundRateLimitBudget, BridgeConfig { + initialize_for_test(aptos_framework); + let initiator = b"5B38Da6a701c568545dCfcB03FcB875f56beddC4"; + let recipient = @0x726563697069656e740000000000000000000000000000000000000000000000; + let insurance_fund = @0xbeaf; + let amount = 100; + let nonce = 1; + + // Create a bridge transfer ID algorithmically + let combined_bytes = vector::empty(); + vector::append(&mut combined_bytes, initiator); + vector::append(&mut combined_bytes, bcs::to_bytes(&recipient)); + vector::append(&mut combined_bytes, normalize_u64_to_32_bytes(&amount)); + vector::append(&mut combined_bytes, normalize_u64_to_32_bytes(&nonce)); + let bridge_transfer_id = keccak256(combined_bytes); + + aptos_account::create_account(insurance_fund); + update_insurance_fund(aptos_framework, insurance_fund); + + // grant the insurance fund 4 * amount of coins + mint(insurance_fund, amount * 4 + 4); + + // Create an account for our recipient + aptos_account::create_account(recipient); + timestamp::set_time_has_started_for_testing(aptos_framework); + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + initiator, + recipient, + amount, + nonce + ); + + let bridge_events = borrow_global(signer::address_of(aptos_framework)); + let complete_events = event::emitted_events_by_handle(&bridge_events.bridge_transfer_completed_events); + + // Assert that the event was emitted + let expected_event = BridgeTransferCompletedEvent { + bridge_transfer_id, + initiator, + recipient, + amount, + nonce, + }; + assert!(std::vector::contains(&complete_events, &expected_event), 0); + assert!(bridge_transfer_id == expected_event.bridge_transfer_id, 0) + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 4, location = Self)] + fun test_complete_bridge_transfer_rate_limit(aptos_framework: &signer) acquires BridgeEvents, AptosCoinMintCapability, SmartTableWrapper, InboundRateLimitBudget, BridgeConfig { + initialize_for_test(aptos_framework); + let initiator = b"5B38Da6a701c568545dCfcB03FcB875f56beddC4"; + let recipient = @0x726563697069656e740000000000000000000000000000000000000000000000; + let insurance_fund = @0xbeaf; + let day = 86400; + let amount = 100; + let nonce = 1; + + // Create a bridge transfer ID algorithmically + let combined_bytes = vector::empty(); + vector::append(&mut combined_bytes, initiator); + vector::append(&mut combined_bytes, bcs::to_bytes(&recipient)); + vector::append(&mut combined_bytes, normalize_u64_to_32_bytes(&amount)); + vector::append(&mut combined_bytes, normalize_u64_to_32_bytes(&nonce)); + let bridge_transfer_id = keccak256(combined_bytes); + + aptos_account::create_account(insurance_fund); + update_insurance_fund(aptos_framework, insurance_fund); + + // grant the insurance fund 4 * amount of coins + mint(insurance_fund, amount * 4 + 4); + + // Create an account for our recipient + aptos_account::create_account(recipient); + timestamp::set_time_has_started_for_testing(aptos_framework); + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + initiator, + recipient, + amount, + nonce + ); + + let bridge_events = borrow_global(signer::address_of(aptos_framework)); + let complete_events = event::emitted_events_by_handle(&bridge_events.bridge_transfer_completed_events); + + // Assert that the event was emitted + let expected_event = BridgeTransferCompletedEvent { + bridge_transfer_id, + initiator, + recipient, + amount, + nonce, + }; + assert!(std::vector::contains(&complete_events, &expected_event), 0); + assert!(bridge_transfer_id == expected_event.bridge_transfer_id, 0); + + // reset the rate limit + timestamp::fast_forward_seconds(day); + + nonce = nonce + 1; + let combined_bytes2 = vector::empty(); + vector::append(&mut combined_bytes2, initiator); + vector::append(&mut combined_bytes2, bcs::to_bytes(&recipient)); + vector::append(&mut combined_bytes2, normalize_u64_to_32_bytes(&amount)); + vector::append(&mut combined_bytes2, normalize_u64_to_32_bytes(&nonce)); + let bridge_transfer_id2 = keccak256(combined_bytes2); + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id2, + initiator, + recipient, + amount, + nonce + ); + + nonce = nonce + 1; + + let combined_bytes3 = vector::empty(); + vector::append(&mut combined_bytes3, initiator); + vector::append(&mut combined_bytes3, bcs::to_bytes(&recipient)); + vector::append(&mut combined_bytes3, normalize_u64_to_32_bytes(&amount)); + vector::append(&mut combined_bytes3, normalize_u64_to_32_bytes(&nonce)); + let bridge_transfer_id3 = keccak256(combined_bytes2); + // expect to fail as it reaches the rate limit + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id3, + initiator, + recipient, + amount, + nonce + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = 11, location = Self)] + fun test_complete_bridge_transfer_by_non_relayer( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeEvents, AptosCoinMintCapability, SmartTableWrapper, InboundRateLimitBudget, BridgeConfig { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + + let bridge_transfer_id = b"guessing the id"; + + // As relayer I send a complete request and it should fail + complete_bridge_transfer( + sender, + bridge_transfer_id, + valid_eip55(), + sender_address, + 1000, + 1 + ); + } + + #[test(aptos_framework = @aptos_framework, sender = @0xdaff)] + #[expected_failure(abort_code = EINVALID_BRIDGE_TRANSFER_ID, location = Self)] // ENOT_FOUND + fun test_complete_bridge_with_erroneous_bridge_id_by_relayer( + sender: &signer, + aptos_framework: &signer + ) acquires BridgeEvents, AptosCoinMintCapability, SmartTableWrapper, InboundRateLimitBudget, BridgeConfig { + let sender_address = signer::address_of(sender); + // Create an account for our recipient + initialize_for_test(aptos_framework); + aptos_account::create_account(sender_address); + let insurance_fund = @0xbeaf; + + let bridge_transfer_id = b"guessing the id"; + + aptos_account::create_account(insurance_fund); + update_insurance_fund(aptos_framework, insurance_fund); + + // grant the insurance fund 4 * amount of coins + mint(insurance_fund, 1000 * 4 + 4); + + timestamp::set_time_has_started_for_testing(aptos_framework); + // As relayer I send a complete request and it should fail + complete_bridge_transfer( + aptos_framework, + bridge_transfer_id, + valid_eip55(), + sender_address, + 1000, + 1 + ); + } + + #[test] + /// Test normalisation (serialization) of u64 to 32 bytes + fun test_normalize_u64_to_32_bytes() { + test_normalize_u64_to_32_bytes_helper(0x64, + vector[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0x64]); + test_normalize_u64_to_32_bytes_helper(0x6400, + vector[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0x64,0x00]); + test_normalize_u64_to_32_bytes_helper(0x00_32_00_00_64_00, + vector[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0x32,0,0,0x64,0x00]); + } + + /// Test serialization of u64 to 32 bytes + fun test_normalize_u64_to_32_bytes_helper(x: u64, expected: vector) { + let r = normalize_u64_to_32_bytes(&x); + assert!(vector::length(&r) == 32, 0); + assert!(r == expected, 0); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/object.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/object.move new file mode 100644 index 000000000..6e809e87e --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/object.move @@ -0,0 +1,1073 @@ +/// This defines the Move object model with the following properties: +/// - Simplified storage interface that supports a heterogeneous collection of resources to be +/// stored together. This enables data types to share a common core data layer (e.g., tokens), +/// while having richer extensions (e.g., concert ticket, sword). +/// - Globally accessible data and ownership model that enables creators and developers to dictate +/// the application and lifetime of data. +/// - Extensible programming model that supports individualization of user applications that +/// leverage the core framework including tokens. +/// - Support emitting events directly, thus improving discoverability of events associated with +/// objects. +/// - Considerate of the underlying system by leveraging resource groups for gas efficiency, +/// avoiding costly deserialization and serialization costs, and supporting deletability. +/// +/// TODO: +/// * There is no means to borrow an object or a reference to an object. We are exploring how to +/// make it so that a reference to a global object can be returned from a function. +module aptos_framework::object { + use std::bcs; + use std::error; + use std::hash; + use std::signer; + use std::vector; + + use aptos_std::from_bcs; + + use aptos_framework::account; + use aptos_framework::transaction_context; + use aptos_framework::create_signer::create_signer; + use aptos_framework::event; + use aptos_framework::guid; + + friend aptos_framework::coin; + friend aptos_framework::primary_fungible_store; + + /// An object already exists at this address + const EOBJECT_EXISTS: u64 = 1; + /// An object does not exist at this address + const EOBJECT_DOES_NOT_EXIST: u64 = 2; + /// The object does not have ungated transfers enabled + const ENO_UNGATED_TRANSFERS: u64 = 3; + /// The caller does not have ownership permissions + const ENOT_OBJECT_OWNER: u64 = 4; + /// The object does not allow for deletion + const ECANNOT_DELETE: u64 = 5; + /// Exceeds maximum nesting for an object transfer. + const EMAXIMUM_NESTING: u64 = 6; + /// The resource is not stored at the specified address. + const ERESOURCE_DOES_NOT_EXIST: u64 = 7; + /// Cannot reclaim objects that weren't burnt. + const EOBJECT_NOT_BURNT: u64 = 8; + /// Object is untransferable any operations that might result in a transfer are disallowed. + const EOBJECT_NOT_TRANSFERRABLE: u64 = 9; + + /// Explicitly separate the GUID space between Object and Account to prevent accidental overlap. + const INIT_GUID_CREATION_NUM: u64 = 0x4000000000000; + + /// Maximum nesting from one object to another. That is objects can technically have infinte + /// nesting, but any checks such as transfer will only be evaluated this deep. + const MAXIMUM_OBJECT_NESTING: u8 = 8; + + /// generate_unique_address uses this for domain separation within its native implementation + const DERIVE_AUID_ADDRESS_SCHEME: u8 = 0xFB; + + /// Scheme identifier used to generate an object's address `obj_addr` as derived from another object. + /// The object's address is generated as: + /// ``` + /// obj_addr = sha3_256(account addr | derived from object's address | 0xFC) + /// ``` + /// + /// This 0xFC constant serves as a domain separation tag to prevent existing authentication key and resource account + /// derivation to produce an object address. + const OBJECT_DERIVED_SCHEME: u8 = 0xFC; + + /// Scheme identifier used to generate an object's address `obj_addr` via a fresh GUID generated by the creator at + /// `source_addr`. The object's address is generated as: + /// ``` + /// obj_addr = sha3_256(guid | 0xFD) + /// ``` + /// where `guid = account::create_guid(create_signer(source_addr))` + /// + /// This 0xFD constant serves as a domain separation tag to prevent existing authentication key and resource account + /// derivation to produce an object address. + const OBJECT_FROM_GUID_ADDRESS_SCHEME: u8 = 0xFD; + + /// Scheme identifier used to generate an object's address `obj_addr` from the creator's `source_addr` and a `seed` as: + /// obj_addr = sha3_256(source_addr | seed | 0xFE). + /// + /// This 0xFE constant serves as a domain separation tag to prevent existing authentication key and resource account + /// derivation to produce an object address. + const OBJECT_FROM_SEED_ADDRESS_SCHEME: u8 = 0xFE; + + /// Address where unwanted objects can be forcefully transferred to. + const BURN_ADDRESS: address = @0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// The core of the object model that defines ownership, transferability, and events. + struct ObjectCore has key { + /// Used by guid to guarantee globally unique objects and create event streams + guid_creation_num: u64, + /// The address (object or account) that owns this object + owner: address, + /// Object transferring is a common operation, this allows for disabling and enabling + /// transfers bypassing the use of a TransferRef. + allow_ungated_transfer: bool, + /// Emitted events upon transferring of ownership. + transfer_events: event::EventHandle, + } + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// This is added to objects that are burnt (ownership transferred to BURN_ADDRESS). + struct TombStone has key { + /// Track the previous owner before the object is burnt so they can reclaim later if so desired. + original_owner: address, + } + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// The existence of this renders all `TransferRef`s irrelevant. The object cannot be moved. + struct Untransferable has key {} + + #[resource_group(scope = global)] + /// A shared resource group for storing object resources together in storage. + struct ObjectGroup {} + + /// A pointer to an object -- these can only provide guarantees based upon the underlying data + /// type, that is the validity of T existing at an address is something that cannot be verified + /// by any other module than the module that defined T. Similarly, the module that defines T + /// can remove it from storage at any point in time. + struct Object has copy, drop, store { + inner: address, + } + + /// This is a one time ability given to the creator to configure the object as necessary + struct ConstructorRef has drop { + self: address, + /// True if the object can be deleted. Named objects are not deletable. + can_delete: bool, + } + + /// Used to remove an object from storage. + struct DeleteRef has drop, store { + self: address, + } + + /// Used to create events or move additional resources into object storage. + struct ExtendRef has drop, store { + self: address, + } + + /// Used to create LinearTransferRef, hence ownership transfer. + struct TransferRef has drop, store { + self: address, + } + + /// Used to perform transfers. This locks transferring ability to a single time use bound to + /// the current owner. + struct LinearTransferRef has drop { + self: address, + owner: address, + } + + /// Used to create derived objects from a given objects. + struct DeriveRef has drop, store { + self: address, + } + + /// Emitted whenever the object's owner field is changed. + struct TransferEvent has drop, store { + object: address, + from: address, + to: address, + } + + #[event] + /// Emitted whenever the object's owner field is changed. + struct Transfer has drop, store { + object: address, + from: address, + to: address, + } + + #[view] + public fun is_untransferable(object: Object): bool { + exists(object.inner) + } + + #[view] + public fun is_burnt(object: Object): bool { + exists(object.inner) + } + + /// Produces an ObjectId from the given address. This is not verified. + public fun address_to_object(object: address): Object { + assert!(exists(object), error::not_found(EOBJECT_DOES_NOT_EXIST)); + assert!(exists_at(object), error::not_found(ERESOURCE_DOES_NOT_EXIST)); + Object { inner: object } + } + + /// Returns true if there exists an object or the remnants of an object. + public fun is_object(object: address): bool { + exists(object) + } + + /// Returns true if there exists an object with resource T. + public fun object_exists(object: address): bool { + exists(object) && exists_at(object) + } + + /// Derives an object address from source material: sha3_256([creator address | seed | 0xFE]). + public fun create_object_address(source: &address, seed: vector): address { + let bytes = bcs::to_bytes(source); + vector::append(&mut bytes, seed); + vector::push_back(&mut bytes, OBJECT_FROM_SEED_ADDRESS_SCHEME); + from_bcs::to_address(hash::sha3_256(bytes)) + } + + native fun create_user_derived_object_address_impl(source: address, derive_from: address): address; + + /// Derives an object address from the source address and an object: sha3_256([source | object addr | 0xFC]). + public fun create_user_derived_object_address(source: address, derive_from: address): address { + if (std::features::object_native_derived_address_enabled()) { + create_user_derived_object_address_impl(source, derive_from) + } else { + let bytes = bcs::to_bytes(&source); + vector::append(&mut bytes, bcs::to_bytes(&derive_from)); + vector::push_back(&mut bytes, OBJECT_DERIVED_SCHEME); + from_bcs::to_address(hash::sha3_256(bytes)) + } + } + + /// Derives an object from an Account GUID. + public fun create_guid_object_address(source: address, creation_num: u64): address { + let id = guid::create_id(source, creation_num); + let bytes = bcs::to_bytes(&id); + vector::push_back(&mut bytes, OBJECT_FROM_GUID_ADDRESS_SCHEME); + from_bcs::to_address(hash::sha3_256(bytes)) + } + + native fun exists_at(object: address): bool; + + /// Returns the address of within an ObjectId. + public fun object_address(object: &Object): address { + object.inner + } + + /// Convert Object to Object. + public fun convert(object: Object): Object { + address_to_object(object.inner) + } + + /// Create a new named object and return the ConstructorRef. Named objects can be queried globally + /// by knowing the user generated seed used to create them. Named objects cannot be deleted. + public fun create_named_object(creator: &signer, seed: vector): ConstructorRef { + let creator_address = signer::address_of(creator); + let obj_addr = create_object_address(&creator_address, seed); + create_object_internal(creator_address, obj_addr, false) + } + + /// Create a new object whose address is derived based on the creator account address and another object. + /// Derivde objects, similar to named objects, cannot be deleted. + public(friend) fun create_user_derived_object(creator_address: address, derive_ref: &DeriveRef): ConstructorRef { + let obj_addr = create_user_derived_object_address(creator_address, derive_ref.self); + create_object_internal(creator_address, obj_addr, false) + } + + /// Create a new object by generating a random unique address based on transaction hash. + /// The unique address is computed sha3_256([transaction hash | auid counter | 0xFB]). + /// The created object is deletable as we can guarantee the same unique address can + /// never be regenerated with future txs. + public fun create_object(owner_address: address): ConstructorRef { + let unique_address = transaction_context::generate_auid_address(); + create_object_internal(owner_address, unique_address, true) + } + + /// Same as `create_object` except the object to be created will be undeletable. + public fun create_sticky_object(owner_address: address): ConstructorRef { + let unique_address = transaction_context::generate_auid_address(); + create_object_internal(owner_address, unique_address, false) + } + + /// Create a sticky object at a specific address. Only used by aptos_framework::coin. + public(friend) fun create_sticky_object_at_address( + owner_address: address, + object_address: address, + ): ConstructorRef { + create_object_internal(owner_address, object_address, false) + } + + #[deprecated] + /// Use `create_object` instead. + /// Create a new object from a GUID generated by an account. + /// As the GUID creation internally increments a counter, two transactions that executes + /// `create_object_from_account` function for the same creator run sequentially. + /// Therefore, using `create_object` method for creating objects is preferrable as it + /// doesn't have the same bottlenecks. + public fun create_object_from_account(creator: &signer): ConstructorRef { + let guid = account::create_guid(creator); + create_object_from_guid(signer::address_of(creator), guid) + } + + #[deprecated] + /// Use `create_object` instead. + /// Create a new object from a GUID generated by an object. + /// As the GUID creation internally increments a counter, two transactions that executes + /// `create_object_from_object` function for the same creator run sequentially. + /// Therefore, using `create_object` method for creating objects is preferrable as it + /// doesn't have the same bottlenecks. + public fun create_object_from_object(creator: &signer): ConstructorRef acquires ObjectCore { + let guid = create_guid(creator); + create_object_from_guid(signer::address_of(creator), guid) + } + + fun create_object_from_guid(creator_address: address, guid: guid::GUID): ConstructorRef { + let bytes = bcs::to_bytes(&guid); + vector::push_back(&mut bytes, OBJECT_FROM_GUID_ADDRESS_SCHEME); + let obj_addr = from_bcs::to_address(hash::sha3_256(bytes)); + create_object_internal(creator_address, obj_addr, true) + } + + fun create_object_internal( + creator_address: address, + object: address, + can_delete: bool, + ): ConstructorRef { + assert!(!exists(object), error::already_exists(EOBJECT_EXISTS)); + + let object_signer = create_signer(object); + let guid_creation_num = INIT_GUID_CREATION_NUM; + let transfer_events_guid = guid::create(object, &mut guid_creation_num); + + move_to( + &object_signer, + ObjectCore { + guid_creation_num, + owner: creator_address, + allow_ungated_transfer: true, + transfer_events: event::new_event_handle(transfer_events_guid), + }, + ); + ConstructorRef { self: object, can_delete } + } + + // Creation helpers + + /// Generates the DeleteRef, which can be used to remove ObjectCore from global storage. + public fun generate_delete_ref(ref: &ConstructorRef): DeleteRef { + assert!(ref.can_delete, error::permission_denied(ECANNOT_DELETE)); + DeleteRef { self: ref.self } + } + + /// Generates the ExtendRef, which can be used to add new events and resources to the object. + public fun generate_extend_ref(ref: &ConstructorRef): ExtendRef { + ExtendRef { self: ref.self } + } + + /// Generates the TransferRef, which can be used to manage object transfers. + public fun generate_transfer_ref(ref: &ConstructorRef): TransferRef { + assert!(!exists(ref.self), error::permission_denied(EOBJECT_NOT_TRANSFERRABLE)); + TransferRef { self: ref.self } + } + + /// Generates the DeriveRef, which can be used to create determnistic derived objects from the current object. + public fun generate_derive_ref(ref: &ConstructorRef): DeriveRef { + DeriveRef { self: ref.self } + } + + /// Create a signer for the ConstructorRef + public fun generate_signer(ref: &ConstructorRef): signer { + create_signer(ref.self) + } + + /// Returns the address associated with the constructor + public fun address_from_constructor_ref(ref: &ConstructorRef): address { + ref.self + } + + /// Returns an Object from within a ConstructorRef + public fun object_from_constructor_ref(ref: &ConstructorRef): Object { + address_to_object(ref.self) + } + + /// Returns whether or not the ConstructorRef can be used to create DeleteRef + public fun can_generate_delete_ref(ref: &ConstructorRef): bool { + ref.can_delete + } + + // Signer required functions + + /// Create a guid for the object, typically used for events + public fun create_guid(object: &signer): guid::GUID acquires ObjectCore { + let addr = signer::address_of(object); + let object_data = borrow_global_mut(addr); + guid::create(addr, &mut object_data.guid_creation_num) + } + + /// Generate a new event handle. + public fun new_event_handle( + object: &signer, + ): event::EventHandle acquires ObjectCore { + event::new_event_handle(create_guid(object)) + } + + // Deletion helpers + + /// Returns the address associated with the constructor + public fun address_from_delete_ref(ref: &DeleteRef): address { + ref.self + } + + /// Returns an Object from within a DeleteRef. + public fun object_from_delete_ref(ref: &DeleteRef): Object { + address_to_object(ref.self) + } + + /// Removes from the specified Object from global storage. + public fun delete(ref: DeleteRef) acquires Untransferable, ObjectCore { + let object_core = move_from(ref.self); + let ObjectCore { + guid_creation_num: _, + owner: _, + allow_ungated_transfer: _, + transfer_events, + } = object_core; + + if (exists(ref.self)) { + let Untransferable {} = move_from(ref.self); + }; + + event::destroy_handle(transfer_events); + } + + // Extension helpers + + /// Create a signer for the ExtendRef + public fun generate_signer_for_extending(ref: &ExtendRef): signer { + create_signer(ref.self) + } + + /// Returns an address from within a ExtendRef. + public fun address_from_extend_ref(ref: &ExtendRef): address { + ref.self + } + + // Transfer functionality + + /// Disable direct transfer, transfers can only be triggered via a TransferRef + public fun disable_ungated_transfer(ref: &TransferRef) acquires ObjectCore { + let object = borrow_global_mut(ref.self); + object.allow_ungated_transfer = false; + } + + /// Prevent moving of the object + public fun set_untransferable(ref: &ConstructorRef) acquires ObjectCore { + let object = borrow_global_mut(ref.self); + object.allow_ungated_transfer = false; + let object_signer = generate_signer(ref); + move_to(&object_signer, Untransferable {}); + } + + /// Enable direct transfer. + public fun enable_ungated_transfer(ref: &TransferRef) acquires ObjectCore { + assert!(!exists(ref.self), error::permission_denied(EOBJECT_NOT_TRANSFERRABLE)); + let object = borrow_global_mut(ref.self); + object.allow_ungated_transfer = true; + } + + /// Create a LinearTransferRef for a one-time transfer. This requires that the owner at the + /// time of generation is the owner at the time of transferring. + public fun generate_linear_transfer_ref(ref: &TransferRef): LinearTransferRef acquires ObjectCore { + assert!(!exists(ref.self), error::permission_denied(EOBJECT_NOT_TRANSFERRABLE)); + let owner = owner(Object { inner: ref.self }); + LinearTransferRef { + self: ref.self, + owner, + } + } + + /// Transfer to the destination address using a LinearTransferRef. + public fun transfer_with_ref(ref: LinearTransferRef, to: address) acquires ObjectCore, TombStone { + assert!(!exists(ref.self), error::permission_denied(EOBJECT_NOT_TRANSFERRABLE)); + + // Undo soft burn if present as we don't want the original owner to be able to reclaim by calling unburn later. + if (exists(ref.self)) { + let TombStone { original_owner: _ } = move_from(ref.self); + }; + + let object = borrow_global_mut(ref.self); + assert!( + object.owner == ref.owner, + error::permission_denied(ENOT_OBJECT_OWNER), + ); + if (std::features::module_event_migration_enabled()) { + event::emit( + Transfer { + object: ref.self, + from: object.owner, + to, + }, + ); + }; + event::emit_event( + &mut object.transfer_events, + TransferEvent { + object: ref.self, + from: object.owner, + to, + }, + ); + object.owner = to; + } + + /// Entry function that can be used to transfer, if allow_ungated_transfer is set true. + public entry fun transfer_call( + owner: &signer, + object: address, + to: address, + ) acquires ObjectCore { + transfer_raw(owner, object, to) + } + + /// Transfers ownership of the object (and all associated resources) at the specified address + /// for Object to the "to" address. + public entry fun transfer( + owner: &signer, + object: Object, + to: address, + ) acquires ObjectCore { + transfer_raw(owner, object.inner, to) + } + + /// Attempts to transfer using addresses only. Transfers the given object if + /// allow_ungated_transfer is set true. Note, that this allows the owner of a nested object to + /// transfer that object, so long as allow_ungated_transfer is enabled at each stage in the + /// hierarchy. + public fun transfer_raw( + owner: &signer, + object: address, + to: address, + ) acquires ObjectCore { + let owner_address = signer::address_of(owner); + verify_ungated_and_descendant(owner_address, object); + transfer_raw_inner(object, to); + } + + inline fun transfer_raw_inner(object: address, to: address) acquires ObjectCore { + let object_core = borrow_global_mut(object); + if (object_core.owner != to) { + if (std::features::module_event_migration_enabled()) { + event::emit( + Transfer { + object, + from: object_core.owner, + to, + }, + ); + }; + event::emit_event( + &mut object_core.transfer_events, + TransferEvent { + object, + from: object_core.owner, + to, + }, + ); + object_core.owner = to; + }; + } + + /// Transfer the given object to another object. See `transfer` for more information. + public entry fun transfer_to_object( + owner: &signer, + object: Object, + to: Object, + ) acquires ObjectCore { + transfer(owner, object, to.inner) + } + + /// This checks that the destination address is eventually owned by the owner and that each + /// object between the two allows for ungated transfers. Note, this is limited to a depth of 8 + /// objects may have cyclic dependencies. + fun verify_ungated_and_descendant(owner: address, destination: address) acquires ObjectCore { + let current_address = destination; + assert!( + exists(current_address), + error::not_found(EOBJECT_DOES_NOT_EXIST), + ); + + let object = borrow_global(current_address); + assert!( + object.allow_ungated_transfer, + error::permission_denied(ENO_UNGATED_TRANSFERS), + ); + + let current_address = object.owner; + let count = 0; + while (owner != current_address) { + count = count + 1; + assert!(count < MAXIMUM_OBJECT_NESTING, error::out_of_range(EMAXIMUM_NESTING)); + // At this point, the first object exists and so the more likely case is that the + // object's owner is not an object. So we return a more sensible error. + assert!( + exists(current_address), + error::permission_denied(ENOT_OBJECT_OWNER), + ); + let object = borrow_global(current_address); + assert!( + object.allow_ungated_transfer, + error::permission_denied(ENO_UNGATED_TRANSFERS), + ); + current_address = object.owner; + }; + } + + /// Forcefully transfer an unwanted object to BURN_ADDRESS, ignoring whether ungated_transfer is allowed. + /// This only works for objects directly owned and for simplicity does not apply to indirectly owned objects. + /// Original owners can reclaim burnt objects any time in the future by calling unburn. + public entry fun burn(owner: &signer, object: Object) acquires ObjectCore { + let original_owner = signer::address_of(owner); + assert!(is_owner(object, original_owner), error::permission_denied(ENOT_OBJECT_OWNER)); + let object_addr = object.inner; + move_to(&create_signer(object_addr), TombStone { original_owner }); + transfer_raw_inner(object_addr, BURN_ADDRESS); + } + + /// Allow origin owners to reclaim any objects they previous burnt. + public entry fun unburn( + original_owner: &signer, + object: Object, + ) acquires TombStone, ObjectCore { + let object_addr = object.inner; + assert!(exists(object_addr), error::invalid_argument(EOBJECT_NOT_BURNT)); + + let TombStone { original_owner: original_owner_addr } = move_from(object_addr); + assert!(original_owner_addr == signer::address_of(original_owner), error::permission_denied(ENOT_OBJECT_OWNER)); + transfer_raw_inner(object_addr, original_owner_addr); + } + + /// Accessors + /// Return true if ungated transfer is allowed. + public fun ungated_transfer_allowed(object: Object): bool acquires ObjectCore { + assert!( + exists(object.inner), + error::not_found(EOBJECT_DOES_NOT_EXIST), + ); + borrow_global(object.inner).allow_ungated_transfer + } + + /// Return the current owner. + public fun owner(object: Object): address acquires ObjectCore { + assert!( + exists(object.inner), + error::not_found(EOBJECT_DOES_NOT_EXIST), + ); + borrow_global(object.inner).owner + } + + /// Return true if the provided address is the current owner. + public fun is_owner(object: Object, owner: address): bool acquires ObjectCore { + owner(object) == owner + } + + /// Return true if the provided address has indirect or direct ownership of the provided object. + public fun owns(object: Object, owner: address): bool acquires ObjectCore { + let current_address = object_address(&object); + if (current_address == owner) { + return true + }; + + assert!( + exists(current_address), + error::not_found(EOBJECT_DOES_NOT_EXIST), + ); + + let object = borrow_global(current_address); + let current_address = object.owner; + + let count = 0; + while (owner != current_address) { + count = count + 1; + assert!(count < MAXIMUM_OBJECT_NESTING, error::out_of_range(EMAXIMUM_NESTING)); + if (!exists(current_address)) { + return false + }; + + let object = borrow_global(current_address); + current_address = object.owner; + }; + true + } + + /// Returns the root owner of an object. As objects support nested ownership, it can be useful + /// to determine the identity of the starting point of ownership. + public fun root_owner(object: Object): address acquires ObjectCore { + let obj_owner = owner(object); + while (is_object(obj_owner)) { + obj_owner = owner(address_to_object(obj_owner)); + }; + obj_owner + } + + #[test_only] + use std::option::{Self, Option}; + + #[test_only] + const EHERO_DOES_NOT_EXIST: u64 = 0x100; + #[test_only] + const EWEAPON_DOES_NOT_EXIST: u64 = 0x101; + + #[test_only] + struct HeroEquipEvent has drop, store { + weapon_id: Option>, + } + + #[test_only] + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + struct Hero has key { + equip_events: event::EventHandle, + weapon: Option>, + } + + #[test_only] + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + struct Weapon has key {} + + #[test_only] + public fun create_hero(creator: &signer): (ConstructorRef, Object) acquires ObjectCore { + let hero_constructor_ref = create_named_object(creator, b"hero"); + let hero_signer = generate_signer(&hero_constructor_ref); + let guid_for_equip_events = create_guid(&hero_signer); + move_to( + &hero_signer, + Hero { + weapon: option::none(), + equip_events: event::new_event_handle(guid_for_equip_events), + }, + ); + + let hero = object_from_constructor_ref(&hero_constructor_ref); + (hero_constructor_ref, hero) + } + + #[test_only] + public fun create_weapon(creator: &signer): (ConstructorRef, Object) { + let weapon_constructor_ref = create_named_object(creator, b"weapon"); + let weapon_signer = generate_signer(&weapon_constructor_ref); + move_to(&weapon_signer, Weapon {}); + let weapon = object_from_constructor_ref(&weapon_constructor_ref); + (weapon_constructor_ref, weapon) + } + + #[test_only] + public fun hero_equip( + owner: &signer, + hero: Object, + weapon: Object, + ) acquires Hero, ObjectCore { + transfer_to_object(owner, weapon, hero); + let hero_obj = borrow_global_mut(object_address(&hero)); + option::fill(&mut hero_obj.weapon, weapon); + event::emit_event( + &mut hero_obj.equip_events, + HeroEquipEvent { weapon_id: option::some(weapon) }, + ); + } + + #[test_only] + public fun hero_unequip( + owner: &signer, + hero: Object, + weapon: Object, + ) acquires Hero, ObjectCore { + transfer(owner, weapon, signer::address_of(owner)); + let hero = borrow_global_mut(object_address(&hero)); + option::extract(&mut hero.weapon); + event::emit_event( + &mut hero.equip_events, + HeroEquipEvent { weapon_id: option::none() }, + ); + } + + #[test(creator = @0x123)] + fun test_object(creator: &signer) acquires Hero, ObjectCore { + let (_, hero) = create_hero(creator); + let (_, weapon) = create_weapon(creator); + + assert!(owns(weapon, @0x123), 0); + hero_equip(creator, hero, weapon); + assert!(owns(weapon, @0x123), 1); + hero_unequip(creator, hero, weapon); + assert!(root_owner(hero) == @0x123, 2); + assert!(root_owner(weapon) == @0x123, 3); + } + + #[test(creator = @0x123)] + fun test_linear_transfer(creator: &signer) acquires ObjectCore, TombStone { + let (hero_constructor, hero) = create_hero(creator); + assert!(root_owner(hero) == @0x123, 0); + + let transfer_ref = generate_transfer_ref(&hero_constructor); + let linear_transfer_ref = generate_linear_transfer_ref(&transfer_ref); + transfer_with_ref(linear_transfer_ref, @0x456); + assert!(owner(hero) == @0x456, 1); + assert!(owns(hero, @0x456), 2); + assert!(root_owner(hero) == @0x456, 3); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 0x50004, location = Self)] + fun test_bad_linear_transfer(creator: &signer) acquires ObjectCore, TombStone { + let (hero_constructor, hero) = create_hero(creator); + let transfer_ref = generate_transfer_ref(&hero_constructor); + let linear_transfer_ref_good = generate_linear_transfer_ref(&transfer_ref); + // This will contain the address of the creator + let linear_transfer_ref_bad = generate_linear_transfer_ref(&transfer_ref); + transfer_with_ref(linear_transfer_ref_good, @0x456); + assert!(owner(hero) == @0x456, 0); + transfer_with_ref(linear_transfer_ref_bad, @0x789); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 0x10008, location = Self)] + fun test_cannot_unburn_after_transfer_with_ref(creator: &signer) acquires ObjectCore, TombStone { + let (hero_constructor, hero) = create_hero(creator); + burn(creator, hero); + let transfer_ref = generate_transfer_ref(&hero_constructor); + transfer_with_ref(generate_linear_transfer_ref(&transfer_ref), @0x456); + unburn(creator, hero); + } + + #[test(fx = @std)] + fun test_correct_auid() { + let auid1 = aptos_framework::transaction_context::generate_auid_address(); + let bytes = aptos_framework::transaction_context::get_transaction_hash(); + std::vector::push_back(&mut bytes, 1); + std::vector::push_back(&mut bytes, 0); + std::vector::push_back(&mut bytes, 0); + std::vector::push_back(&mut bytes, 0); + std::vector::push_back(&mut bytes, 0); + std::vector::push_back(&mut bytes, 0); + std::vector::push_back(&mut bytes, 0); + std::vector::push_back(&mut bytes, 0); + std::vector::push_back(&mut bytes, DERIVE_AUID_ADDRESS_SCHEME); + let auid2 = aptos_framework::from_bcs::to_address(std::hash::sha3_256(bytes)); + assert!(auid1 == auid2, 0); + } + + #[test(fx = @std)] + fun test_correct_derived_object_address(fx: signer) { + use std::features; + use aptos_framework::object; + let feature = features::get_object_native_derived_address_feature(); + + let source = @0x12345; + let derive_from = @0x7890; + + features::change_feature_flags_for_testing(&fx, vector[], vector[feature]); + let in_move = object::create_user_derived_object_address(source, derive_from); + + features::change_feature_flags_for_testing(&fx, vector[feature], vector[]); + let in_native = object::create_user_derived_object_address(source, derive_from); + + assert!(in_move == in_native, 0); + + let bytes = bcs::to_bytes(&source); + vector::append(&mut bytes, bcs::to_bytes(&derive_from)); + vector::push_back(&mut bytes, OBJECT_DERIVED_SCHEME); + let directly = from_bcs::to_address(hash::sha3_256(bytes)); + + assert!(directly == in_native, 0); + } + + #[test(creator = @0x123)] + fun test_burn_and_unburn(creator: &signer) acquires ObjectCore, TombStone { + let (hero_constructor, hero) = create_hero(creator); + // Freeze the object. + let transfer_ref = generate_transfer_ref(&hero_constructor); + disable_ungated_transfer(&transfer_ref); + + // Owner should be able to burn, despite ungated transfer disallowed. + burn(creator, hero); + assert!(owner(hero) == BURN_ADDRESS, 0); + assert!(!ungated_transfer_allowed(hero), 0); + + // Owner should be able to reclaim. + unburn(creator, hero); + assert!(owner(hero) == signer::address_of(creator), 0); + // Object still frozen. + assert!(!ungated_transfer_allowed(hero), 0); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 0x50004, location = Self)] + fun test_burn_indirectly_owned_should_fail(creator: &signer) acquires ObjectCore { + let (_, hero) = create_hero(creator); + let (_, weapon) = create_weapon(creator); + transfer_to_object(creator, weapon, hero); + + // Owner should be not be able to burn weapon directly. + assert!(owner(weapon) == object_address(&hero), 0); + assert!(owns(weapon, signer::address_of(creator)), 0); + burn(creator, weapon); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 0x10008, location = Self)] + fun test_unburn_object_not_burnt_should_fail(creator: &signer) acquires ObjectCore, TombStone { + let (_, hero) = create_hero(creator); + unburn(creator, hero); + } + + #[test_only] + fun create_simple_object(creator: &signer, seed: vector): Object { + object_from_constructor_ref(&create_named_object(creator, seed)) + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 131078, location = Self)] + fun test_exceeding_maximum_object_nesting_owns_should_fail(creator: &signer) acquires ObjectCore { + let obj1 = create_simple_object(creator, b"1"); + let obj2 = create_simple_object(creator, b"2"); + let obj3 = create_simple_object(creator, b"3"); + let obj4 = create_simple_object(creator, b"4"); + let obj5 = create_simple_object(creator, b"5"); + let obj6 = create_simple_object(creator, b"6"); + let obj7 = create_simple_object(creator, b"7"); + let obj8 = create_simple_object(creator, b"8"); + let obj9 = create_simple_object(creator, b"9"); + + transfer(creator, obj1, object_address(&obj2)); + transfer(creator, obj2, object_address(&obj3)); + transfer(creator, obj3, object_address(&obj4)); + transfer(creator, obj4, object_address(&obj5)); + transfer(creator, obj5, object_address(&obj6)); + transfer(creator, obj6, object_address(&obj7)); + transfer(creator, obj7, object_address(&obj8)); + transfer(creator, obj8, object_address(&obj9)); + + assert!(owns(obj9, signer::address_of(creator)), 1); + assert!(owns(obj8, signer::address_of(creator)), 1); + assert!(owns(obj7, signer::address_of(creator)), 1); + assert!(owns(obj6, signer::address_of(creator)), 1); + assert!(owns(obj5, signer::address_of(creator)), 1); + assert!(owns(obj4, signer::address_of(creator)), 1); + assert!(owns(obj3, signer::address_of(creator)), 1); + assert!(owns(obj2, signer::address_of(creator)), 1); + + // Calling `owns` should fail as the nesting is too deep. + assert!(owns(obj1, signer::address_of(creator)), 1); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 131078, location = Self)] + fun test_exceeding_maximum_object_nesting_transfer_should_fail(creator: &signer) acquires ObjectCore { + let obj1 = create_simple_object(creator, b"1"); + let obj2 = create_simple_object(creator, b"2"); + let obj3 = create_simple_object(creator, b"3"); + let obj4 = create_simple_object(creator, b"4"); + let obj5 = create_simple_object(creator, b"5"); + let obj6 = create_simple_object(creator, b"6"); + let obj7 = create_simple_object(creator, b"7"); + let obj8 = create_simple_object(creator, b"8"); + let obj9 = create_simple_object(creator, b"9"); + + transfer(creator, obj1, object_address(&obj2)); + transfer(creator, obj2, object_address(&obj3)); + transfer(creator, obj3, object_address(&obj4)); + transfer(creator, obj4, object_address(&obj5)); + transfer(creator, obj5, object_address(&obj6)); + transfer(creator, obj6, object_address(&obj7)); + transfer(creator, obj7, object_address(&obj8)); + transfer(creator, obj8, object_address(&obj9)); + + // This should fail as the nesting is too deep. + transfer(creator, obj1, @0x1); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 131078, location = Self)] + fun test_cyclic_ownership_transfer_should_fail(creator: &signer) acquires ObjectCore { + let obj1 = create_simple_object(creator, b"1"); + // This creates a cycle (self-loop) in ownership. + transfer(creator, obj1, object_address(&obj1)); + // This should fails as the ownership is cyclic. + transfer(creator, obj1, object_address(&obj1)); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 131078, location = Self)] + fun test_cyclic_ownership_owns_should_fail(creator: &signer) acquires ObjectCore { + let obj1 = create_simple_object(creator, b"1"); + // This creates a cycle (self-loop) in ownership. + transfer(creator, obj1, object_address(&obj1)); + // This should fails as the ownership is cyclic. + let _ = owns(obj1, signer::address_of(creator)); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 327683, location = Self)] + fun test_untransferable_direct_ownership_transfer(creator: &signer) acquires ObjectCore { + let (hero_constructor_ref, hero) = create_hero(creator); + set_untransferable(&hero_constructor_ref); + transfer(creator, hero, @0x456); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 327689, location = Self)] + fun test_untransferable_direct_ownership_gen_transfer_ref(creator: &signer) acquires ObjectCore { + let (hero_constructor_ref, _) = create_hero(creator); + set_untransferable(&hero_constructor_ref); + generate_transfer_ref(&hero_constructor_ref); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 327689, location = Self)] + fun test_untransferable_direct_ownership_gen_linear_transfer_ref(creator: &signer) acquires ObjectCore { + let (hero_constructor_ref, _) = create_hero(creator); + let transfer_ref = generate_transfer_ref(&hero_constructor_ref); + set_untransferable(&hero_constructor_ref); + generate_linear_transfer_ref(&transfer_ref); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 327689, location = Self)] + fun test_untransferable_direct_ownership_with_linear_transfer_ref(creator: &signer) acquires ObjectCore, TombStone { + let (hero_constructor_ref, _) = create_hero(creator); + let transfer_ref = generate_transfer_ref(&hero_constructor_ref); + let linear_transfer_ref = generate_linear_transfer_ref(&transfer_ref); + set_untransferable(&hero_constructor_ref); + transfer_with_ref(linear_transfer_ref, @0x456); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 327683, location = Self)] + fun test_untransferable_indirect_ownership_transfer(creator: &signer) acquires ObjectCore { + let (_, hero) = create_hero(creator); + let (weapon_constructor_ref, weapon) = create_weapon(creator); + transfer_to_object(creator, weapon, hero); + set_untransferable(&weapon_constructor_ref); + transfer(creator, weapon, @0x456); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 327689, location = Self)] + fun test_untransferable_indirect_ownership_gen_transfer_ref(creator: &signer) acquires ObjectCore { + let (_, hero) = create_hero(creator); + let (weapon_constructor_ref, weapon) = create_weapon(creator); + transfer_to_object(creator, weapon, hero); + set_untransferable(&weapon_constructor_ref); + generate_transfer_ref(&weapon_constructor_ref); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 327689, location = Self)] + fun test_untransferable_indirect_ownership_gen_linear_transfer_ref(creator: &signer) acquires ObjectCore { + let (_, hero) = create_hero(creator); + let (weapon_constructor_ref, weapon) = create_weapon(creator); + transfer_to_object(creator, weapon, hero); + let transfer_ref = generate_transfer_ref(&weapon_constructor_ref); + set_untransferable(&weapon_constructor_ref); + generate_linear_transfer_ref(&transfer_ref); + } + + #[test(creator = @0x123)] + #[expected_failure(abort_code = 327689, location = Self)] + fun test_untransferable_indirect_ownership_with_linear_transfer_ref(creator: &signer) acquires ObjectCore, TombStone { + let (_, hero) = create_hero(creator); + let (weapon_constructor_ref, weapon) = create_weapon(creator); + transfer_to_object(creator, weapon, hero); + let transfer_ref = generate_transfer_ref(&weapon_constructor_ref); + let linear_transfer_ref = generate_linear_transfer_ref(&transfer_ref); + set_untransferable(&weapon_constructor_ref); + transfer_with_ref(linear_transfer_ref, @0x456); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/object_code_deployment.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/object_code_deployment.move new file mode 100644 index 000000000..ef9e7d37f --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/object_code_deployment.move @@ -0,0 +1,147 @@ +/// This module allows users to deploy, upgrade and freeze modules deployed to objects on-chain. +/// This enables users to deploy modules to an object with a unique address each time they are published. +/// This modules provides an alternative method to publish code on-chain, where code is deployed to objects rather than accounts. +/// This is encouraged as it abstracts the necessary resources needed for deploying modules, +/// along with the required authorization to upgrade and freeze modules. +/// +/// The functionalities of this module are as follows. +/// +/// Publishing modules flow: +/// 1. Create a new object with the address derived from the publisher address and the object seed. +/// 2. Publish the module passed in the function via `metadata_serialized` and `code` to the newly created object. +/// 3. Emits 'Publish' event with the address of the newly created object. +/// 4. Create a `ManagingRefs` which stores the extend ref of the newly created object. +/// Note: This is needed to upgrade the code as the signer must be generated to upgrade the existing code in an object. +/// +/// Upgrading modules flow: +/// 1. Assert the `code_object` passed in the function is owned by the `publisher`. +/// 2. Assert the `code_object` passed in the function exists in global storage. +/// 2. Retrieve the `ExtendRef` from the `code_object` and generate the signer from this. +/// 3. Upgrade the module with the `metadata_serialized` and `code` passed in the function. +/// 4. Emits 'Upgrade' event with the address of the object with the upgraded code. +/// Note: If the modules were deployed as immutable when calling `publish`, the upgrade will fail. +/// +/// Freezing modules flow: +/// 1. Assert the `code_object` passed in the function exists in global storage. +/// 2. Assert the `code_object` passed in the function is owned by the `publisher`. +/// 3. Mark all the modules in the `code_object` as immutable. +/// 4. Emits 'Freeze' event with the address of the object with the frozen code. +/// Note: There is no unfreeze function as this gives no benefit if the user can freeze/unfreeze modules at will. +/// Once modules are marked as immutable, they cannot be made mutable again. +module aptos_framework::object_code_deployment { + use std::bcs; + use std::error; + use std::features; + use std::signer; + use std::vector; + use aptos_framework::account; + use aptos_framework::code; + use aptos_framework::code::PackageRegistry; + use aptos_framework::event; + use aptos_framework::object; + use aptos_framework::object::{ExtendRef, Object}; + + /// Object code deployment feature not supported. + const EOBJECT_CODE_DEPLOYMENT_NOT_SUPPORTED: u64 = 1; + /// Not the owner of the `code_object` + const ENOT_CODE_OBJECT_OWNER: u64 = 2; + /// `code_object` does not exist. + const ECODE_OBJECT_DOES_NOT_EXIST: u64 = 3; + + const OBJECT_CODE_DEPLOYMENT_DOMAIN_SEPARATOR: vector = b"aptos_framework::object_code_deployment"; + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// Internal struct, attached to the object, that holds Refs we need to manage the code deployment (i.e. upgrades). + struct ManagingRefs has key { + /// We need to keep the extend ref to be able to generate the signer to upgrade existing code. + extend_ref: ExtendRef, + } + + #[event] + /// Event emitted when code is published to an object. + struct Publish has drop, store { + object_address: address, + } + + #[event] + /// Event emitted when code in an existing object is upgraded. + struct Upgrade has drop, store { + object_address: address, + } + + #[event] + /// Event emitted when code in an existing object is made immutable. + struct Freeze has drop, store { + object_address: address, + } + + /// Creates a new object with a unique address derived from the publisher address and the object seed. + /// Publishes the code passed in the function to the newly created object. + /// The caller must provide package metadata describing the package via `metadata_serialized` and + /// the code to be published via `code`. This contains a vector of modules to be deployed on-chain. + public entry fun publish( + publisher: &signer, + metadata_serialized: vector, + code: vector>, + ) { + assert!( + features::is_object_code_deployment_enabled(), + error::unavailable(EOBJECT_CODE_DEPLOYMENT_NOT_SUPPORTED), + ); + + let publisher_address = signer::address_of(publisher); + let object_seed = object_seed(publisher_address); + let constructor_ref = &object::create_named_object(publisher, object_seed); + let code_signer = &object::generate_signer(constructor_ref); + code::publish_package_txn(code_signer, metadata_serialized, code); + + event::emit(Publish { object_address: signer::address_of(code_signer), }); + + move_to(code_signer, ManagingRefs { + extend_ref: object::generate_extend_ref(constructor_ref), + }); + } + + inline fun object_seed(publisher: address): vector { + let sequence_number = account::get_sequence_number(publisher) + 1; + let seeds = vector[]; + vector::append(&mut seeds, bcs::to_bytes(&OBJECT_CODE_DEPLOYMENT_DOMAIN_SEPARATOR)); + vector::append(&mut seeds, bcs::to_bytes(&sequence_number)); + seeds + } + + /// Upgrades the existing modules at the `code_object` address with the new modules passed in `code`, + /// along with the metadata `metadata_serialized`. + /// Note: If the modules were deployed as immutable when calling `publish`, the upgrade will fail. + /// Requires the publisher to be the owner of the `code_object`. + public entry fun upgrade( + publisher: &signer, + metadata_serialized: vector, + code: vector>, + code_object: Object, + ) acquires ManagingRefs { + let publisher_address = signer::address_of(publisher); + assert!( + object::is_owner(code_object, publisher_address), + error::permission_denied(ENOT_CODE_OBJECT_OWNER), + ); + + let code_object_address = object::object_address(&code_object); + assert!(exists(code_object_address), error::not_found(ECODE_OBJECT_DOES_NOT_EXIST)); + + let extend_ref = &borrow_global(code_object_address).extend_ref; + let code_signer = &object::generate_signer_for_extending(extend_ref); + code::publish_package_txn(code_signer, metadata_serialized, code); + + event::emit(Upgrade { object_address: signer::address_of(code_signer), }); + } + + /// Make an existing upgradable package immutable. Once this is called, the package cannot be made upgradable again. + /// Each `code_object` should only have one package, as one package is deployed per object in this module. + /// Requires the `publisher` to be the owner of the `code_object`. + public entry fun freeze_code_object(publisher: &signer, code_object: Object) { + code::freeze_code_object(publisher, code_object); + + event::emit(Freeze { object_address: object::object_address(&code_object), }); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/optional_aggregator.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/optional_aggregator.move new file mode 100644 index 000000000..f3a545600 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/optional_aggregator.move @@ -0,0 +1,295 @@ +/// This module provides an interface to aggregate integers either via +/// aggregator (parallelizable) or via normal integers. +module aptos_framework::optional_aggregator { + use std::error; + use std::option::{Self, Option}; + + use aptos_framework::aggregator_factory; + use aptos_framework::aggregator::{Self, Aggregator}; + + friend aptos_framework::coin; + friend aptos_framework::fungible_asset; + + /// The value of aggregator underflows (goes below zero). Raised by native code. + const EAGGREGATOR_OVERFLOW: u64 = 1; + + /// Aggregator feature is not supported. Raised by native code. + const EAGGREGATOR_UNDERFLOW: u64 = 2; + + /// Wrapper around integer with a custom overflow limit. Supports add, subtract and read just like `Aggregator`. + struct Integer has store { + value: u128, + limit: u128, + } + + /// Creates a new integer which overflows on exceeding a `limit`. + fun new_integer(limit: u128): Integer { + Integer { + value: 0, + limit, + } + } + + /// Adds `value` to integer. Aborts on overflowing the limit. + fun add_integer(integer: &mut Integer, value: u128) { + assert!( + value <= (integer.limit - integer.value), + error::out_of_range(EAGGREGATOR_OVERFLOW) + ); + integer.value = integer.value + value; + } + + /// Subtracts `value` from integer. Aborts on going below zero. + fun sub_integer(integer: &mut Integer, value: u128) { + assert!(value <= integer.value, error::out_of_range(EAGGREGATOR_UNDERFLOW)); + integer.value = integer.value - value; + } + + /// Returns an overflow limit of integer. + fun limit(integer: &Integer): u128 { + integer.limit + } + + /// Returns a value stored in this integer. + fun read_integer(integer: &Integer): u128 { + integer.value + } + + /// Destroys an integer. + fun destroy_integer(integer: Integer) { + let Integer { value: _, limit: _ } = integer; + } + + /// Contains either an aggregator or a normal integer, both overflowing on limit. + struct OptionalAggregator has store { + // Parallelizable. + aggregator: Option, + // Non-parallelizable. + integer: Option, + } + + /// Creates a new optional aggregator. + public(friend) fun new(limit: u128, parallelizable: bool): OptionalAggregator { + if (parallelizable) { + OptionalAggregator { + aggregator: option::some(aggregator_factory::create_aggregator_internal(limit)), + integer: option::none(), + } + } else { + OptionalAggregator { + aggregator: option::none(), + integer: option::some(new_integer(limit)), + } + } + } + + /// Switches between parallelizable and non-parallelizable implementations. + public fun switch(optional_aggregator: &mut OptionalAggregator) { + let value = read(optional_aggregator); + switch_and_zero_out(optional_aggregator); + add(optional_aggregator, value); + } + + /// Switches between parallelizable and non-parallelizable implementations, setting + /// the value of the new optional aggregator to zero. + fun switch_and_zero_out(optional_aggregator: &mut OptionalAggregator) { + if (is_parallelizable(optional_aggregator)) { + switch_to_integer_and_zero_out(optional_aggregator); + } else { + switch_to_aggregator_and_zero_out(optional_aggregator); + } + } + + /// Switches from parallelizable to non-parallelizable implementation, zero-initializing + /// the value. + fun switch_to_integer_and_zero_out( + optional_aggregator: &mut OptionalAggregator + ): u128 { + let aggregator = option::extract(&mut optional_aggregator.aggregator); + let limit = aggregator::limit(&aggregator); + aggregator::destroy(aggregator); + let integer = new_integer(limit); + option::fill(&mut optional_aggregator.integer, integer); + limit + } + + /// Switches from non-parallelizable to parallelizable implementation, zero-initializing + /// the value. + fun switch_to_aggregator_and_zero_out( + optional_aggregator: &mut OptionalAggregator + ): u128 { + let integer = option::extract(&mut optional_aggregator.integer); + let limit = limit(&integer); + destroy_integer(integer); + let aggregator = aggregator_factory::create_aggregator_internal(limit); + option::fill(&mut optional_aggregator.aggregator, aggregator); + limit + } + + /// Destroys optional aggregator. + public fun destroy(optional_aggregator: OptionalAggregator) { + if (is_parallelizable(&optional_aggregator)) { + destroy_optional_aggregator(optional_aggregator); + } else { + destroy_optional_integer(optional_aggregator); + } + } + + /// Destroys parallelizable optional aggregator and returns its limit. + fun destroy_optional_aggregator(optional_aggregator: OptionalAggregator): u128 { + let OptionalAggregator { aggregator, integer } = optional_aggregator; + let limit = aggregator::limit(option::borrow(&aggregator)); + aggregator::destroy(option::destroy_some(aggregator)); + option::destroy_none(integer); + limit + } + + /// Destroys non-parallelizable optional aggregator and returns its limit. + fun destroy_optional_integer(optional_aggregator: OptionalAggregator): u128 { + let OptionalAggregator { aggregator, integer } = optional_aggregator; + let limit = limit(option::borrow(&integer)); + destroy_integer(option::destroy_some(integer)); + option::destroy_none(aggregator); + limit + } + + /// Adds `value` to optional aggregator, aborting on exceeding the `limit`. + public fun add(optional_aggregator: &mut OptionalAggregator, value: u128) { + if (option::is_some(&optional_aggregator.aggregator)) { + let aggregator = option::borrow_mut(&mut optional_aggregator.aggregator); + aggregator::add(aggregator, value); + } else { + let integer = option::borrow_mut(&mut optional_aggregator.integer); + add_integer(integer, value); + } + } + + /// Subtracts `value` from optional aggregator, aborting on going below zero. + public fun sub(optional_aggregator: &mut OptionalAggregator, value: u128) { + if (option::is_some(&optional_aggregator.aggregator)) { + let aggregator = option::borrow_mut(&mut optional_aggregator.aggregator); + aggregator::sub(aggregator, value); + } else { + let integer = option::borrow_mut(&mut optional_aggregator.integer); + sub_integer(integer, value); + } + } + + /// Returns the value stored in optional aggregator. + public fun read(optional_aggregator: &OptionalAggregator): u128 { + if (option::is_some(&optional_aggregator.aggregator)) { + let aggregator = option::borrow(&optional_aggregator.aggregator); + aggregator::read(aggregator) + } else { + let integer = option::borrow(&optional_aggregator.integer); + read_integer(integer) + } + } + + /// Returns true if optional aggregator uses parallelizable implementation. + public fun is_parallelizable(optional_aggregator: &OptionalAggregator): bool { + option::is_some(&optional_aggregator.aggregator) + } + + #[test(account = @aptos_framework)] + fun optional_aggregator_test(account: signer) { + aggregator_factory::initialize_aggregator_factory(&account); + + let aggregator = new(30, false); + assert!(!is_parallelizable(&aggregator), 0); + + add(&mut aggregator, 12); + add(&mut aggregator, 3); + assert!(read(&aggregator) == 15, 0); + + sub(&mut aggregator, 10); + assert!(read(&aggregator) == 5, 0); + + // Switch to parallelizable aggregator and check the value is preserved. + switch(&mut aggregator); + assert!(is_parallelizable(&aggregator), 0); + assert!(read(&aggregator) == 5, 0); + + add(&mut aggregator, 12); + add(&mut aggregator, 3); + assert!(read(&aggregator) == 20, 0); + + sub(&mut aggregator, 10); + assert!(read(&aggregator) == 10, 0); + + // Switch back! + switch(&mut aggregator); + assert!(!is_parallelizable(&aggregator), 0); + assert!(read(&aggregator) == 10, 0); + + destroy(aggregator); + } + + #[test(account = @aptos_framework)] + fun optional_aggregator_destroy_test(account: signer) { + aggregator_factory::initialize_aggregator_factory(&account); + + let aggregator = new(30, false); + destroy(aggregator); + + let aggregator = new(30, true); + destroy(aggregator); + + let aggregator = new(12, false); + assert!(destroy_optional_integer(aggregator) == 12, 0); + + let aggregator = new(21, true); + assert!(destroy_optional_aggregator(aggregator) == 21, 0); + } + + #[test(account = @aptos_framework)] + #[expected_failure(abort_code = 0x020001, location = Self)] + fun non_parallelizable_aggregator_overflow_test(account: signer) { + aggregator_factory::initialize_aggregator_factory(&account); + let aggregator = new(15, false); + + // Overflow! + add(&mut aggregator, 16); + + destroy(aggregator); + } + + #[test(account = @aptos_framework)] + #[expected_failure(abort_code = 0x020002, location = Self)] + fun non_parallelizable_aggregator_underflow_test(account: signer) { + aggregator_factory::initialize_aggregator_factory(&account); + let aggregator = new(100, false); + + // Underflow! + sub(&mut aggregator, 100); + add(&mut aggregator, 100); + + destroy(aggregator); + } + + #[test(account = @aptos_framework)] + #[expected_failure(abort_code = 0x020001, location = aptos_framework::aggregator)] + fun parallelizable_aggregator_overflow_test(account: signer) { + aggregator_factory::initialize_aggregator_factory(&account); + let aggregator = new(15, true); + + // Overflow! + add(&mut aggregator, 16); + + destroy(aggregator); + } + + #[test(account = @aptos_framework)] + #[expected_failure(abort_code = 0x020002, location = aptos_framework::aggregator)] + fun parallelizable_aggregator_underflow_test(account: signer) { + aggregator_factory::initialize_aggregator_factory(&account); + let aggregator = new(100, true); + + // Underflow! + add(&mut aggregator, 99); + sub(&mut aggregator, 100); + add(&mut aggregator, 100); + + destroy(aggregator); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/primary_fungible_store.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/primary_fungible_store.move new file mode 100644 index 000000000..fc20e1cf3 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/primary_fungible_store.move @@ -0,0 +1,405 @@ +/// This module provides a way for creators of fungible assets to enable support for creating primary (deterministic) +/// stores for their users. This is useful for assets that are meant to be used as a currency, as it allows users to +/// easily create a store for their account and deposit/withdraw/transfer fungible assets to/from it. +/// +/// The transfer flow works as below: +/// 1. The sender calls `transfer` on the fungible asset metadata object to transfer `amount` of fungible asset to +/// `recipient`. +/// 2. The fungible asset metadata object calls `ensure_primary_store_exists` to ensure that both the sender's and the +/// recipient's primary stores exist. If either doesn't, it will be created. +/// 3. The fungible asset metadata object calls `withdraw` on the sender's primary store to withdraw `amount` of +/// fungible asset from it. This emits a withdraw event. +/// 4. The fungible asset metadata object calls `deposit` on the recipient's primary store to deposit `amount` of +/// fungible asset to it. This emits an deposit event. +module aptos_framework::primary_fungible_store { + use aptos_framework::dispatchable_fungible_asset; + use aptos_framework::fungible_asset::{Self, FungibleAsset, FungibleStore, Metadata, MintRef, TransferRef, BurnRef}; + use aptos_framework::object::{Self, Object, ConstructorRef, DeriveRef}; + + use std::option::Option; + use std::signer; + use std::string::String; + + #[resource_group_member(group = aptos_framework::object::ObjectGroup)] + /// A resource that holds the derive ref for the fungible asset metadata object. This is used to create primary + /// stores for users with deterministic addresses so that users can easily deposit/withdraw/transfer fungible + /// assets. + struct DeriveRefPod has key { + metadata_derive_ref: DeriveRef, + } + + /// Create a fungible asset with primary store support. When users transfer fungible assets to each other, their + /// primary stores will be created automatically if they don't exist. Primary stores have deterministic addresses + /// so that users can easily deposit/withdraw/transfer fungible assets. + public fun create_primary_store_enabled_fungible_asset( + constructor_ref: &ConstructorRef, + maximum_supply: Option, + name: String, + symbol: String, + decimals: u8, + icon_uri: String, + project_uri: String, + ) { + fungible_asset::add_fungibility( + constructor_ref, + maximum_supply, + name, + symbol, + decimals, + icon_uri, + project_uri, + ); + let metadata_obj = &object::generate_signer(constructor_ref); + move_to(metadata_obj, DeriveRefPod { + metadata_derive_ref: object::generate_derive_ref(constructor_ref), + }); + } + + /// Ensure that the primary store object for the given address exists. If it doesn't, create it. + public fun ensure_primary_store_exists( + owner: address, + metadata: Object, + ): Object acquires DeriveRefPod { + let store_addr = primary_store_address(owner, metadata); + if (fungible_asset::store_exists(store_addr)) { + object::address_to_object(store_addr) + } else { + create_primary_store(owner, metadata) + } + } + + /// Create a primary store object to hold fungible asset for the given address. + public fun create_primary_store( + owner_addr: address, + metadata: Object, + ): Object acquires DeriveRefPod { + let metadata_addr = object::object_address(&metadata); + object::address_to_object(metadata_addr); + let derive_ref = &borrow_global(metadata_addr).metadata_derive_ref; + let constructor_ref = &object::create_user_derived_object(owner_addr, derive_ref); + // Disable ungated transfer as deterministic stores shouldn't be transferrable. + let transfer_ref = &object::generate_transfer_ref(constructor_ref); + object::disable_ungated_transfer(transfer_ref); + + fungible_asset::create_store(constructor_ref, metadata) + } + + #[view] + /// Get the address of the primary store for the given account. + public fun primary_store_address(owner: address, metadata: Object): address { + let metadata_addr = object::object_address(&metadata); + object::create_user_derived_object_address(owner, metadata_addr) + } + + #[view] + /// Get the primary store object for the given account. + public fun primary_store(owner: address, metadata: Object): Object { + let store = primary_store_address(owner, metadata); + object::address_to_object(store) + } + + #[view] + /// Return whether the given account's primary store exists. + public fun primary_store_exists(account: address, metadata: Object): bool { + fungible_asset::store_exists(primary_store_address(account, metadata)) + } + + /// Get the address of the primary store for the given account. + /// Use instead of the corresponding view functions for dispatchable hooks to avoid circular dependencies of modules. + public inline fun primary_store_address_inlined(owner: address, metadata: Object): address { + let metadata_addr = object::object_address(&metadata); + object::create_user_derived_object_address(owner, metadata_addr) + } + + /// Get the primary store object for the given account. + /// Use instead of the corresponding view functions for dispatchable hooks to avoid circular dependencies of modules. + public inline fun primary_store_inlined(owner: address, metadata: Object): Object { + let store = primary_store_address_inlined(owner, metadata); + object::address_to_object(store) + } + + /// Return whether the given account's primary store exists. + /// Use instead of the corresponding view functions for dispatchable hooks to avoid circular dependencies of modules. + public inline fun primary_store_exists_inlined(account: address, metadata: Object): bool { + fungible_asset::store_exists(primary_store_address_inlined(account, metadata)) + } + + #[view] + /// Get the balance of `account`'s primary store. + public fun balance(account: address, metadata: Object): u64 { + if (primary_store_exists(account, metadata)) { + fungible_asset::balance(primary_store(account, metadata)) + } else { + 0 + } + } + + #[view] + public fun is_balance_at_least(account: address, metadata: Object, amount: u64): bool { + if (primary_store_exists(account, metadata)) { + fungible_asset::is_balance_at_least(primary_store(account, metadata), amount) + } else { + amount == 0 + } + } + + #[view] + /// Return whether the given account's primary store is frozen. + public fun is_frozen(account: address, metadata: Object): bool { + if (primary_store_exists(account, metadata)) { + fungible_asset::is_frozen(primary_store(account, metadata)) + } else { + false + } + } + + /// Withdraw `amount` of fungible asset from the given account's primary store. + public fun withdraw(owner: &signer, metadata: Object, amount: u64): FungibleAsset acquires DeriveRefPod { + let store = ensure_primary_store_exists(signer::address_of(owner), metadata); + // Check if the store object has been burnt or not. If so, unburn it first. + may_be_unburn(owner, store); + dispatchable_fungible_asset::withdraw(owner, store, amount) + } + + /// Deposit fungible asset `fa` to the given account's primary store. + public fun deposit(owner: address, fa: FungibleAsset) acquires DeriveRefPod { + let metadata = fungible_asset::asset_metadata(&fa); + let store = ensure_primary_store_exists(owner, metadata); + dispatchable_fungible_asset::deposit(store, fa); + } + + /// Deposit fungible asset `fa` to the given account's primary store. + public(friend) fun force_deposit(owner: address, fa: FungibleAsset) acquires DeriveRefPod { + let metadata = fungible_asset::asset_metadata(&fa); + let store = ensure_primary_store_exists(owner, metadata); + fungible_asset::deposit_internal(object::object_address(&store), fa); + } + + /// Transfer `amount` of fungible asset from sender's primary store to receiver's primary store. + public entry fun transfer( + sender: &signer, + metadata: Object, + recipient: address, + amount: u64, + ) acquires DeriveRefPod { + let sender_store = ensure_primary_store_exists(signer::address_of(sender), metadata); + // Check if the sender store object has been burnt or not. If so, unburn it first. + may_be_unburn(sender, sender_store); + let recipient_store = ensure_primary_store_exists(recipient, metadata); + dispatchable_fungible_asset::transfer(sender, sender_store, recipient_store, amount); + } + + /// Transfer `amount` of fungible asset from sender's primary store to receiver's primary store. + /// Use the minimum deposit assertion api to make sure receipient will receive a minimum amount of fund. + public entry fun transfer_assert_minimum_deposit( + sender: &signer, + metadata: Object, + recipient: address, + amount: u64, + expected: u64, + ) acquires DeriveRefPod { + let sender_store = ensure_primary_store_exists(signer::address_of(sender), metadata); + // Check if the sender store object has been burnt or not. If so, unburn it first. + may_be_unburn(sender, sender_store); + let recipient_store = ensure_primary_store_exists(recipient, metadata); + dispatchable_fungible_asset::transfer_assert_minimum_deposit( + sender, + sender_store, + recipient_store, + amount, + expected + ); + } + + /// Mint to the primary store of `owner`. + public fun mint(mint_ref: &MintRef, owner: address, amount: u64) acquires DeriveRefPod { + let primary_store = ensure_primary_store_exists(owner, fungible_asset::mint_ref_metadata(mint_ref)); + fungible_asset::mint_to(mint_ref, primary_store, amount); + } + + /// Burn from the primary store of `owner`. + public fun burn(burn_ref: &BurnRef, owner: address, amount: u64) { + let primary_store = primary_store(owner, fungible_asset::burn_ref_metadata(burn_ref)); + fungible_asset::burn_from(burn_ref, primary_store, amount); + } + + /// Freeze/Unfreeze the primary store of `owner`. + public fun set_frozen_flag(transfer_ref: &TransferRef, owner: address, frozen: bool) acquires DeriveRefPod { + let primary_store = ensure_primary_store_exists(owner, fungible_asset::transfer_ref_metadata(transfer_ref)); + fungible_asset::set_frozen_flag(transfer_ref, primary_store, frozen); + } + + /// Withdraw from the primary store of `owner` ignoring frozen flag. + public fun withdraw_with_ref(transfer_ref: &TransferRef, owner: address, amount: u64): FungibleAsset { + let from_primary_store = primary_store(owner, fungible_asset::transfer_ref_metadata(transfer_ref)); + fungible_asset::withdraw_with_ref(transfer_ref, from_primary_store, amount) + } + + /// Deposit from the primary store of `owner` ignoring frozen flag. + public fun deposit_with_ref(transfer_ref: &TransferRef, owner: address, fa: FungibleAsset) acquires DeriveRefPod { + let from_primary_store = ensure_primary_store_exists( + owner, + fungible_asset::transfer_ref_metadata(transfer_ref) + ); + fungible_asset::deposit_with_ref(transfer_ref, from_primary_store, fa); + } + + /// Transfer `amount` of FA from the primary store of `from` to that of `to` ignoring frozen flag. + public fun transfer_with_ref( + transfer_ref: &TransferRef, + from: address, + to: address, + amount: u64 + ) acquires DeriveRefPod { + let from_primary_store = primary_store(from, fungible_asset::transfer_ref_metadata(transfer_ref)); + let to_primary_store = ensure_primary_store_exists(to, fungible_asset::transfer_ref_metadata(transfer_ref)); + fungible_asset::transfer_with_ref(transfer_ref, from_primary_store, to_primary_store, amount); + } + + fun may_be_unburn(owner: &signer, store: Object) { + if (object::is_burnt(store)) { + object::unburn(owner, store); + }; + } + + #[test_only] + use aptos_framework::fungible_asset::{ + create_test_token, + generate_mint_ref, + generate_burn_ref, + generate_transfer_ref + }; + #[test_only] + use std::string; + #[test_only] + use std::option; + + #[test_only] + public fun init_test_metadata_with_primary_store_enabled( + constructor_ref: &ConstructorRef + ): (MintRef, TransferRef, BurnRef) { + create_primary_store_enabled_fungible_asset( + constructor_ref, + option::some(100), // max supply + string::utf8(b"TEST COIN"), + string::utf8(b"@T"), + 0, + string::utf8(b"http://example.com/icon"), + string::utf8(b"http://example.com"), + ); + let mint_ref = generate_mint_ref(constructor_ref); + let burn_ref = generate_burn_ref(constructor_ref); + let transfer_ref = generate_transfer_ref(constructor_ref); + (mint_ref, transfer_ref, burn_ref) + } + + #[test(creator = @0xcafe, aaron = @0xface)] + fun test_default_behavior(creator: &signer, aaron: &signer) acquires DeriveRefPod { + let (creator_ref, metadata) = create_test_token(creator); + init_test_metadata_with_primary_store_enabled(&creator_ref); + let creator_address = signer::address_of(creator); + let aaron_address = signer::address_of(aaron); + assert!(!primary_store_exists(creator_address, metadata), 1); + assert!(!primary_store_exists(aaron_address, metadata), 2); + assert!(balance(creator_address, metadata) == 0, 3); + assert!(balance(aaron_address, metadata) == 0, 4); + assert!(!is_frozen(creator_address, metadata), 5); + assert!(!is_frozen(aaron_address, metadata), 6); + ensure_primary_store_exists(creator_address, metadata); + ensure_primary_store_exists(aaron_address, metadata); + assert!(primary_store_exists(creator_address, metadata), 7); + assert!(primary_store_exists(aaron_address, metadata), 8); + } + + #[test(creator = @0xcafe, aaron = @0xface)] + fun test_basic_flow( + creator: &signer, + aaron: &signer, + ) acquires DeriveRefPod { + let (creator_ref, metadata) = create_test_token(creator); + let (mint_ref, transfer_ref, burn_ref) = init_test_metadata_with_primary_store_enabled(&creator_ref); + let creator_address = signer::address_of(creator); + let aaron_address = signer::address_of(aaron); + assert!(balance(creator_address, metadata) == 0, 1); + assert!(balance(aaron_address, metadata) == 0, 2); + mint(&mint_ref, creator_address, 100); + transfer(creator, metadata, aaron_address, 80); + let fa = withdraw(aaron, metadata, 10); + deposit(creator_address, fa); + assert!(balance(creator_address, metadata) == 30, 3); + assert!(balance(aaron_address, metadata) == 70, 4); + set_frozen_flag(&transfer_ref, aaron_address, true); + assert!(is_frozen(aaron_address, metadata), 5); + let fa = withdraw_with_ref(&transfer_ref, aaron_address, 30); + deposit_with_ref(&transfer_ref, aaron_address, fa); + transfer_with_ref(&transfer_ref, aaron_address, creator_address, 20); + set_frozen_flag(&transfer_ref, aaron_address, false); + assert!(!is_frozen(aaron_address, metadata), 6); + burn(&burn_ref, aaron_address, 50); + assert!(balance(aaron_address, metadata) == 0, 7); + } + + #[test(creator = @0xcafe, aaron = @0xface)] + fun test_basic_flow_with_min_balance( + creator: &signer, + aaron: &signer, + ) acquires DeriveRefPod { + let (creator_ref, metadata) = create_test_token(creator); + let (mint_ref, _transfer_ref, _) = init_test_metadata_with_primary_store_enabled(&creator_ref); + let creator_address = signer::address_of(creator); + let aaron_address = signer::address_of(aaron); + assert!(balance(creator_address, metadata) == 0, 1); + assert!(balance(aaron_address, metadata) == 0, 2); + mint(&mint_ref, creator_address, 100); + transfer_assert_minimum_deposit(creator, metadata, aaron_address, 80, 80); + let fa = withdraw(aaron, metadata, 10); + deposit(creator_address, fa); + assert!(balance(creator_address, metadata) == 30, 3); + assert!(balance(aaron_address, metadata) == 70, 4); + } + + #[test(user_1 = @0xcafe, user_2 = @0xface)] + fun test_transfer_to_burnt_store( + user_1: &signer, + user_2: &signer, + ) acquires DeriveRefPod { + let (creator_ref, metadata) = create_test_token(user_1); + let (mint_ref, _, _) = init_test_metadata_with_primary_store_enabled(&creator_ref); + let user_1_address = signer::address_of(user_1); + let user_2_address = signer::address_of(user_2); + mint(&mint_ref, user_1_address, 100); + transfer(user_1, metadata, user_2_address, 80); + + // User 2 burns their primary store but should still be able to transfer afterward. + let user_2_primary_store = primary_store(user_2_address, metadata); + object::burn(user_2, user_2_primary_store); + assert!(object::is_burnt(user_2_primary_store), 0); + // Balance still works + assert!(balance(user_2_address, metadata) == 80, 0); + // Deposit still works + transfer(user_1, metadata, user_2_address, 20); + transfer(user_2, metadata, user_1_address, 90); + assert!(balance(user_2_address, metadata) == 10, 0); + } + + #[test(user_1 = @0xcafe, user_2 = @0xface)] + fun test_withdraw_from_burnt_store( + user_1: &signer, + user_2: &signer, + ) acquires DeriveRefPod { + let (creator_ref, metadata) = create_test_token(user_1); + let (mint_ref, _, _) = init_test_metadata_with_primary_store_enabled(&creator_ref); + let user_1_address = signer::address_of(user_1); + let user_2_address = signer::address_of(user_2); + mint(&mint_ref, user_1_address, 100); + transfer(user_1, metadata, user_2_address, 80); + + // User 2 burns their primary store but should still be able to withdraw afterward. + let user_2_primary_store = primary_store(user_2_address, metadata); + object::burn(user_2, user_2_primary_store); + assert!(object::is_burnt(user_2_primary_store), 0); + let coins = withdraw(user_2, metadata, 70); + assert!(balance(user_2_address, metadata) == 10, 0); + deposit(user_2_address, coins); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/randomness.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/randomness.move new file mode 100644 index 000000000..e479b6e30 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/randomness.move @@ -0,0 +1,574 @@ +/// This module provides access to *instant* secure randomness generated by the Aptos validators, as documented in +/// [AIP-41](https://github.com/aptos-foundation/AIPs/blob/main/aips/aip-41.md). +/// +/// Secure randomness means (1) the randomness cannot be predicted ahead of time by validators, developers or users +/// and (2) the randomness cannot be biased in any way by validators, developers or users. +/// +/// Security holds under the same proof-of-stake assumption that secures the Aptos network. +module aptos_framework::randomness { + use std::hash; + use std::option; + use std::option::Option; + use std::vector; + use aptos_framework::event; + use aptos_framework::system_addresses; + use aptos_framework::transaction_context; + #[test_only] + use aptos_std::debug; + #[test_only] + use aptos_std::table_with_length; + + friend aptos_framework::block; + + const DST: vector = b"APTOS_RANDOMNESS"; + + /// Randomness APIs calls must originate from a private entry function with + /// `#[randomness]` annotation. Otherwise, malicious users can bias randomness result. + const E_API_USE_IS_BIASIBLE: u64 = 1; + + const MAX_U256: u256 = 115792089237316195423570985008687907853269984665640564039457584007913129639935; + + /// 32-byte randomness seed unique to every block. + /// This resource is updated in every block prologue. + struct PerBlockRandomness has drop, key { + epoch: u64, + round: u64, + seed: Option>, + } + + #[event] + /// Event emitted every time a public randomness API in this module is called. + struct RandomnessGeneratedEvent has store, drop { + } + + /// Called in genesis.move. + /// Must be called in tests to initialize the `PerBlockRandomness` resource. + public fun initialize(framework: &signer) { + system_addresses::assert_aptos_framework(framework); + if (!exists(@aptos_framework)) { + move_to(framework, PerBlockRandomness { + epoch: 0, + round: 0, + seed: option::none(), + }); + } + } + + #[test_only] + public fun initialize_for_testing(framework: &signer) acquires PerBlockRandomness { + initialize(framework); + set_seed(x"0000000000000000000000000000000000000000000000000000000000000000"); + } + + /// Invoked in block prologues to update the block-level randomness seed. + public(friend) fun on_new_block(vm: &signer, epoch: u64, round: u64, seed_for_new_block: Option>) acquires PerBlockRandomness { + system_addresses::assert_vm(vm); + if (exists(@aptos_framework)) { + let randomness = borrow_global_mut(@aptos_framework); + randomness.epoch = epoch; + randomness.round = round; + randomness.seed = seed_for_new_block; + } + } + + /// Generate the next 32 random bytes. Repeated calls will yield different results (assuming the collision-resistance + /// of the hash function). + fun next_32_bytes(): vector acquires PerBlockRandomness { + assert!(is_unbiasable(), E_API_USE_IS_BIASIBLE); + + let input = DST; + let randomness = borrow_global(@aptos_framework); + let seed = *option::borrow(&randomness.seed); + + vector::append(&mut input, seed); + vector::append(&mut input, transaction_context::get_transaction_hash()); + vector::append(&mut input, fetch_and_increment_txn_counter()); + hash::sha3_256(input) + } + + /// Generates a sequence of bytes uniformly at random + public fun bytes(n: u64): vector acquires PerBlockRandomness { + let v = vector[]; + let c = 0; + while (c < n) { + let blob = next_32_bytes(); + vector::append(&mut v, blob); + + c = c + 32; + }; + + if (c > n) { + vector::trim(&mut v, n); + }; + + event::emit(RandomnessGeneratedEvent {}); + + v + } + + /// Generates an u8 uniformly at random. + public fun u8_integer(): u8 acquires PerBlockRandomness { + let raw = next_32_bytes(); + let ret: u8 = vector::pop_back(&mut raw); + + event::emit(RandomnessGeneratedEvent {}); + + ret + } + + /// Generates an u16 uniformly at random. + public fun u16_integer(): u16 acquires PerBlockRandomness { + let raw = next_32_bytes(); + let i = 0; + let ret: u16 = 0; + while (i < 2) { + ret = ret * 256 + (vector::pop_back(&mut raw) as u16); + i = i + 1; + }; + + event::emit(RandomnessGeneratedEvent {}); + + ret + } + + /// Generates an u32 uniformly at random. + public fun u32_integer(): u32 acquires PerBlockRandomness { + let raw = next_32_bytes(); + let i = 0; + let ret: u32 = 0; + while (i < 4) { + ret = ret * 256 + (vector::pop_back(&mut raw) as u32); + i = i + 1; + }; + + event::emit(RandomnessGeneratedEvent {}); + + ret + } + + /// Generates an u64 uniformly at random. + public fun u64_integer(): u64 acquires PerBlockRandomness { + let raw = next_32_bytes(); + let i = 0; + let ret: u64 = 0; + while (i < 8) { + ret = ret * 256 + (vector::pop_back(&mut raw) as u64); + i = i + 1; + }; + + event::emit(RandomnessGeneratedEvent {}); + + ret + } + + /// Generates an u128 uniformly at random. + public fun u128_integer(): u128 acquires PerBlockRandomness { + let raw = next_32_bytes(); + let i = 0; + let ret: u128 = 0; + while (i < 16) { + ret = ret * 256 + (vector::pop_back(&mut raw) as u128); + i = i + 1; + }; + + event::emit(RandomnessGeneratedEvent {}); + + ret + } + + /// Generates a u256 uniformly at random. + public fun u256_integer(): u256 acquires PerBlockRandomness { + event::emit(RandomnessGeneratedEvent {}); + u256_integer_internal() + } + + /// Generates a u256 uniformly at random. + fun u256_integer_internal(): u256 acquires PerBlockRandomness { + let raw = next_32_bytes(); + let i = 0; + let ret: u256 = 0; + while (i < 32) { + ret = ret * 256 + (vector::pop_back(&mut raw) as u256); + i = i + 1; + }; + ret + } + + /// Generates a number $n \in [min_incl, max_excl)$ uniformly at random. + /// + /// NOTE: The uniformity is not perfect, but it can be proved that the bias is negligible. + /// If you need perfect uniformity, consider implement your own via rejection sampling. + public fun u8_range(min_incl: u8, max_excl: u8): u8 acquires PerBlockRandomness { + let range = ((max_excl - min_incl) as u256); + let sample = ((u256_integer_internal() % range) as u8); + + event::emit(RandomnessGeneratedEvent {}); + + min_incl + sample + } + + /// Generates a number $n \in [min_incl, max_excl)$ uniformly at random. + /// + /// NOTE: The uniformity is not perfect, but it can be proved that the bias is negligible. + /// If you need perfect uniformity, consider implement your own via rejection sampling. + public fun u16_range(min_incl: u16, max_excl: u16): u16 acquires PerBlockRandomness { + let range = ((max_excl - min_incl) as u256); + let sample = ((u256_integer_internal() % range) as u16); + + event::emit(RandomnessGeneratedEvent {}); + + min_incl + sample + } + + /// Generates a number $n \in [min_incl, max_excl)$ uniformly at random. + /// + /// NOTE: The uniformity is not perfect, but it can be proved that the bias is negligible. + /// If you need perfect uniformity, consider implement your own via rejection sampling. + public fun u32_range(min_incl: u32, max_excl: u32): u32 acquires PerBlockRandomness { + let range = ((max_excl - min_incl) as u256); + let sample = ((u256_integer_internal() % range) as u32); + + event::emit(RandomnessGeneratedEvent {}); + + min_incl + sample + } + + /// Generates a number $n \in [min_incl, max_excl)$ uniformly at random. + /// + /// NOTE: The uniformity is not perfect, but it can be proved that the bias is negligible. + /// If you need perfect uniformity, consider implement your own via rejection sampling. + public fun u64_range(min_incl: u64, max_excl: u64): u64 acquires PerBlockRandomness { + event::emit(RandomnessGeneratedEvent {}); + + u64_range_internal(min_incl, max_excl) + } + + public fun u64_range_internal(min_incl: u64, max_excl: u64): u64 acquires PerBlockRandomness { + let range = ((max_excl - min_incl) as u256); + let sample = ((u256_integer_internal() % range) as u64); + + min_incl + sample + } + + /// Generates a number $n \in [min_incl, max_excl)$ uniformly at random. + /// + /// NOTE: The uniformity is not perfect, but it can be proved that the bias is negligible. + /// If you need perfect uniformity, consider implement your own via rejection sampling. + public fun u128_range(min_incl: u128, max_excl: u128): u128 acquires PerBlockRandomness { + let range = ((max_excl - min_incl) as u256); + let sample = ((u256_integer_internal() % range) as u128); + + event::emit(RandomnessGeneratedEvent {}); + + min_incl + sample + } + + /// Generates a number $n \in [min_incl, max_excl)$ uniformly at random. + /// + /// NOTE: The uniformity is not perfect, but it can be proved that the bias is negligible. + /// If you need perfect uniformity, consider implement your own with `u256_integer()` + rejection sampling. + public fun u256_range(min_incl: u256, max_excl: u256): u256 acquires PerBlockRandomness { + let range = max_excl - min_incl; + let r0 = u256_integer_internal(); + let r1 = u256_integer_internal(); + + // Will compute sample := (r0 + r1*2^256) % range. + + let sample = r1 % range; + let i = 0; + while ({ + spec { + invariant sample >= 0 && sample < max_excl - min_incl; + }; + i < 256 + }) { + sample = safe_add_mod(sample, sample, range); + i = i + 1; + }; + + let sample = safe_add_mod(sample, r0 % range, range); + spec { + assert sample >= 0 && sample < max_excl - min_incl; + }; + + event::emit(RandomnessGeneratedEvent {}); + + min_incl + sample + } + + /// Generate a permutation of `[0, 1, ..., n-1]` uniformly at random. + /// If n is 0, returns the empty vector. + public fun permutation(n: u64): vector acquires PerBlockRandomness { + let values = vector[]; + + if(n == 0) { + return vector[] + }; + + // Initialize into [0, 1, ..., n-1]. + let i = 0; + while ({ + spec { + invariant i <= n; + invariant len(values) == i; + }; + i < n + }) { + std::vector::push_back(&mut values, i); + i = i + 1; + }; + spec { + assert len(values) == n; + }; + + // Shuffle. + let tail = n - 1; + while ({ + spec { + invariant tail >= 0 && tail < len(values); + }; + tail > 0 + }) { + let pop_position = u64_range_internal(0, tail + 1); + spec { + assert pop_position < len(values); + }; + std::vector::swap(&mut values, pop_position, tail); + tail = tail - 1; + }; + + event::emit(RandomnessGeneratedEvent {}); + + values + } + + #[test_only] + public fun set_seed(seed: vector) acquires PerBlockRandomness { + assert!(vector::length(&seed) == 32, 0); + let randomness = borrow_global_mut(@aptos_framework); + randomness.seed = option::some(seed); + } + + /// Compute `(a + b) % m`, assuming `m >= 1, 0 <= a < m, 0<= b < m`. + inline fun safe_add_mod(a: u256, b: u256, m: u256): u256 { + let neg_b = m - b; + if (a < neg_b) { + a + b + } else { + a - neg_b + } + } + + #[verify_only] + fun safe_add_mod_for_verification(a: u256, b: u256, m: u256): u256 { + let neg_b = m - b; + if (a < neg_b) { + a + b + } else { + a - neg_b + } + } + + /// Fetches and increments a transaction-specific 32-byte randomness-related counter. + /// Aborts with `E_API_USE_SUSCEPTIBLE_TO_TEST_AND_ABORT` if randomness is not unbiasable. + native fun fetch_and_increment_txn_counter(): vector; + + /// Called in each randomness generation function to ensure certain safety invariants, namely: + /// 1. The transaction that led to the call of this function had a private (or friend) entry + /// function as its payload. + /// 2. The entry function had `#[randomness]` annotation. + native fun is_unbiasable(): bool; + + #[test] + fun test_safe_add_mod() { + assert!(2 == safe_add_mod(3, 4, 5), 1); + assert!(2 == safe_add_mod(4, 3, 5), 1); + assert!(7 == safe_add_mod(3, 4, 9), 1); + assert!(7 == safe_add_mod(4, 3, 9), 1); + assert!(0xfffffffffffffffffffffffffffffffffffffffffffffffe == safe_add_mod(0xfffffffffffffffffffffffffffffffffffffffffffffffd, 0x000000000000000000000000000000000000000000000001, 0xffffffffffffffffffffffffffffffffffffffffffffffff), 1); + assert!(0xfffffffffffffffffffffffffffffffffffffffffffffffe == safe_add_mod(0x000000000000000000000000000000000000000000000001, 0xfffffffffffffffffffffffffffffffffffffffffffffffd, 0xffffffffffffffffffffffffffffffffffffffffffffffff), 1); + assert!(0x000000000000000000000000000000000000000000000000 == safe_add_mod(0xfffffffffffffffffffffffffffffffffffffffffffffffd, 0x000000000000000000000000000000000000000000000002, 0xffffffffffffffffffffffffffffffffffffffffffffffff), 1); + assert!(0x000000000000000000000000000000000000000000000000 == safe_add_mod(0x000000000000000000000000000000000000000000000002, 0xfffffffffffffffffffffffffffffffffffffffffffffffd, 0xffffffffffffffffffffffffffffffffffffffffffffffff), 1); + assert!(0x000000000000000000000000000000000000000000000001 == safe_add_mod(0xfffffffffffffffffffffffffffffffffffffffffffffffd, 0x000000000000000000000000000000000000000000000003, 0xffffffffffffffffffffffffffffffffffffffffffffffff), 1); + assert!(0x000000000000000000000000000000000000000000000001 == safe_add_mod(0x000000000000000000000000000000000000000000000003, 0xfffffffffffffffffffffffffffffffffffffffffffffffd, 0xffffffffffffffffffffffffffffffffffffffffffffffff), 1); + assert!(0xfffffffffffffffffffffffffffffffffffffffffffffffd == safe_add_mod(0xfffffffffffffffffffffffffffffffffffffffffffffffe, 0xfffffffffffffffffffffffffffffffffffffffffffffffe, 0xffffffffffffffffffffffffffffffffffffffffffffffff), 1); + } + + #[test(fx = @aptos_framework)] + fun randomness_smoke_test(fx: signer) acquires PerBlockRandomness { + initialize(&fx); + set_seed(x"0000000000000000000000000000000000000000000000000000000000000000"); + // Test cases should always have no bias for any randomness call. + assert!(is_unbiasable(), 0); + let num = u64_integer(); + debug::print(&num); + } + + #[test_only] + fun assert_event_count_equals(count: u64) { + let events = event::emitted_events(); + assert!(vector::length(&events) == count, 0); + } + + #[test(fx = @aptos_framework)] + fun test_emit_events(fx: signer) acquires PerBlockRandomness { + initialize_for_testing(&fx); + + let c = 0; + assert_event_count_equals(c); + + let _ = bytes(1); + c = c + 1; + assert_event_count_equals(c); + + let _ = u8_integer(); + c = c + 1; + assert_event_count_equals(c); + + let _ = u16_integer(); + c = c + 1; + assert_event_count_equals(c); + + let _ = u32_integer(); + c = c + 1; + assert_event_count_equals(c); + + let _ = u64_integer(); + c = c + 1; + assert_event_count_equals(c); + + let _ = u128_integer(); + c = c + 1; + assert_event_count_equals(c); + + let _ = u256_integer(); + c = c + 1; + assert_event_count_equals(c); + + let _ = u8_range(0, 255); + c = c + 1; + assert_event_count_equals(c); + + let _ = u16_range(0, 255); + c = c + 1; + assert_event_count_equals(c); + + let _ = u32_range(0, 255); + c = c + 1; + assert_event_count_equals(c); + + let _ = u64_range(0, 255); + c = c + 1; + assert_event_count_equals(c); + + let _ = u128_range(0, 255); + c = c + 1; + assert_event_count_equals(c); + + let _ = u256_range(0, 255); + c = c + 1; + assert_event_count_equals(c); + + let _ = permutation(6); + c = c + 1; + assert_event_count_equals(c); + } + + #[test(fx = @aptos_framework)] + fun test_bytes(fx: signer) acquires PerBlockRandomness { + initialize_for_testing(&fx); + + let v = bytes(0); + assert!(vector::length(&v) == 0, 0); + + let v = bytes(1); + assert!(vector::length(&v) == 1, 0); + let v = bytes(2); + assert!(vector::length(&v) == 2, 0); + let v = bytes(3); + assert!(vector::length(&v) == 3, 0); + let v = bytes(4); + assert!(vector::length(&v) == 4, 0); + let v = bytes(30); + assert!(vector::length(&v) == 30, 0); + let v = bytes(31); + assert!(vector::length(&v) == 31, 0); + let v = bytes(32); + assert!(vector::length(&v) == 32, 0); + + let v = bytes(33); + assert!(vector::length(&v) == 33, 0); + let v = bytes(50); + assert!(vector::length(&v) == 50, 0); + let v = bytes(63); + assert!(vector::length(&v) == 63, 0); + let v = bytes(64); + assert!(vector::length(&v) == 64, 0); + } + + #[test_only] + fun is_permutation(v: &vector): bool { + let present = vector[]; + + // Mark all elements from 0 to n-1 as not present + let n = vector::length(v); + for (i in 0..n) { + vector::push_back(&mut present, false); + }; + + for (i in 0..n) { + let e = vector::borrow(v, i); + let bit = vector::borrow_mut(&mut present, *e); + *bit = true; + }; + + for (i in 0..n) { + let bit = vector::borrow(&present, i); + if(*bit == false) { + return false + }; + }; + + true + } + + #[test(fx = @aptos_framework)] + fun test_permutation(fx: signer) acquires PerBlockRandomness { + initialize_for_testing(&fx); + + let v = permutation(0); + assert!(vector::length(&v) == 0, 0); + + test_permutation_internal(1); + test_permutation_internal(2); + test_permutation_internal(3); + test_permutation_internal(4); + } + + #[test_only] + /// WARNING: Do not call this with a large `size`, since execution time will be \Omega(size!), where ! is the factorial + /// operator. + fun test_permutation_internal(size: u64) acquires PerBlockRandomness { + let num_permutations = 1; + let c = 1; + for (i in 0..size) { + num_permutations = num_permutations * c; + c = c + 1; + }; + + let permutations = table_with_length::new, bool>(); + + // This loop will not exit until all permutations are created + while(table_with_length::length(&permutations) < num_permutations) { + let v = permutation(size); + assert!(vector::length(&v) == size, 0); + assert!(is_permutation(&v), 0); + + if(table_with_length::contains(&permutations, v) == false) { + table_with_length::add(&mut permutations, v, true); + } + }; + + table_with_length::drop_unchecked(permutations); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/randomness_api_v0_config.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/randomness_api_v0_config.move new file mode 100644 index 000000000..28466211d --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/randomness_api_v0_config.move @@ -0,0 +1,57 @@ +module aptos_framework::randomness_api_v0_config { + use std::option::Option; + use aptos_framework::chain_status; + use aptos_framework::config_buffer; + use aptos_framework::system_addresses; + friend aptos_framework::reconfiguration_with_dkg; + + struct RequiredGasDeposit has key, drop, store { + gas_amount: Option, + } + + /// If this flag is set, `max_gas` specified inside `#[randomness()]` will be used as the required deposit. + struct AllowCustomMaxGasFlag has key, drop, store { + value: bool, + } + + /// Only used in genesis. + fun initialize(framework: &signer, required_amount: RequiredGasDeposit, allow_custom_max_gas_flag: AllowCustomMaxGasFlag) { + system_addresses::assert_aptos_framework(framework); + chain_status::assert_genesis(); + move_to(framework, required_amount); + move_to(framework, allow_custom_max_gas_flag); + } + + /// This can be called by on-chain governance to update `RequiredGasDeposit` for the next epoch. + public fun set_for_next_epoch(framework: &signer, gas_amount: Option) { + system_addresses::assert_aptos_framework(framework); + config_buffer::upsert(RequiredGasDeposit { gas_amount }); + } + + /// This can be called by on-chain governance to update `AllowCustomMaxGasFlag` for the next epoch. + public fun set_allow_max_gas_flag_for_next_epoch(framework: &signer, value: bool) { + system_addresses::assert_aptos_framework(framework); + config_buffer::upsert(AllowCustomMaxGasFlag { value } ); + } + + /// Only used in reconfigurations to apply the pending `RequiredGasDeposit`, if there is any. + public fun on_new_epoch(framework: &signer) acquires RequiredGasDeposit, AllowCustomMaxGasFlag { + system_addresses::assert_aptos_framework(framework); + if (config_buffer::does_exist()) { + let new_config = config_buffer::extract(); + if (exists(@aptos_framework)) { + *borrow_global_mut(@aptos_framework) = new_config; + } else { + move_to(framework, new_config); + } + }; + if (config_buffer::does_exist()) { + let new_config = config_buffer::extract(); + if (exists(@aptos_framework)) { + *borrow_global_mut(@aptos_framework) = new_config; + } else { + move_to(framework, new_config); + } + } + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/randomness_config.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/randomness_config.move new file mode 100644 index 000000000..24916393e --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/randomness_config.move @@ -0,0 +1,153 @@ +/// Structs and functions for on-chain randomness configurations. +module aptos_framework::randomness_config { + use std::string; + use aptos_std::copyable_any; + use aptos_std::copyable_any::Any; + use aptos_std::fixed_point64::FixedPoint64; + use aptos_framework::config_buffer; + use aptos_framework::system_addresses; + + friend aptos_framework::reconfiguration_with_dkg; + + const EINVALID_CONFIG_VARIANT: u64 = 1; + + /// The configuration of the on-chain randomness feature. + struct RandomnessConfig has copy, drop, key, store { + /// A config variant packed as an `Any`. + /// Currently the variant type is one of the following. + /// - `ConfigOff` + /// - `ConfigV1` + variant: Any, + } + + /// A randomness config variant indicating the feature is disabled. + struct ConfigOff has copy, drop, store {} + + /// A randomness config variant indicating the feature is enabled. + struct ConfigV1 has copy, drop, store { + /// Any validator subset should not be able to reconstruct randomness if `subset_power / total_power <= secrecy_threshold`, + secrecy_threshold: FixedPoint64, + /// Any validator subset should be able to reconstruct randomness if `subset_power / total_power > reconstruction_threshold`. + reconstruction_threshold: FixedPoint64, + } + + /// A randomness config variant indicating the feature is enabled with fast path. + struct ConfigV2 has copy, drop, store { + /// Any validator subset should not be able to reconstruct randomness if `subset_power / total_power <= secrecy_threshold`, + secrecy_threshold: FixedPoint64, + /// Any validator subset should be able to reconstruct randomness if `subset_power / total_power > reconstruction_threshold`. + reconstruction_threshold: FixedPoint64, + /// Any validator subset should not be able to reconstruct randomness via the fast path if `subset_power / total_power <= fast_path_secrecy_threshold`, + fast_path_secrecy_threshold: FixedPoint64, + } + + /// Initialize the configuration. Used in genesis or governance. + public fun initialize(framework: &signer, config: RandomnessConfig) { + system_addresses::assert_aptos_framework(framework); + if (!exists(@aptos_framework)) { + move_to(framework, config) + } + } + + /// This can be called by on-chain governance to update on-chain consensus configs for the next epoch. + public fun set_for_next_epoch(framework: &signer, new_config: RandomnessConfig) { + system_addresses::assert_aptos_framework(framework); + config_buffer::upsert(new_config); + } + + /// Only used in reconfigurations to apply the pending `RandomnessConfig`, if there is any. + public(friend) fun on_new_epoch(framework: &signer) acquires RandomnessConfig { + system_addresses::assert_aptos_framework(framework); + if (config_buffer::does_exist()) { + let new_config = config_buffer::extract(); + if (exists(@aptos_framework)) { + *borrow_global_mut(@aptos_framework) = new_config; + } else { + move_to(framework, new_config); + } + } + } + + /// Check whether on-chain randomness main logic (e.g., `DKGManager`, `RandManager`, `BlockMetadataExt`) is enabled. + /// + /// NOTE: this returning true does not mean randomness will run. + /// The feature works if and only if `consensus_config::validator_txn_enabled() && randomness_config::enabled()`. + public fun enabled(): bool acquires RandomnessConfig { + if (exists(@aptos_framework)) { + let config = borrow_global(@aptos_framework); + let variant_type_name = *string::bytes(copyable_any::type_name(&config.variant)); + variant_type_name != b"0x1::randomness_config::ConfigOff" + } else { + false + } + } + + /// Create a `ConfigOff` variant. + public fun new_off(): RandomnessConfig { + RandomnessConfig { + variant: copyable_any::pack( ConfigOff {} ) + } + } + + /// Create a `ConfigV1` variant. + public fun new_v1(secrecy_threshold: FixedPoint64, reconstruction_threshold: FixedPoint64): RandomnessConfig { + RandomnessConfig { + variant: copyable_any::pack( ConfigV1 { + secrecy_threshold, + reconstruction_threshold + } ) + } + } + + /// Create a `ConfigV2` variant. + public fun new_v2( + secrecy_threshold: FixedPoint64, + reconstruction_threshold: FixedPoint64, + fast_path_secrecy_threshold: FixedPoint64, + ): RandomnessConfig { + RandomnessConfig { + variant: copyable_any::pack( ConfigV2 { + secrecy_threshold, + reconstruction_threshold, + fast_path_secrecy_threshold, + } ) + } + } + + /// Get the currently effective randomness configuration object. + public fun current(): RandomnessConfig acquires RandomnessConfig { + if (exists(@aptos_framework)) { + *borrow_global(@aptos_framework) + } else { + new_off() + } + } + + #[test_only] + use aptos_std::fixed_point64; + + #[test_only] + fun initialize_for_testing(framework: &signer) { + config_buffer::initialize(framework); + initialize(framework, new_off()); + } + + #[test(framework = @0x1)] + fun init_buffer_apply(framework: signer) acquires RandomnessConfig { + initialize_for_testing(&framework); + + // Enabling. + let config = new_v1( + fixed_point64::create_from_rational(1, 2), + fixed_point64::create_from_rational(2, 3) + ); + set_for_next_epoch(&framework, config); + on_new_epoch(&framework); + assert!(enabled(), 1); + + // Disabling. + set_for_next_epoch(&framework, new_off()); + on_new_epoch(&framework); + assert!(!enabled(), 2); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/randomness_config_seqnum.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/randomness_config_seqnum.move new file mode 100644 index 000000000..174b7fdda --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/randomness_config_seqnum.move @@ -0,0 +1,49 @@ +/// Randomness stall recovery utils. +/// +/// When randomness generation is stuck due to a bug, the chain is also stuck. Below is the recovery procedure. +/// 1. Ensure more than 2/3 stakes are stuck at the same version. +/// 1. Every validator restarts with `randomness_override_seq_num` set to `X+1` in the node config file, +/// where `X` is the current `RandomnessConfigSeqNum` on chain. +/// 1. The chain should then be unblocked. +/// 1. Once the bug is fixed and the binary + framework have been patched, +/// a governance proposal is needed to set `RandomnessConfigSeqNum` to be `X+2`. +module aptos_framework::randomness_config_seqnum { + use aptos_framework::config_buffer; + use aptos_framework::system_addresses; + + friend aptos_framework::reconfiguration_with_dkg; + + /// If this seqnum is smaller than a validator local override, the on-chain `RandomnessConfig` will be ignored. + /// Useful in a chain recovery from randomness stall. + struct RandomnessConfigSeqNum has drop, key, store { + seq_num: u64, + } + + /// Update `RandomnessConfigSeqNum`. + /// Used when re-enable randomness after an emergency randomness disable via local override. + public fun set_for_next_epoch(framework: &signer, seq_num: u64) { + system_addresses::assert_aptos_framework(framework); + config_buffer::upsert(RandomnessConfigSeqNum { seq_num }); + } + + /// Initialize the configuration. Used in genesis or governance. + public fun initialize(framework: &signer) { + system_addresses::assert_aptos_framework(framework); + if (!exists(@aptos_framework)) { + move_to(framework, RandomnessConfigSeqNum { seq_num: 0 }) + } + } + + /// Only used in reconfigurations to apply the pending `RandomnessConfig`, if there is any. + public(friend) fun on_new_epoch(framework: &signer) acquires RandomnessConfigSeqNum { + system_addresses::assert_aptos_framework(framework); + if (config_buffer::does_exist()) { + let new_config = config_buffer::extract(); + if (exists(@aptos_framework)) { + *borrow_global_mut(@aptos_framework) = new_config; + } else { + move_to(framework, new_config); + } + } + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/reconfiguration.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/reconfiguration.move new file mode 100644 index 000000000..04a48b646 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/reconfiguration.move @@ -0,0 +1,237 @@ +/// Publishes configuration information for validators, and issues reconfiguration events +/// to synchronize configuration changes for the validators. +module aptos_framework::reconfiguration { + use std::error; + use std::features; + use std::signer; + + use aptos_framework::account; + use aptos_framework::event; + use aptos_framework::stake; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + use aptos_framework::chain_status; + use aptos_framework::reconfiguration_state; + use aptos_framework::storage_gas; + use aptos_framework::transaction_fee; + + friend aptos_framework::aptos_governance; + friend aptos_framework::block; + friend aptos_framework::consensus_config; + friend aptos_framework::execution_config; + friend aptos_framework::gas_schedule; + friend aptos_framework::genesis; + friend aptos_framework::version; + friend aptos_framework::reconfiguration_with_dkg; + + #[event] + /// Event that signals consensus to start a new epoch, + /// with new configuration information. This is also called a + /// "reconfiguration event" + struct NewEpochEvent has drop, store { + epoch: u64, + } + + #[event] + /// Event that signals consensus to start a new epoch, + /// with new configuration information. This is also called a + /// "reconfiguration event" + struct NewEpoch has drop, store { + epoch: u64, + } + + /// Holds information about state of reconfiguration + struct Configuration has key { + /// Epoch number + epoch: u64, + /// Time of last reconfiguration. Only changes on reconfiguration events. + last_reconfiguration_time: u64, + /// Event handle for reconfiguration events + events: event::EventHandle, + } + + /// Reconfiguration will be disabled if this resource is published under the + /// aptos_framework system address + struct DisableReconfiguration has key {} + + /// The `Configuration` resource is in an invalid state + const ECONFIGURATION: u64 = 1; + /// A `Reconfiguration` resource is in an invalid state + const ECONFIG: u64 = 2; + /// A `ModifyConfigCapability` is in a different state than was expected + const EMODIFY_CAPABILITY: u64 = 3; + /// An invalid block time was encountered. + const EINVALID_BLOCK_TIME: u64 = 4; + /// An invalid block time was encountered. + const EINVALID_GUID_FOR_EVENT: u64 = 5; + + /// Only called during genesis. + /// Publishes `Configuration` resource. Can only be invoked by aptos framework account, and only a single time in Genesis. + public(friend) fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + + // assert it matches `new_epoch_event_key()`, otherwise the event can't be recognized + assert!(account::get_guid_next_creation_num(signer::address_of(aptos_framework)) == 2, error::invalid_state(EINVALID_GUID_FOR_EVENT)); + move_to( + aptos_framework, + Configuration { + epoch: 0, + last_reconfiguration_time: 0, + events: account::new_event_handle(aptos_framework), + } + ); + } + + /// Private function to temporarily halt reconfiguration. + /// This function should only be used for offline WriteSet generation purpose and should never be invoked on chain. + fun disable_reconfiguration(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(reconfiguration_enabled(), error::invalid_state(ECONFIGURATION)); + move_to(aptos_framework, DisableReconfiguration {}) + } + + /// Private function to resume reconfiguration. + /// This function should only be used for offline WriteSet generation purpose and should never be invoked on chain. + fun enable_reconfiguration(aptos_framework: &signer) acquires DisableReconfiguration { + system_addresses::assert_aptos_framework(aptos_framework); + + assert!(!reconfiguration_enabled(), error::invalid_state(ECONFIGURATION)); + DisableReconfiguration {} = move_from(signer::address_of(aptos_framework)); + } + + fun reconfiguration_enabled(): bool { + !exists(@aptos_framework) + } + + /// Signal validators to start using new configuration. Must be called from friend config modules. + public(friend) fun reconfigure() acquires Configuration { + // Do not do anything if genesis has not finished. + if (chain_status::is_genesis() || timestamp::now_microseconds() == 0 || !reconfiguration_enabled()) { + return + }; + + let config_ref = borrow_global_mut(@aptos_framework); + let current_time = timestamp::now_microseconds(); + + // Do not do anything if a reconfiguration event is already emitted within this transaction. + // + // This is OK because: + // - The time changes in every non-empty block + // - A block automatically ends after a transaction that emits a reconfiguration event, which is guaranteed by + // VM spec that all transactions comming after a reconfiguration transaction will be returned as Retry + // status. + // - Each transaction must emit at most one reconfiguration event + // + // Thus, this check ensures that a transaction that does multiple "reconfiguration required" actions emits only + // one reconfiguration event. + // + if (current_time == config_ref.last_reconfiguration_time) { + return + }; + + reconfiguration_state::on_reconfig_start(); + + // Reconfiguration "forces the block" to end, as mentioned above. Therefore, we must process the collected fees + // explicitly so that staking can distribute them. + // + // This also handles the case when a validator is removed due to the governance proposal. In particular, removing + // the validator causes a reconfiguration. We explicitly process fees, i.e. we drain aggregatable coin and populate + // the fees table, prior to calling `on_new_epoch()`. That call, in turn, distributes transaction fees for all active + // and pending_inactive validators, which include any validator that is to be removed. + if (features::collect_and_distribute_gas_fees()) { + // All transactions after reconfiguration are Retry. Therefore, when the next + // block starts and tries to assign/burn collected fees it will be just 0 and + // nothing will be assigned. + transaction_fee::process_collected_fees(); + }; + + // Call stake to compute the new validator set and distribute rewards and transaction fees. + stake::on_new_epoch(); + storage_gas::on_reconfig(); + + assert!(current_time > config_ref.last_reconfiguration_time, error::invalid_state(EINVALID_BLOCK_TIME)); + config_ref.last_reconfiguration_time = current_time; + spec { + assume config_ref.epoch + 1 <= MAX_U64; + }; + config_ref.epoch = config_ref.epoch + 1; + + if (std::features::module_event_migration_enabled()) { + event::emit( + NewEpoch { + epoch: config_ref.epoch, + }, + ); + }; + event::emit_event( + &mut config_ref.events, + NewEpochEvent { + epoch: config_ref.epoch, + }, + ); + + reconfiguration_state::on_reconfig_finish(); + } + + public fun last_reconfiguration_time(): u64 acquires Configuration { + borrow_global(@aptos_framework).last_reconfiguration_time + } + + public fun current_epoch(): u64 acquires Configuration { + borrow_global(@aptos_framework).epoch + } + + /// Emit a `NewEpochEvent` event. This function will be invoked by genesis directly to generate the very first + /// reconfiguration event. + fun emit_genesis_reconfiguration_event() acquires Configuration { + let config_ref = borrow_global_mut(@aptos_framework); + assert!(config_ref.epoch == 0 && config_ref.last_reconfiguration_time == 0, error::invalid_state(ECONFIGURATION)); + config_ref.epoch = 1; + + if (std::features::module_event_migration_enabled()) { + event::emit( + NewEpoch { + epoch: config_ref.epoch, + }, + ); + }; + event::emit_event( + &mut config_ref.events, + NewEpochEvent { + epoch: config_ref.epoch, + }, + ); + } + + // For tests, skips the guid validation. + #[test_only] + public fun initialize_for_test(account: &signer) { + system_addresses::assert_aptos_framework(account); + move_to( + account, + Configuration { + epoch: 0, + last_reconfiguration_time: 0, + events: account::new_event_handle(account), + } + ); + } + + #[test_only] + public fun reconfigure_for_test() acquires Configuration { + reconfigure(); + } + + // This is used together with stake::end_epoch() for testing with last_reconfiguration_time + // It must be called each time an epoch changes + #[test_only] + public fun reconfigure_for_test_custom() acquires Configuration { + let config_ref = borrow_global_mut(@aptos_framework); + let current_time = timestamp::now_microseconds(); + if (current_time == config_ref.last_reconfiguration_time) { + return + }; + config_ref.last_reconfiguration_time = current_time; + config_ref.epoch = config_ref.epoch + 1; + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/reconfiguration_state.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/reconfiguration_state.move new file mode 100644 index 000000000..4818dd2a1 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/reconfiguration_state.move @@ -0,0 +1,132 @@ +/// Reconfiguration meta-state resources and util functions. +/// +/// WARNING: `reconfiguration_state::initialize()` is required before `RECONFIGURE_WITH_DKG` can be enabled. +module aptos_framework::reconfiguration_state { + use std::error; + use std::string; + use aptos_std::copyable_any; + use aptos_std::copyable_any::Any; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + + friend aptos_framework::reconfiguration; + friend aptos_framework::reconfiguration_with_dkg; + friend aptos_framework::stake; + + const ERECONFIG_NOT_IN_PROGRESS: u64 = 1; + + /// Reconfiguration drivers update this resources to notify other modules of some reconfiguration state. + struct State has key { + /// The state variant packed as an `Any`. + /// Currently the variant type is one of the following. + /// - `ReconfigStateInactive` + /// - `ReconfigStateActive` + variant: Any, + } + + /// A state variant indicating no reconfiguration is in progress. + struct StateInactive has copy, drop, store {} + + /// A state variant indicating a reconfiguration is in progress. + struct StateActive has copy, drop, store { + start_time_secs: u64, + } + + public fun is_initialized(): bool { + exists(@aptos_framework) + } + + public fun initialize(fx: &signer) { + system_addresses::assert_aptos_framework(fx); + if (!exists(@aptos_framework)) { + move_to(fx, State { + variant: copyable_any::pack(StateInactive {}) + }) + } + } + + public fun initialize_for_testing(fx: &signer) { + initialize(fx) + } + + /// Return whether the reconfiguration state is marked "in progress". + public(friend) fun is_in_progress(): bool acquires State { + if (!exists(@aptos_framework)) { + return false + }; + + let state = borrow_global(@aptos_framework); + let variant_type_name = *string::bytes(copyable_any::type_name(&state.variant)); + variant_type_name == b"0x1::reconfiguration_state::StateActive" + } + + /// Called at the beginning of a reconfiguration (either immediate or async) + /// to mark the reconfiguration state "in progress" if it is currently "stopped". + /// + /// Also record the current time as the reconfiguration start time. (Some module, e.g., `stake.move`, needs this info). + public(friend) fun on_reconfig_start() acquires State { + if (exists(@aptos_framework)) { + let state = borrow_global_mut(@aptos_framework); + let variant_type_name = *string::bytes(copyable_any::type_name(&state.variant)); + if (variant_type_name == b"0x1::reconfiguration_state::StateInactive") { + state.variant = copyable_any::pack(StateActive { + start_time_secs: timestamp::now_seconds() + }); + } + }; + } + + /// Get the unix time when the currently in-progress reconfiguration started. + /// Abort if the reconfiguration state is not "in progress". + public(friend) fun start_time_secs(): u64 acquires State { + let state = borrow_global(@aptos_framework); + let variant_type_name = *string::bytes(copyable_any::type_name(&state.variant)); + if (variant_type_name == b"0x1::reconfiguration_state::StateActive") { + let active = copyable_any::unpack(state.variant); + active.start_time_secs + } else { + abort(error::invalid_state(ERECONFIG_NOT_IN_PROGRESS)) + } + } + + /// Called at the end of every reconfiguration to mark the state as "stopped". + /// Abort if the current state is not "in progress". + public(friend) fun on_reconfig_finish() acquires State { + if (exists(@aptos_framework)) { + let state = borrow_global_mut(@aptos_framework); + let variant_type_name = *string::bytes(copyable_any::type_name(&state.variant)); + if (variant_type_name == b"0x1::reconfiguration_state::StateActive") { + state.variant = copyable_any::pack(StateInactive {}); + } else { + abort(error::invalid_state(ERECONFIG_NOT_IN_PROGRESS)) + } + } + } + + #[test(fx = @aptos_framework)] + fun basic(fx: &signer) acquires State { + // Setip. + timestamp::set_time_has_started_for_testing(fx); + initialize(fx); + + // Initially no reconfig is in progress. + assert!(!is_in_progress(), 1); + + // "try_start" should work. + timestamp::fast_forward_seconds(123); + on_reconfig_start(); + assert!(is_in_progress(), 1); + assert!(123 == start_time_secs(), 1); + + // Redundant `try_start` should be no-op. + timestamp::fast_forward_seconds(1); + on_reconfig_start(); + assert!(is_in_progress(), 1); + assert!(123 == start_time_secs(), 1); + + // A `finish` call should work when the state is marked "in progess". + timestamp::fast_forward_seconds(10); + on_reconfig_finish(); + assert!(!is_in_progress(), 1); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/reconfiguration_with_dkg.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/reconfiguration_with_dkg.move new file mode 100644 index 000000000..1357c4edb --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/reconfiguration_with_dkg.move @@ -0,0 +1,69 @@ +/// Reconfiguration with DKG helper functions. +module aptos_framework::reconfiguration_with_dkg { + use std::features; + use std::option; + use aptos_framework::consensus_config; + use aptos_framework::dkg; + use aptos_framework::execution_config; + use aptos_framework::gas_schedule; + use aptos_framework::jwk_consensus_config; + use aptos_framework::jwks; + use aptos_framework::keyless_account; + use aptos_framework::randomness_api_v0_config; + use aptos_framework::randomness_config; + use aptos_framework::randomness_config_seqnum; + use aptos_framework::reconfiguration; + use aptos_framework::reconfiguration_state; + use aptos_framework::stake; + use aptos_framework::system_addresses; + friend aptos_framework::block; + friend aptos_framework::aptos_governance; + + /// Trigger a reconfiguration with DKG. + /// Do nothing if one is already in progress. + public(friend) fun try_start() { + let incomplete_dkg_session = dkg::incomplete_session(); + if (option::is_some(&incomplete_dkg_session)) { + let session = option::borrow(&incomplete_dkg_session); + if (dkg::session_dealer_epoch(session) == reconfiguration::current_epoch()) { + return + } + }; + reconfiguration_state::on_reconfig_start(); + let cur_epoch = reconfiguration::current_epoch(); + dkg::start( + cur_epoch, + randomness_config::current(), + stake::cur_validator_consensus_infos(), + stake::next_validator_consensus_infos(), + ); + } + + /// Clear incomplete DKG session, if it exists. + /// Apply buffered on-chain configs (except for ValidatorSet, which is done inside `reconfiguration::reconfigure()`). + /// Re-enable validator set changes. + /// Run the default reconfiguration to enter the new epoch. + public(friend) fun finish(framework: &signer) { + system_addresses::assert_aptos_framework(framework); + dkg::try_clear_incomplete_session(framework); + consensus_config::on_new_epoch(framework); + execution_config::on_new_epoch(framework); + gas_schedule::on_new_epoch(framework); + std::version::on_new_epoch(framework); + features::on_new_epoch(framework); + jwk_consensus_config::on_new_epoch(framework); + jwks::on_new_epoch(framework); + keyless_account::on_new_epoch(framework); + randomness_config_seqnum::on_new_epoch(framework); + randomness_config::on_new_epoch(framework); + randomness_api_v0_config::on_new_epoch(framework); + reconfiguration::reconfigure(); + } + + /// Complete the current reconfiguration with DKG. + /// Abort if no DKG is in progress. + fun finish_with_dkg_result(account: &signer, dkg_result: vector) { + dkg::finish(dkg_result); + finish(account); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/resource_account.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/resource_account.move new file mode 100644 index 000000000..26ee8123e --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/resource_account.move @@ -0,0 +1,267 @@ +/// A resource account is used to manage resources independent of an account managed by a user. +/// This contains several utilities to make using resource accounts more effective. +/// +/// ## Resource Accounts to manage liquidity pools +/// +/// A dev wishing to use resource accounts for a liquidity pool, would likely do the following: +/// +/// 1. Create a new account using `resource_account::create_resource_account`. This creates the +/// account, stores the `signer_cap` within a `resource_account::Container`, and rotates the key to +/// the current account's authentication key or a provided authentication key. +/// 2. Define the liquidity pool module's address to be the same as the resource account. +/// 3. Construct a package-publishing transaction for the resource account using the +/// authentication key used in step 1. +/// 4. In the liquidity pool module's `init_module` function, call `retrieve_resource_account_cap` +/// which will retrieve the `signer_cap` and rotate the resource account's authentication key to +/// `0x0`, effectively locking it off. +/// 5. When adding a new coin, the liquidity pool will load the capability and hence the `signer` to +/// register and store new `LiquidityCoin` resources. +/// +/// Code snippets to help: +/// +/// ``` +/// fun init_module(resource_account: &signer) { +/// let dev_address = @DEV_ADDR; +/// let signer_cap = retrieve_resource_account_cap(resource_account, dev_address); +/// let lp = LiquidityPoolInfo { signer_cap: signer_cap, ... }; +/// move_to(resource_account, lp); +/// } +/// ``` +/// +/// Later on during a coin registration: +/// ``` +/// public fun add_coin(lp: &LP, x: Coin, y: Coin) { +/// if(!exists(LP::Address(lp), LiquidityCoin)) { +/// let mint, burn = Coin::initialize>(...); +/// move_to(&create_signer_with_capability(&lp.cap), LiquidityCoin{ mint, burn }); +/// } +/// ... +/// } +/// ``` +/// ## Resource accounts to manage an account for module publishing (i.e., contract account) +/// +/// A dev wishes to have an account dedicated to managing a contract. The contract itself does not +/// require signer post initialization. The dev could do the following: +/// 1. Create a new account using `resource_account::create_resource_account_and_publish_package`. +/// This creates the account and publishes the package for that account. +/// 2. At a later point in time, the account creator can move the signer capability to the module. +/// +/// ``` +/// struct MyModuleResource has key { +/// ... +/// resource_signer_cap: Option, +/// } +/// +/// public fun provide_signer_capability(resource_signer_cap: SignerCapability) { +/// let account_addr = account::get_signer_capability_address(resource_signer_cap); +/// let resource_addr = type_info::account_address(&type_info::type_of()); +/// assert!(account_addr == resource_addr, EADDRESS_MISMATCH); +/// let module = borrow_global_mut(account_addr); +/// module.resource_signer_cap = option::some(resource_signer_cap); +/// } +/// ``` +module aptos_framework::resource_account { + use std::error; + use std::signer; + use std::vector; + use aptos_framework::account; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::coin; + use aptos_std::simple_map::{Self, SimpleMap}; + + /// Container resource not found in account + const ECONTAINER_NOT_PUBLISHED: u64 = 1; + /// The resource account was not created by the specified source account + const EUNAUTHORIZED_NOT_OWNER: u64 = 2; + + const ZERO_AUTH_KEY: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; + + struct Container has key { + store: SimpleMap, + } + + /// Creates a new resource account and rotates the authentication key to either + /// the optional auth key if it is non-empty (though auth keys are 32-bytes) + /// or the source accounts current auth key. + public entry fun create_resource_account( + origin: &signer, + seed: vector, + optional_auth_key: vector, + ) acquires Container { + let (resource, resource_signer_cap) = account::create_resource_account(origin, seed); + rotate_account_authentication_key_and_store_capability( + origin, + resource, + resource_signer_cap, + optional_auth_key, + ); + } + + /// Creates a new resource account, transfer the amount of coins from the origin to the resource + /// account, and rotates the authentication key to either the optional auth key if it is + /// non-empty (though auth keys are 32-bytes) or the source accounts current auth key. Note, + /// this function adds additional resource ownership to the resource account and should only be + /// used for resource accounts that need access to `Coin`. + public entry fun create_resource_account_and_fund( + origin: &signer, + seed: vector, + optional_auth_key: vector, + fund_amount: u64, + ) acquires Container { + let (resource, resource_signer_cap) = account::create_resource_account(origin, seed); + coin::register(&resource); + coin::transfer(origin, signer::address_of(&resource), fund_amount); + rotate_account_authentication_key_and_store_capability( + origin, + resource, + resource_signer_cap, + optional_auth_key, + ); + } + + /// Creates a new resource account, publishes the package under this account transaction under + /// this account and leaves the signer cap readily available for pickup. + public entry fun create_resource_account_and_publish_package( + origin: &signer, + seed: vector, + metadata_serialized: vector, + code: vector>, + ) acquires Container { + let (resource, resource_signer_cap) = account::create_resource_account(origin, seed); + aptos_framework::code::publish_package_txn(&resource, metadata_serialized, code); + rotate_account_authentication_key_and_store_capability( + origin, + resource, + resource_signer_cap, + ZERO_AUTH_KEY, + ); + } + + fun rotate_account_authentication_key_and_store_capability( + origin: &signer, + resource: signer, + resource_signer_cap: account::SignerCapability, + optional_auth_key: vector, + ) acquires Container { + let origin_addr = signer::address_of(origin); + if (!exists(origin_addr)) { + move_to(origin, Container { store: simple_map::create() }) + }; + + let container = borrow_global_mut(origin_addr); + let resource_addr = signer::address_of(&resource); + simple_map::add(&mut container.store, resource_addr, resource_signer_cap); + + let auth_key = if (vector::is_empty(&optional_auth_key)) { + account::get_authentication_key(origin_addr) + } else { + optional_auth_key + }; + account::rotate_authentication_key_internal(&resource, auth_key); + } + + /// When called by the resource account, it will retrieve the capability associated with that + /// account and rotate the account's auth key to 0x0 making the account inaccessible without + /// the SignerCapability. + public fun retrieve_resource_account_cap( + resource: &signer, + source_addr: address, + ): account::SignerCapability acquires Container { + assert!(exists(source_addr), error::not_found(ECONTAINER_NOT_PUBLISHED)); + + let resource_addr = signer::address_of(resource); + let (resource_signer_cap, empty_container) = { + let container = borrow_global_mut(source_addr); + assert!( + simple_map::contains_key(&container.store, &resource_addr), + error::invalid_argument(EUNAUTHORIZED_NOT_OWNER) + ); + let (_resource_addr, signer_cap) = simple_map::remove(&mut container.store, &resource_addr); + (signer_cap, simple_map::length(&container.store) == 0) + }; + + if (empty_container) { + let container = move_from(source_addr); + let Container { store } = container; + simple_map::destroy_empty(store); + }; + + account::rotate_authentication_key_internal(resource, ZERO_AUTH_KEY); + resource_signer_cap + } + + #[test(user = @0x1111)] + public entry fun test_create_account_and_retrieve_cap(user: signer) acquires Container { + let user_addr = signer::address_of(&user); + account::create_account(user_addr); + + let seed = x"01"; + + create_resource_account(&user, copy seed, vector::empty()); + let container = borrow_global(user_addr); + + let resource_addr = aptos_framework::account::create_resource_address(&user_addr, seed); + let resource_cap = simple_map::borrow(&container.store, &resource_addr); + + let resource = account::create_signer_with_capability(resource_cap); + let _resource_cap = retrieve_resource_account_cap(&resource, user_addr); + } + + #[test(user = @0x1111)] + #[expected_failure(abort_code = 0x10002, location = aptos_std::simple_map)] + public entry fun test_create_account_and_retrieve_cap_resource_address_does_not_exist( + user: signer + ) acquires Container { + let user_addr = signer::address_of(&user); + account::create_account(user_addr); + + let seed = x"01"; + let seed2 = x"02"; + + create_resource_account(&user, seed2, vector::empty()); + let container = borrow_global(user_addr); + + let resource_addr = account::create_resource_address(&user_addr, seed); + let resource_cap = simple_map::borrow(&container.store, &resource_addr); + + let resource = account::create_signer_with_capability(resource_cap); + let _resource_cap = retrieve_resource_account_cap(&resource, user_addr); + } + + #[test(framework = @0x1, user = @0x1234)] + public entry fun with_coin(framework: signer, user: signer) acquires Container { + let user_addr = signer::address_of(&user); + let (burn, mint) = aptos_framework::aptos_coin::initialize_for_test(&framework); + aptos_framework::aptos_account::create_account(copy user_addr); + + let coin = coin::mint(100, &mint); + coin::deposit(copy user_addr, coin); + + let seed = x"01"; + create_resource_account_and_fund(&user, copy seed, vector::empty(), 10); + + let resource_addr = aptos_framework::account::create_resource_address(&user_addr, seed); + coin::transfer(&user, resource_addr, 10); + + coin::destroy_burn_cap(burn); + coin::destroy_mint_cap(mint); + } + + #[test(framework = @0x1, user = @0x2345)] + #[expected_failure(abort_code = 0x60005, location = aptos_framework::coin)] + public entry fun without_coin(framework: signer, user: signer) acquires Container { + let user_addr = signer::address_of(&user); + let (burn, mint) = aptos_framework::aptos_coin::initialize_for_test(&framework); + aptos_framework::aptos_account::create_account(user_addr); + + let seed = x"01"; + create_resource_account(&user, copy seed, vector::empty()); + + let resource_addr = aptos_framework::account::create_resource_address(&user_addr, seed); + let coin = coin::mint(100, &mint); + coin::deposit(resource_addr, coin); + + coin::destroy_burn_cap(burn); + coin::destroy_mint_cap(mint); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/stake.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/stake.move new file mode 100644 index 000000000..9639ffa8f --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/stake.move @@ -0,0 +1,3286 @@ +/// +/// Validator lifecycle: +/// 1. Prepare a validator node set up and call stake::initialize_validator +/// 2. Once ready to deposit stake (or have funds assigned by a staking service in exchange for ownership capability), +/// call stake::add_stake (or *_with_cap versions if called from the staking service) +/// 3. Call stake::join_validator_set (or _with_cap version) to join the active validator set. Changes are effective in +/// the next epoch. +/// 4. Validate and gain rewards. The stake will automatically be locked up for a fixed duration (set by governance) and +/// automatically renewed at expiration. +/// 5. At any point, if the validator operator wants to update the consensus key or network/fullnode addresses, they can +/// call stake::rotate_consensus_key and stake::update_network_and_fullnode_addresses. Similar to changes to stake, the +/// changes to consensus key/network/fullnode addresses are only effective in the next epoch. +/// 6. Validator can request to unlock their stake at any time. However, their stake will only become withdrawable when +/// their current lockup expires. This can be at most as long as the fixed lockup duration. +/// 7. After exiting, the validator can either explicitly leave the validator set by calling stake::leave_validator_set +/// or if their stake drops below the min required, they would get removed at the end of the epoch. +/// 8. Validator can always rejoin the validator set by going through steps 2-3 again. +/// 9. An owner can always switch operators by calling stake::set_operator. +/// 10. An owner can always switch designated voter by calling stake::set_designated_voter. +module aptos_framework::stake { + use std::error; + use std::features; + use std::option::{Self, Option}; + use std::signer; + use std::vector; + use aptos_std::bls12381; + use aptos_std::math64::min; + use aptos_std::table::{Self, Table}; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::account; + use aptos_framework::coin::{Self, Coin, MintCapability}; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::timestamp; + use aptos_framework::system_addresses; + use aptos_framework::staking_config::{Self, StakingConfig, StakingRewardsConfig}; + use aptos_framework::chain_status; + + friend aptos_framework::block; + friend aptos_framework::genesis; + friend aptos_framework::reconfiguration; + friend aptos_framework::reconfiguration_with_dkg; + friend aptos_framework::transaction_fee; + + /// Validator Config not published. + const EVALIDATOR_CONFIG: u64 = 1; + /// Not enough stake to join validator set. + const ESTAKE_TOO_LOW: u64 = 2; + /// Too much stake to join validator set. + const ESTAKE_TOO_HIGH: u64 = 3; + /// Account is already a validator or pending validator. + const EALREADY_ACTIVE_VALIDATOR: u64 = 4; + /// Account is not a validator. + const ENOT_VALIDATOR: u64 = 5; + /// Can't remove last validator. + const ELAST_VALIDATOR: u64 = 6; + /// Total stake exceeds maximum allowed. + const ESTAKE_EXCEEDS_MAX: u64 = 7; + /// Account is already registered as a validator candidate. + const EALREADY_REGISTERED: u64 = 8; + /// Account does not have the right operator capability. + const ENOT_OPERATOR: u64 = 9; + /// Validators cannot join or leave post genesis on this test network. + const ENO_POST_GENESIS_VALIDATOR_SET_CHANGE_ALLOWED: u64 = 10; + /// Invalid consensus public key + const EINVALID_PUBLIC_KEY: u64 = 11; + /// Validator set exceeds the limit + const EVALIDATOR_SET_TOO_LARGE: u64 = 12; + /// Voting power increase has exceeded the limit for this current epoch. + const EVOTING_POWER_INCREASE_EXCEEDS_LIMIT: u64 = 13; + /// Stake pool does not exist at the provided pool address. + const ESTAKE_POOL_DOES_NOT_EXIST: u64 = 14; + /// Owner capability does not exist at the provided account. + const EOWNER_CAP_NOT_FOUND: u64 = 15; + /// An account cannot own more than one owner capability. + const EOWNER_CAP_ALREADY_EXISTS: u64 = 16; + /// Validator is not defined in the ACL of entities allowed to be validators + const EINELIGIBLE_VALIDATOR: u64 = 17; + /// Cannot update stake pool's lockup to earlier than current lockup. + const EINVALID_LOCKUP: u64 = 18; + /// Table to store collected transaction fees for each validator already exists. + const EFEES_TABLE_ALREADY_EXISTS: u64 = 19; + /// Validator set change temporarily disabled because of in-progress reconfiguration. + const ERECONFIGURATION_IN_PROGRESS: u64 = 20; + + /// Validator status enum. We can switch to proper enum later once Move supports it. + const VALIDATOR_STATUS_PENDING_ACTIVE: u64 = 1; + const VALIDATOR_STATUS_ACTIVE: u64 = 2; + const VALIDATOR_STATUS_PENDING_INACTIVE: u64 = 3; + const VALIDATOR_STATUS_INACTIVE: u64 = 4; + + /// Limit the maximum size to u16::max, it's the current limit of the bitvec + /// https://github.com/aptos-labs/aptos-core/blob/main/crates/aptos-bitvec/src/lib.rs#L20 + const MAX_VALIDATOR_SET_SIZE: u64 = 65536; + + /// Limit the maximum value of `rewards_rate` in order to avoid any arithmetic overflow. + const MAX_REWARDS_RATE: u64 = 1000000; + + const MAX_U64: u128 = 18446744073709551615; + + /// Capability that represents ownership and can be used to control the validator and the associated stake pool. + /// Having this be separate from the signer for the account that the validator resources are hosted at allows + /// modules to have control over a validator. + struct OwnerCapability has key, store { + pool_address: address, + } + + /// Each validator has a separate StakePool resource and can provide a stake. + /// Changes in stake for an active validator: + /// 1. If a validator calls add_stake, the newly added stake is moved to pending_active. + /// 2. If validator calls unlock, their stake is moved to pending_inactive. + /// 2. When the next epoch starts, any pending_inactive stake is moved to inactive and can be withdrawn. + /// Any pending_active stake is moved to active and adds to the validator's voting power. + /// + /// Changes in stake for an inactive validator: + /// 1. If a validator calls add_stake, the newly added stake is moved directly to active. + /// 2. If validator calls unlock, their stake is moved directly to inactive. + /// 3. When the next epoch starts, the validator can be activated if their active stake is more than the minimum. + struct StakePool has key { + // active stake + active: Coin, + // inactive stake, can be withdrawn + inactive: Coin, + // pending activation for next epoch + pending_active: Coin, + // pending deactivation for next epoch + pending_inactive: Coin, + locked_until_secs: u64, + // Track the current operator of the validator node. + // This allows the operator to be different from the original account and allow for separation of + // the validator operations and ownership. + // Only the account holding OwnerCapability of the staking pool can update this. + operator_address: address, + + // Track the current vote delegator of the staking pool. + // Only the account holding OwnerCapability of the staking pool can update this. + delegated_voter: address, + + // The events emitted for the entire StakePool's lifecycle. + initialize_validator_events: EventHandle, + set_operator_events: EventHandle, + add_stake_events: EventHandle, + reactivate_stake_events: EventHandle, + rotate_consensus_key_events: EventHandle, + update_network_and_fullnode_addresses_events: EventHandle, + increase_lockup_events: EventHandle, + join_validator_set_events: EventHandle, + distribute_rewards_events: EventHandle, + unlock_stake_events: EventHandle, + withdraw_stake_events: EventHandle, + leave_validator_set_events: EventHandle, + } + + /// Validator info stored in validator address. + struct ValidatorConfig has key, copy, store, drop { + consensus_pubkey: vector, + network_addresses: vector, + // to make it compatible with previous definition, remove later + fullnode_addresses: vector, + // Index in the active set if the validator corresponding to this stake pool is active. + validator_index: u64, + } + + /// Consensus information per validator, stored in ValidatorSet. + struct ValidatorInfo has copy, store, drop { + addr: address, + voting_power: u64, + config: ValidatorConfig, + } + + /// Full ValidatorSet, stored in @aptos_framework. + /// 1. join_validator_set adds to pending_active queue. + /// 2. leave_valdiator_set moves from active to pending_inactive queue. + /// 3. on_new_epoch processes two pending queues and refresh ValidatorInfo from the owner's address. + struct ValidatorSet has copy, key, drop, store { + consensus_scheme: u8, + // Active validators for the current epoch. + active_validators: vector, + // Pending validators to leave in next epoch (still active). + pending_inactive: vector, + // Pending validators to join in next epoch. + pending_active: vector, + // Current total voting power. + total_voting_power: u128, + // Total voting power waiting to join in the next epoch. + total_joining_power: u128, + } + + /// AptosCoin capabilities, set during genesis and stored in @CoreResource account. + /// This allows the Stake module to mint rewards to stakers. + struct AptosCoinCapabilities has key { + mint_cap: MintCapability, + } + + struct IndividualValidatorPerformance has store, drop { + successful_proposals: u64, + failed_proposals: u64, + } + + struct ValidatorPerformance has key { + validators: vector, + } + + struct RegisterValidatorCandidateEvent has drop, store { + pool_address: address, + } + + #[event] + struct RegisterValidatorCandidate has drop, store { + pool_address: address, + } + + struct SetOperatorEvent has drop, store { + pool_address: address, + old_operator: address, + new_operator: address, + } + + #[event] + struct SetOperator has drop, store { + pool_address: address, + old_operator: address, + new_operator: address, + } + + struct AddStakeEvent has drop, store { + pool_address: address, + amount_added: u64, + } + + #[event] + struct AddStake has drop, store { + pool_address: address, + amount_added: u64, + } + + struct ReactivateStakeEvent has drop, store { + pool_address: address, + amount: u64, + } + + #[event] + struct ReactivateStake has drop, store { + pool_address: address, + amount: u64, + } + + struct RotateConsensusKeyEvent has drop, store { + pool_address: address, + old_consensus_pubkey: vector, + new_consensus_pubkey: vector, + } + + #[event] + struct RotateConsensusKey has drop, store { + pool_address: address, + old_consensus_pubkey: vector, + new_consensus_pubkey: vector, + } + + struct UpdateNetworkAndFullnodeAddressesEvent has drop, store { + pool_address: address, + old_network_addresses: vector, + new_network_addresses: vector, + old_fullnode_addresses: vector, + new_fullnode_addresses: vector, + } + + #[event] + struct UpdateNetworkAndFullnodeAddresses has drop, store { + pool_address: address, + old_network_addresses: vector, + new_network_addresses: vector, + old_fullnode_addresses: vector, + new_fullnode_addresses: vector, + } + + struct IncreaseLockupEvent has drop, store { + pool_address: address, + old_locked_until_secs: u64, + new_locked_until_secs: u64, + } + + #[event] + struct IncreaseLockup has drop, store { + pool_address: address, + old_locked_until_secs: u64, + new_locked_until_secs: u64, + } + + struct JoinValidatorSetEvent has drop, store { + pool_address: address, + } + + #[event] + struct JoinValidatorSet has drop, store { + pool_address: address, + } + + struct DistributeRewardsEvent has drop, store { + pool_address: address, + rewards_amount: u64, + } + + #[event] + struct DistributeRewards has drop, store { + pool_address: address, + rewards_amount: u64, + } + + struct UnlockStakeEvent has drop, store { + pool_address: address, + amount_unlocked: u64, + } + + #[event] + struct UnlockStake has drop, store { + pool_address: address, + amount_unlocked: u64, + } + + struct WithdrawStakeEvent has drop, store { + pool_address: address, + amount_withdrawn: u64, + } + + #[event] + struct WithdrawStake has drop, store { + pool_address: address, + amount_withdrawn: u64, + } + + struct LeaveValidatorSetEvent has drop, store { + pool_address: address, + } + + #[event] + struct LeaveValidatorSet has drop, store { + pool_address: address, + } + + /// Stores transaction fees assigned to validators. All fees are distributed to validators + /// at the end of the epoch. + struct ValidatorFees has key { + fees_table: Table>, + } + + /// Initializes the resource storing information about collected transaction fees per validator. + /// Used by `transaction_fee.move` to initialize fee collection and distribution. + public(friend) fun initialize_validator_fees(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!( + !exists(@aptos_framework), + error::already_exists(EFEES_TABLE_ALREADY_EXISTS) + ); + move_to(aptos_framework, ValidatorFees { fees_table: table::new() }); + } + + /// Stores the transaction fee collected to the specified validator address. + public(friend) fun add_transaction_fee(validator_addr: address, fee: Coin) acquires ValidatorFees { + let fees_table = &mut borrow_global_mut(@aptos_framework).fees_table; + if (table::contains(fees_table, validator_addr)) { + let collected_fee = table::borrow_mut(fees_table, validator_addr); + coin::merge(collected_fee, fee); + } else { + table::add(fees_table, validator_addr, fee); + } + } + + #[view] + /// Return the lockup expiration of the stake pool at `pool_address`. + /// This will throw an error if there's no stake pool at `pool_address`. + public fun get_lockup_secs(pool_address: address): u64 acquires StakePool { + assert_stake_pool_exists(pool_address); + borrow_global(pool_address).locked_until_secs + } + + #[view] + /// Return the remaining lockup of the stake pool at `pool_address`. + /// This will throw an error if there's no stake pool at `pool_address`. + public fun get_remaining_lockup_secs(pool_address: address): u64 acquires StakePool { + assert_stake_pool_exists(pool_address); + let lockup_time = borrow_global(pool_address).locked_until_secs; + if (lockup_time <= timestamp::now_seconds()) { + 0 + } else { + lockup_time - timestamp::now_seconds() + } + } + + #[view] + /// Return the different stake amounts for `pool_address` (whether the validator is active or not). + /// The returned amounts are for (active, inactive, pending_active, pending_inactive) stake respectively. + public fun get_stake(pool_address: address): (u64, u64, u64, u64) acquires StakePool { + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global(pool_address); + ( + coin::value(&stake_pool.active), + coin::value(&stake_pool.inactive), + coin::value(&stake_pool.pending_active), + coin::value(&stake_pool.pending_inactive), + ) + } + + #[view] + /// Returns the validator's state. + public fun get_validator_state(pool_address: address): u64 acquires ValidatorSet { + let validator_set = borrow_global(@aptos_framework); + if (option::is_some(&find_validator(&validator_set.pending_active, pool_address))) { + VALIDATOR_STATUS_PENDING_ACTIVE + } else if (option::is_some(&find_validator(&validator_set.active_validators, pool_address))) { + VALIDATOR_STATUS_ACTIVE + } else if (option::is_some(&find_validator(&validator_set.pending_inactive, pool_address))) { + VALIDATOR_STATUS_PENDING_INACTIVE + } else { + VALIDATOR_STATUS_INACTIVE + } + } + + #[view] + /// Return the voting power of the validator in the current epoch. + /// This is the same as the validator's total active and pending_inactive stake. + public fun get_current_epoch_voting_power(pool_address: address): u64 acquires StakePool, ValidatorSet { + assert_stake_pool_exists(pool_address); + let validator_state = get_validator_state(pool_address); + // Both active and pending inactive validators can still vote in the current epoch. + if (validator_state == VALIDATOR_STATUS_ACTIVE || validator_state == VALIDATOR_STATUS_PENDING_INACTIVE) { + let active_stake = coin::value(&borrow_global(pool_address).active); + let pending_inactive_stake = coin::value(&borrow_global(pool_address).pending_inactive); + active_stake + pending_inactive_stake + } else { + 0 + } + } + + #[view] + /// Return the delegated voter of the validator at `pool_address`. + public fun get_delegated_voter(pool_address: address): address acquires StakePool { + assert_stake_pool_exists(pool_address); + borrow_global(pool_address).delegated_voter + } + + #[view] + /// Return the operator of the validator at `pool_address`. + public fun get_operator(pool_address: address): address acquires StakePool { + assert_stake_pool_exists(pool_address); + borrow_global(pool_address).operator_address + } + + /// Return the pool address in `owner_cap`. + public fun get_owned_pool_address(owner_cap: &OwnerCapability): address { + owner_cap.pool_address + } + + #[view] + /// Return the validator index for `pool_address`. + public fun get_validator_index(pool_address: address): u64 acquires ValidatorConfig { + assert_stake_pool_exists(pool_address); + borrow_global(pool_address).validator_index + } + + #[view] + /// Return the number of successful and failed proposals for the proposal at the given validator index. + public fun get_current_epoch_proposal_counts(validator_index: u64): (u64, u64) acquires ValidatorPerformance { + let validator_performances = &borrow_global(@aptos_framework).validators; + let validator_performance = vector::borrow(validator_performances, validator_index); + (validator_performance.successful_proposals, validator_performance.failed_proposals) + } + + #[view] + /// Return the validator's config. + public fun get_validator_config( + pool_address: address + ): (vector, vector, vector) acquires ValidatorConfig { + assert_stake_pool_exists(pool_address); + let validator_config = borrow_global(pool_address); + (validator_config.consensus_pubkey, validator_config.network_addresses, validator_config.fullnode_addresses) + } + + #[view] + public fun stake_pool_exists(addr: address): bool { + exists(addr) + } + + /// Initialize validator set to the core resource account. + public(friend) fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + + move_to(aptos_framework, ValidatorSet { + consensus_scheme: 0, + active_validators: vector::empty(), + pending_active: vector::empty(), + pending_inactive: vector::empty(), + total_voting_power: 0, + total_joining_power: 0, + }); + + move_to(aptos_framework, ValidatorPerformance { + validators: vector::empty(), + }); + } + + /// This is only called during Genesis, which is where MintCapability can be created. + /// Beyond genesis, no one can create AptosCoin mint/burn capabilities. + public(friend) fun store_aptos_coin_mint_cap(aptos_framework: &signer, mint_cap: MintCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, AptosCoinCapabilities { mint_cap }) + } + + /// Allow on chain governance to remove validators from the validator set. + public fun remove_validators( + aptos_framework: &signer, + validators: &vector
, + ) acquires ValidatorSet { + assert_reconfig_not_in_progress(); + system_addresses::assert_aptos_framework(aptos_framework); + let validator_set = borrow_global_mut(@aptos_framework); + let active_validators = &mut validator_set.active_validators; + let pending_inactive = &mut validator_set.pending_inactive; + spec { + update ghost_active_num = len(active_validators); + update ghost_pending_inactive_num = len(pending_inactive); + }; + let len_validators = vector::length(validators); + let i = 0; + // Remove each validator from the validator set. + while ({ + spec { + invariant i <= len_validators; + invariant spec_validators_are_initialized(active_validators); + invariant spec_validator_indices_are_valid(active_validators); + invariant spec_validators_are_initialized(pending_inactive); + invariant spec_validator_indices_are_valid(pending_inactive); + invariant ghost_active_num + ghost_pending_inactive_num == len(active_validators) + len(pending_inactive); + }; + i < len_validators + }) { + let validator = *vector::borrow(validators, i); + let validator_index = find_validator(active_validators, validator); + if (option::is_some(&validator_index)) { + let validator_info = vector::swap_remove(active_validators, *option::borrow(&validator_index)); + vector::push_back(pending_inactive, validator_info); + spec { + update ghost_active_num = ghost_active_num - 1; + update ghost_pending_inactive_num = ghost_pending_inactive_num + 1; + }; + }; + i = i + 1; + }; + } + + /// Initialize the validator account and give ownership to the signing account + /// except it leaves the ValidatorConfig to be set by another entity. + /// Note: this triggers setting the operator and owner, set it to the account's address + /// to set later. + public entry fun initialize_stake_owner( + owner: &signer, + initial_stake_amount: u64, + operator: address, + voter: address, + ) acquires AllowedValidators, OwnerCapability, StakePool, ValidatorSet { + initialize_owner(owner); + move_to(owner, ValidatorConfig { + consensus_pubkey: vector::empty(), + network_addresses: vector::empty(), + fullnode_addresses: vector::empty(), + validator_index: 0, + }); + + if (initial_stake_amount > 0) { + add_stake(owner, initial_stake_amount); + }; + + let account_address = signer::address_of(owner); + if (account_address != operator) { + set_operator(owner, operator) + }; + if (account_address != voter) { + set_delegated_voter(owner, voter) + }; + } + + /// Initialize the validator account and give ownership to the signing account. + public entry fun initialize_validator( + account: &signer, + consensus_pubkey: vector, + proof_of_possession: vector, + network_addresses: vector, + fullnode_addresses: vector, + ) acquires AllowedValidators { + // Checks the public key has a valid proof-of-possession to prevent rogue-key attacks. + let pubkey_from_pop = &mut bls12381::public_key_from_bytes_with_pop( + consensus_pubkey, + &proof_of_possession_from_bytes(proof_of_possession) + ); + assert!(option::is_some(pubkey_from_pop), error::invalid_argument(EINVALID_PUBLIC_KEY)); + + initialize_owner(account); + move_to(account, ValidatorConfig { + consensus_pubkey, + network_addresses, + fullnode_addresses, + validator_index: 0, + }); + } + + fun initialize_owner(owner: &signer) acquires AllowedValidators { + let owner_address = signer::address_of(owner); + assert!(is_allowed(owner_address), error::not_found(EINELIGIBLE_VALIDATOR)); + assert!(!stake_pool_exists(owner_address), error::already_exists(EALREADY_REGISTERED)); + + move_to(owner, StakePool { + active: coin::zero(), + pending_active: coin::zero(), + pending_inactive: coin::zero(), + inactive: coin::zero(), + locked_until_secs: 0, + operator_address: owner_address, + delegated_voter: owner_address, + // Events. + initialize_validator_events: account::new_event_handle(owner), + set_operator_events: account::new_event_handle(owner), + add_stake_events: account::new_event_handle(owner), + reactivate_stake_events: account::new_event_handle(owner), + rotate_consensus_key_events: account::new_event_handle(owner), + update_network_and_fullnode_addresses_events: account::new_event_handle( + owner + ), + increase_lockup_events: account::new_event_handle(owner), + join_validator_set_events: account::new_event_handle(owner), + distribute_rewards_events: account::new_event_handle(owner), + unlock_stake_events: account::new_event_handle(owner), + withdraw_stake_events: account::new_event_handle(owner), + leave_validator_set_events: account::new_event_handle(owner), + }); + + move_to(owner, OwnerCapability { pool_address: owner_address }); + } + + /// Extract and return owner capability from the signing account. + public fun extract_owner_cap(owner: &signer): OwnerCapability acquires OwnerCapability { + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + move_from(owner_address) + } + + /// Deposit `owner_cap` into `account`. This requires `account` to not already have ownership of another + /// staking pool. + public fun deposit_owner_cap(owner: &signer, owner_cap: OwnerCapability) { + assert!(!exists(signer::address_of(owner)), error::not_found(EOWNER_CAP_ALREADY_EXISTS)); + move_to(owner, owner_cap); + } + + /// Destroy `owner_cap`. + public fun destroy_owner_cap(owner_cap: OwnerCapability) { + let OwnerCapability { pool_address: _ } = owner_cap; + } + + /// Allows an owner to change the operator of the stake pool. + public entry fun set_operator(owner: &signer, new_operator: address) acquires OwnerCapability, StakePool { + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + let ownership_cap = borrow_global(owner_address); + set_operator_with_cap(ownership_cap, new_operator); + } + + /// Allows an account with ownership capability to change the operator of the stake pool. + public fun set_operator_with_cap(owner_cap: &OwnerCapability, new_operator: address) acquires StakePool { + let pool_address = owner_cap.pool_address; + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global_mut(pool_address); + let old_operator = stake_pool.operator_address; + stake_pool.operator_address = new_operator; + + if (std::features::module_event_migration_enabled()) { + event::emit( + SetOperator { + pool_address, + old_operator, + new_operator, + }, + ); + }; + + event::emit_event( + &mut stake_pool.set_operator_events, + SetOperatorEvent { + pool_address, + old_operator, + new_operator, + }, + ); + } + + /// Allows an owner to change the delegated voter of the stake pool. + public entry fun set_delegated_voter(owner: &signer, new_voter: address) acquires OwnerCapability, StakePool { + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + let ownership_cap = borrow_global(owner_address); + set_delegated_voter_with_cap(ownership_cap, new_voter); + } + + /// Allows an owner to change the delegated voter of the stake pool. + public fun set_delegated_voter_with_cap(owner_cap: &OwnerCapability, new_voter: address) acquires StakePool { + let pool_address = owner_cap.pool_address; + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global_mut(pool_address); + stake_pool.delegated_voter = new_voter; + } + + /// Add `amount` of coins from the `account` owning the StakePool. + public entry fun add_stake(owner: &signer, amount: u64) acquires OwnerCapability, StakePool, ValidatorSet { + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + let ownership_cap = borrow_global(owner_address); + add_stake_with_cap(ownership_cap, coin::withdraw(owner, amount)); + } + + /// Add `coins` into `pool_address`. this requires the corresponding `owner_cap` to be passed in. + public fun add_stake_with_cap(owner_cap: &OwnerCapability, coins: Coin) acquires StakePool, ValidatorSet { + assert_reconfig_not_in_progress(); + let pool_address = owner_cap.pool_address; + assert_stake_pool_exists(pool_address); + + let amount = coin::value(&coins); + if (amount == 0) { + coin::destroy_zero(coins); + return + }; + + // Only track and validate voting power increase for active and pending_active validator. + // Pending_inactive validator will be removed from the validator set in the next epoch. + // Inactive validator's total stake will be tracked when they join the validator set. + let validator_set = borrow_global_mut(@aptos_framework); + // Search directly rather using get_validator_state to save on unnecessary loops. + if (option::is_some(&find_validator(&validator_set.active_validators, pool_address)) || + option::is_some(&find_validator(&validator_set.pending_active, pool_address))) { + update_voting_power_increase(amount); + }; + + // Add to pending_active if it's a current validator because the stake is not counted until the next epoch. + // Otherwise, the delegation can be added to active directly as the validator is also activated in the epoch. + let stake_pool = borrow_global_mut(pool_address); + if (is_current_epoch_validator(pool_address)) { + coin::merge(&mut stake_pool.pending_active, coins); + } else { + coin::merge(&mut stake_pool.active, coins); + }; + + let (_, maximum_stake) = staking_config::get_required_stake(&staking_config::get()); + let voting_power = get_next_epoch_voting_power(stake_pool); + assert!(voting_power <= maximum_stake, error::invalid_argument(ESTAKE_EXCEEDS_MAX)); + + if (std::features::module_event_migration_enabled()) { + event::emit( + AddStake { + pool_address, + amount_added: amount, + }, + ); + }; + event::emit_event( + &mut stake_pool.add_stake_events, + AddStakeEvent { + pool_address, + amount_added: amount, + }, + ); + } + + /// Move `amount` of coins from pending_inactive to active. + public entry fun reactivate_stake(owner: &signer, amount: u64) acquires OwnerCapability, StakePool { + assert_reconfig_not_in_progress(); + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + let ownership_cap = borrow_global(owner_address); + reactivate_stake_with_cap(ownership_cap, amount); + } + + public fun reactivate_stake_with_cap(owner_cap: &OwnerCapability, amount: u64) acquires StakePool { + assert_reconfig_not_in_progress(); + let pool_address = owner_cap.pool_address; + assert_stake_pool_exists(pool_address); + + // Cap the amount to reactivate by the amount in pending_inactive. + let stake_pool = borrow_global_mut(pool_address); + let total_pending_inactive = coin::value(&stake_pool.pending_inactive); + amount = min(amount, total_pending_inactive); + + // Since this does not count as a voting power change (pending inactive still counts as voting power in the + // current epoch), stake can be immediately moved from pending inactive to active. + // We also don't need to check voting power increase as there's none. + let reactivated_coins = coin::extract(&mut stake_pool.pending_inactive, amount); + coin::merge(&mut stake_pool.active, reactivated_coins); + + if (std::features::module_event_migration_enabled()) { + event::emit( + ReactivateStake { + pool_address, + amount, + }, + ); + }; + event::emit_event( + &mut stake_pool.reactivate_stake_events, + ReactivateStakeEvent { + pool_address, + amount, + }, + ); + } + + /// Rotate the consensus key of the validator, it'll take effect in next epoch. + public entry fun rotate_consensus_key( + operator: &signer, + pool_address: address, + new_consensus_pubkey: vector, + proof_of_possession: vector, + ) acquires StakePool, ValidatorConfig { + assert_reconfig_not_in_progress(); + assert_stake_pool_exists(pool_address); + + let stake_pool = borrow_global_mut(pool_address); + assert!(signer::address_of(operator) == stake_pool.operator_address, error::unauthenticated(ENOT_OPERATOR)); + + assert!(exists(pool_address), error::not_found(EVALIDATOR_CONFIG)); + let validator_info = borrow_global_mut(pool_address); + let old_consensus_pubkey = validator_info.consensus_pubkey; + // Checks the public key has a valid proof-of-possession to prevent rogue-key attacks. + let pubkey_from_pop = &mut bls12381::public_key_from_bytes_with_pop( + new_consensus_pubkey, + &proof_of_possession_from_bytes(proof_of_possession) + ); + assert!(option::is_some(pubkey_from_pop), error::invalid_argument(EINVALID_PUBLIC_KEY)); + validator_info.consensus_pubkey = new_consensus_pubkey; + + if (std::features::module_event_migration_enabled()) { + event::emit( + RotateConsensusKey { + pool_address, + old_consensus_pubkey, + new_consensus_pubkey, + }, + ); + }; + event::emit_event( + &mut stake_pool.rotate_consensus_key_events, + RotateConsensusKeyEvent { + pool_address, + old_consensus_pubkey, + new_consensus_pubkey, + }, + ); + } + + /// Update the network and full node addresses of the validator. This only takes effect in the next epoch. + public entry fun update_network_and_fullnode_addresses( + operator: &signer, + pool_address: address, + new_network_addresses: vector, + new_fullnode_addresses: vector, + ) acquires StakePool, ValidatorConfig { + assert_reconfig_not_in_progress(); + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global_mut(pool_address); + assert!(signer::address_of(operator) == stake_pool.operator_address, error::unauthenticated(ENOT_OPERATOR)); + assert!(exists(pool_address), error::not_found(EVALIDATOR_CONFIG)); + let validator_info = borrow_global_mut(pool_address); + let old_network_addresses = validator_info.network_addresses; + validator_info.network_addresses = new_network_addresses; + let old_fullnode_addresses = validator_info.fullnode_addresses; + validator_info.fullnode_addresses = new_fullnode_addresses; + + if (std::features::module_event_migration_enabled()) { + event::emit( + UpdateNetworkAndFullnodeAddresses { + pool_address, + old_network_addresses, + new_network_addresses, + old_fullnode_addresses, + new_fullnode_addresses, + }, + ); + }; + event::emit_event( + &mut stake_pool.update_network_and_fullnode_addresses_events, + UpdateNetworkAndFullnodeAddressesEvent { + pool_address, + old_network_addresses, + new_network_addresses, + old_fullnode_addresses, + new_fullnode_addresses, + }, + ); + + } + + /// Similar to increase_lockup_with_cap but will use ownership capability from the signing account. + public entry fun increase_lockup(owner: &signer) acquires OwnerCapability, StakePool { + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + let ownership_cap = borrow_global(owner_address); + increase_lockup_with_cap(ownership_cap); + } + + /// Unlock from active delegation, it's moved to pending_inactive if locked_until_secs < current_time or + /// directly inactive if it's not from an active validator. + public fun increase_lockup_with_cap(owner_cap: &OwnerCapability) acquires StakePool { + let pool_address = owner_cap.pool_address; + assert_stake_pool_exists(pool_address); + let config = staking_config::get(); + + let stake_pool = borrow_global_mut(pool_address); + let old_locked_until_secs = stake_pool.locked_until_secs; + let new_locked_until_secs = timestamp::now_seconds() + staking_config::get_recurring_lockup_duration(&config); + assert!(old_locked_until_secs < new_locked_until_secs, error::invalid_argument(EINVALID_LOCKUP)); + stake_pool.locked_until_secs = new_locked_until_secs; + + if (std::features::module_event_migration_enabled()) { + event::emit( + IncreaseLockup { + pool_address, + old_locked_until_secs, + new_locked_until_secs, + }, + ); + }; + event::emit_event( + &mut stake_pool.increase_lockup_events, + IncreaseLockupEvent { + pool_address, + old_locked_until_secs, + new_locked_until_secs, + }, + ); + } + + /// This can only called by the operator of the validator/staking pool. + public entry fun join_validator_set( + operator: &signer, + pool_address: address + ) acquires StakePool, ValidatorConfig, ValidatorSet { + assert!( + staking_config::get_allow_validator_set_change(&staking_config::get()), + error::invalid_argument(ENO_POST_GENESIS_VALIDATOR_SET_CHANGE_ALLOWED), + ); + + join_validator_set_internal(operator, pool_address); + } + + /// Request to have `pool_address` join the validator set. Can only be called after calling `initialize_validator`. + /// If the validator has the required stake (more than minimum and less than maximum allowed), they will be + /// added to the pending_active queue. All validators in this queue will be added to the active set when the next + /// epoch starts (eligibility will be rechecked). + /// + /// This internal version can only be called by the Genesis module during Genesis. + public(friend) fun join_validator_set_internal( + operator: &signer, + pool_address: address + ) acquires StakePool, ValidatorConfig, ValidatorSet { + assert_reconfig_not_in_progress(); + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global_mut(pool_address); + assert!(signer::address_of(operator) == stake_pool.operator_address, error::unauthenticated(ENOT_OPERATOR)); + assert!( + get_validator_state(pool_address) == VALIDATOR_STATUS_INACTIVE, + error::invalid_state(EALREADY_ACTIVE_VALIDATOR), + ); + + let config = staking_config::get(); + let (minimum_stake, maximum_stake) = staking_config::get_required_stake(&config); + let voting_power = get_next_epoch_voting_power(stake_pool); + assert!(voting_power >= minimum_stake, error::invalid_argument(ESTAKE_TOO_LOW)); + assert!(voting_power <= maximum_stake, error::invalid_argument(ESTAKE_TOO_HIGH)); + + // Track and validate voting power increase. + update_voting_power_increase(voting_power); + + // Add validator to pending_active, to be activated in the next epoch. + let validator_config = borrow_global_mut(pool_address); + assert!(!vector::is_empty(&validator_config.consensus_pubkey), error::invalid_argument(EINVALID_PUBLIC_KEY)); + + // Validate the current validator set size has not exceeded the limit. + let validator_set = borrow_global_mut(@aptos_framework); + vector::push_back( + &mut validator_set.pending_active, + generate_validator_info(pool_address, stake_pool, *validator_config) + ); + let validator_set_size = vector::length(&validator_set.active_validators) + vector::length( + &validator_set.pending_active + ); + assert!(validator_set_size <= MAX_VALIDATOR_SET_SIZE, error::invalid_argument(EVALIDATOR_SET_TOO_LARGE)); + + if (std::features::module_event_migration_enabled()) { + event::emit(JoinValidatorSet { pool_address }); + }; + event::emit_event( + &mut stake_pool.join_validator_set_events, + JoinValidatorSetEvent { pool_address }, + ); + } + + /// Similar to unlock_with_cap but will use ownership capability from the signing account. + public entry fun unlock(owner: &signer, amount: u64) acquires OwnerCapability, StakePool { + assert_reconfig_not_in_progress(); + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + let ownership_cap = borrow_global(owner_address); + unlock_with_cap(amount, ownership_cap); + } + + /// Unlock `amount` from the active stake. Only possible if the lockup has expired. + public fun unlock_with_cap(amount: u64, owner_cap: &OwnerCapability) acquires StakePool { + assert_reconfig_not_in_progress(); + // Short-circuit if amount to unlock is 0 so we don't emit events. + if (amount == 0) { + return + }; + + // Unlocked coins are moved to pending_inactive. When the current lockup cycle expires, they will be moved into + // inactive in the earliest possible epoch transition. + let pool_address = owner_cap.pool_address; + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global_mut(pool_address); + // Cap amount to unlock by maximum active stake. + let amount = min(amount, coin::value(&stake_pool.active)); + let unlocked_stake = coin::extract(&mut stake_pool.active, amount); + coin::merge(&mut stake_pool.pending_inactive, unlocked_stake); + + if (std::features::module_event_migration_enabled()) { + event::emit( + UnlockStake { + pool_address, + amount_unlocked: amount, + }, + ); + }; + event::emit_event( + &mut stake_pool.unlock_stake_events, + UnlockStakeEvent { + pool_address, + amount_unlocked: amount, + }, + ); + } + + /// Withdraw from `account`'s inactive stake. + public entry fun withdraw( + owner: &signer, + withdraw_amount: u64 + ) acquires OwnerCapability, StakePool, ValidatorSet { + let owner_address = signer::address_of(owner); + assert_owner_cap_exists(owner_address); + let ownership_cap = borrow_global(owner_address); + let coins = withdraw_with_cap(ownership_cap, withdraw_amount); + coin::deposit(owner_address, coins); + } + + /// Withdraw from `pool_address`'s inactive stake with the corresponding `owner_cap`. + public fun withdraw_with_cap( + owner_cap: &OwnerCapability, + withdraw_amount: u64 + ): Coin acquires StakePool, ValidatorSet { + assert_reconfig_not_in_progress(); + let pool_address = owner_cap.pool_address; + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global_mut(pool_address); + // There's an edge case where a validator unlocks their stake and leaves the validator set before + // the stake is fully unlocked (the current lockup cycle has not expired yet). + // This can leave their stake stuck in pending_inactive even after the current lockup cycle expires. + if (get_validator_state(pool_address) == VALIDATOR_STATUS_INACTIVE && + timestamp::now_seconds() >= stake_pool.locked_until_secs) { + let pending_inactive_stake = coin::extract_all(&mut stake_pool.pending_inactive); + coin::merge(&mut stake_pool.inactive, pending_inactive_stake); + }; + + // Cap withdraw amount by total inactive coins. + withdraw_amount = min(withdraw_amount, coin::value(&stake_pool.inactive)); + if (withdraw_amount == 0) return coin::zero(); + + if (std::features::module_event_migration_enabled()) { + event::emit( + WithdrawStake { + pool_address, + amount_withdrawn: withdraw_amount, + }, + ); + }; + event::emit_event( + &mut stake_pool.withdraw_stake_events, + WithdrawStakeEvent { + pool_address, + amount_withdrawn: withdraw_amount, + }, + ); + + coin::extract(&mut stake_pool.inactive, withdraw_amount) + } + + /// Request to have `pool_address` leave the validator set. The validator is only actually removed from the set when + /// the next epoch starts. + /// The last validator in the set cannot leave. This is an edge case that should never happen as long as the network + /// is still operational. + /// + /// Can only be called by the operator of the validator/staking pool. + public entry fun leave_validator_set( + operator: &signer, + pool_address: address + ) acquires StakePool, ValidatorSet { + assert_reconfig_not_in_progress(); + let config = staking_config::get(); + assert!( + staking_config::get_allow_validator_set_change(&config), + error::invalid_argument(ENO_POST_GENESIS_VALIDATOR_SET_CHANGE_ALLOWED), + ); + + assert_stake_pool_exists(pool_address); + let stake_pool = borrow_global_mut(pool_address); + // Account has to be the operator. + assert!(signer::address_of(operator) == stake_pool.operator_address, error::unauthenticated(ENOT_OPERATOR)); + + let validator_set = borrow_global_mut(@aptos_framework); + // If the validator is still pending_active, directly kick the validator out. + let maybe_pending_active_index = find_validator(&validator_set.pending_active, pool_address); + if (option::is_some(&maybe_pending_active_index)) { + vector::swap_remove( + &mut validator_set.pending_active, option::extract(&mut maybe_pending_active_index)); + + // Decrease the voting power increase as the pending validator's voting power was added when they requested + // to join. Now that they changed their mind, their voting power should not affect the joining limit of this + // epoch. + let validator_stake = (get_next_epoch_voting_power(stake_pool) as u128); + // total_joining_power should be larger than validator_stake but just in case there has been a small + // rounding error somewhere that can lead to an underflow, we still want to allow this transaction to + // succeed. + if (validator_set.total_joining_power > validator_stake) { + validator_set.total_joining_power = validator_set.total_joining_power - validator_stake; + } else { + validator_set.total_joining_power = 0; + }; + } else { + // Validate that the validator is already part of the validator set. + let maybe_active_index = find_validator(&validator_set.active_validators, pool_address); + assert!(option::is_some(&maybe_active_index), error::invalid_state(ENOT_VALIDATOR)); + let validator_info = vector::swap_remove( + &mut validator_set.active_validators, option::extract(&mut maybe_active_index)); + assert!(vector::length(&validator_set.active_validators) > 0, error::invalid_state(ELAST_VALIDATOR)); + vector::push_back(&mut validator_set.pending_inactive, validator_info); + + if (std::features::module_event_migration_enabled()) { + event::emit(LeaveValidatorSet { pool_address }); + }; + event::emit_event( + &mut stake_pool.leave_validator_set_events, + LeaveValidatorSetEvent { + pool_address, + }, + ); + }; + } + + /// Returns true if the current validator can still vote in the current epoch. + /// This includes validators that requested to leave but are still in the pending_inactive queue and will be removed + /// when the epoch starts. + public fun is_current_epoch_validator(pool_address: address): bool acquires ValidatorSet { + assert_stake_pool_exists(pool_address); + let validator_state = get_validator_state(pool_address); + validator_state == VALIDATOR_STATUS_ACTIVE || validator_state == VALIDATOR_STATUS_PENDING_INACTIVE + } + + /// Update the validator performance (proposal statistics). This is only called by block::prologue(). + /// This function cannot abort. + public(friend) fun update_performance_statistics( + proposer_index: Option, + failed_proposer_indices: vector + ) acquires ValidatorPerformance { + // Validator set cannot change until the end of the epoch, so the validator index in arguments should + // match with those of the validators in ValidatorPerformance resource. + let validator_perf = borrow_global_mut(@aptos_framework); + let validator_len = vector::length(&validator_perf.validators); + + spec { + update ghost_valid_perf = validator_perf; + update ghost_proposer_idx = proposer_index; + }; + // proposer_index is an option because it can be missing (for NilBlocks) + if (option::is_some(&proposer_index)) { + let cur_proposer_index = option::extract(&mut proposer_index); + // Here, and in all other vector::borrow, skip any validator indices that are out of bounds, + // this ensures that this function doesn't abort if there are out of bounds errors. + if (cur_proposer_index < validator_len) { + let validator = vector::borrow_mut(&mut validator_perf.validators, cur_proposer_index); + spec { + assume validator.successful_proposals + 1 <= MAX_U64; + }; + validator.successful_proposals = validator.successful_proposals + 1; + }; + }; + + let f = 0; + let f_len = vector::length(&failed_proposer_indices); + while ({ + spec { + invariant len(validator_perf.validators) == validator_len; + invariant (option::spec_is_some(ghost_proposer_idx) && option::spec_borrow( + ghost_proposer_idx + ) < validator_len) ==> + (validator_perf.validators[option::spec_borrow(ghost_proposer_idx)].successful_proposals == + ghost_valid_perf.validators[option::spec_borrow(ghost_proposer_idx)].successful_proposals + 1); + }; + f < f_len + }) { + let validator_index = *vector::borrow(&failed_proposer_indices, f); + if (validator_index < validator_len) { + let validator = vector::borrow_mut(&mut validator_perf.validators, validator_index); + spec { + assume validator.failed_proposals + 1 <= MAX_U64; + }; + validator.failed_proposals = validator.failed_proposals + 1; + }; + f = f + 1; + }; + } + + /// Triggered during a reconfiguration. This function shouldn't abort. + /// + /// 1. Distribute transaction fees and rewards to stake pools of active and pending inactive validators (requested + /// to leave but not yet removed). + /// 2. Officially move pending active stake to active and move pending inactive stake to inactive. + /// The staking pool's voting power in this new epoch will be updated to the total active stake. + /// 3. Add pending active validators to the active set if they satisfy requirements so they can vote and remove + /// pending inactive validators so they no longer can vote. + /// 4. The validator's voting power in the validator set is updated to be the corresponding staking pool's voting + /// power. + public(friend) fun on_new_epoch( + ) acquires StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + let validator_set = borrow_global_mut(@aptos_framework); + let config = staking_config::get(); + let validator_perf = borrow_global_mut(@aptos_framework); + + // Process pending stake and distribute transaction fees and rewards for each currently active validator. + vector::for_each_ref(&validator_set.active_validators, |validator| { + let validator: &ValidatorInfo = validator; + update_stake_pool(validator_perf, validator.addr, &config); + }); + + // Process pending stake and distribute transaction fees and rewards for each currently pending_inactive validator + // (requested to leave but not removed yet). + vector::for_each_ref(&validator_set.pending_inactive, |validator| { + let validator: &ValidatorInfo = validator; + update_stake_pool(validator_perf, validator.addr, &config); + }); + + // Activate currently pending_active validators. + append(&mut validator_set.active_validators, &mut validator_set.pending_active); + + // Officially deactivate all pending_inactive validators. They will now no longer receive rewards. + validator_set.pending_inactive = vector::empty(); + + // Update active validator set so that network address/public key change takes effect. + // Moreover, recalculate the total voting power, and deactivate the validator whose + // voting power is less than the minimum required stake. + let next_epoch_validators = vector::empty(); + let (minimum_stake, _) = staking_config::get_required_stake(&config); + let vlen = vector::length(&validator_set.active_validators); + let total_voting_power = 0; + let i = 0; + while ({ + spec { + invariant spec_validators_are_initialized(next_epoch_validators); + invariant i <= vlen; + }; + i < vlen + }) { + let old_validator_info = vector::borrow_mut(&mut validator_set.active_validators, i); + let pool_address = old_validator_info.addr; + let validator_config = borrow_global_mut(pool_address); + let stake_pool = borrow_global_mut(pool_address); + let new_validator_info = generate_validator_info(pool_address, stake_pool, *validator_config); + + // A validator needs at least the min stake required to join the validator set. + if (new_validator_info.voting_power >= minimum_stake) { + spec { + assume total_voting_power + new_validator_info.voting_power <= MAX_U128; + }; + total_voting_power = total_voting_power + (new_validator_info.voting_power as u128); + vector::push_back(&mut next_epoch_validators, new_validator_info); + }; + i = i + 1; + }; + + validator_set.active_validators = next_epoch_validators; + validator_set.total_voting_power = total_voting_power; + validator_set.total_joining_power = 0; + + // Update validator indices, reset performance scores, and renew lockups. + validator_perf.validators = vector::empty(); + let recurring_lockup_duration_secs = staking_config::get_recurring_lockup_duration(&config); + let vlen = vector::length(&validator_set.active_validators); + let validator_index = 0; + while ({ + spec { + invariant spec_validators_are_initialized(validator_set.active_validators); + invariant len(validator_set.pending_active) == 0; + invariant len(validator_set.pending_inactive) == 0; + invariant 0 <= validator_index && validator_index <= vlen; + invariant vlen == len(validator_set.active_validators); + invariant forall i in 0..validator_index: + global(validator_set.active_validators[i].addr).validator_index < validator_index; + invariant forall i in 0..validator_index: + validator_set.active_validators[i].config.validator_index < validator_index; + invariant len(validator_perf.validators) == validator_index; + }; + validator_index < vlen + }) { + let validator_info = vector::borrow_mut(&mut validator_set.active_validators, validator_index); + validator_info.config.validator_index = validator_index; + let validator_config = borrow_global_mut(validator_info.addr); + validator_config.validator_index = validator_index; + + vector::push_back(&mut validator_perf.validators, IndividualValidatorPerformance { + successful_proposals: 0, + failed_proposals: 0, + }); + + // Automatically renew a validator's lockup for validators that will still be in the validator set in the + // next epoch. + let stake_pool = borrow_global_mut(validator_info.addr); + let now_secs = timestamp::now_seconds(); + let reconfig_start_secs = if (chain_status::is_operating()) { + get_reconfig_start_time_secs() + } else { + now_secs + }; + if (stake_pool.locked_until_secs <= reconfig_start_secs) { + spec { + assume now_secs + recurring_lockup_duration_secs <= MAX_U64; + }; + stake_pool.locked_until_secs = now_secs + recurring_lockup_duration_secs; + }; + + validator_index = validator_index + 1; + }; + + if (features::periodical_reward_rate_decrease_enabled()) { + // Update rewards rate after reward distribution. + staking_config::calculate_and_save_latest_epoch_rewards_rate(); + }; + } + + /// Return the `ValidatorConsensusInfo` of each current validator, sorted by current validator index. + public fun cur_validator_consensus_infos(): vector acquires ValidatorSet { + let validator_set = borrow_global(@aptos_framework); + validator_consensus_infos_from_validator_set(validator_set) + } + + + public fun next_validator_consensus_infos(): vector acquires ValidatorSet, ValidatorPerformance, StakePool, ValidatorFees, ValidatorConfig { + // Init. + let cur_validator_set = borrow_global(@aptos_framework); + let staking_config = staking_config::get(); + let validator_perf = borrow_global(@aptos_framework); + let (minimum_stake, _) = staking_config::get_required_stake(&staking_config); + let (rewards_rate, rewards_rate_denominator) = staking_config::get_reward_rate(&staking_config); + + // Compute new validator set. + let new_active_validators = vector[]; + let num_new_actives = 0; + let candidate_idx = 0; + let new_total_power = 0; + let num_cur_actives = vector::length(&cur_validator_set.active_validators); + let num_cur_pending_actives = vector::length(&cur_validator_set.pending_active); + spec { + assume num_cur_actives + num_cur_pending_actives <= MAX_U64; + }; + let num_candidates = num_cur_actives + num_cur_pending_actives; + while ({ + spec { + invariant candidate_idx <= num_candidates; + invariant spec_validators_are_initialized(new_active_validators); + invariant len(new_active_validators) == num_new_actives; + invariant forall i in 0..len(new_active_validators): + new_active_validators[i].config.validator_index == i; + invariant num_new_actives <= candidate_idx; + invariant spec_validators_are_initialized(new_active_validators); + }; + candidate_idx < num_candidates + }) { + let candidate_in_current_validator_set = candidate_idx < num_cur_actives; + let candidate = if (candidate_idx < num_cur_actives) { + vector::borrow(&cur_validator_set.active_validators, candidate_idx) + } else { + vector::borrow(&cur_validator_set.pending_active, candidate_idx - num_cur_actives) + }; + let stake_pool = borrow_global(candidate.addr); + let cur_active = coin::value(&stake_pool.active); + let cur_pending_active = coin::value(&stake_pool.pending_active); + let cur_pending_inactive = coin::value(&stake_pool.pending_inactive); + + let cur_reward = if (candidate_in_current_validator_set && cur_active > 0) { + spec { + assert candidate.config.validator_index < len(validator_perf.validators); + }; + let cur_perf = vector::borrow(&validator_perf.validators, candidate.config.validator_index); + spec { + assume cur_perf.successful_proposals + cur_perf.failed_proposals <= MAX_U64; + }; + calculate_rewards_amount(cur_active, cur_perf.successful_proposals, cur_perf.successful_proposals + cur_perf.failed_proposals, rewards_rate, rewards_rate_denominator) + } else { + 0 + }; + + let cur_fee = 0; + if (features::collect_and_distribute_gas_fees()) { + let fees_table = &borrow_global(@aptos_framework).fees_table; + if (table::contains(fees_table, candidate.addr)) { + let fee_coin = table::borrow(fees_table, candidate.addr); + cur_fee = coin::value(fee_coin); + } + }; + + let lockup_expired = get_reconfig_start_time_secs() >= stake_pool.locked_until_secs; + spec { + assume cur_active + cur_pending_active + cur_reward + cur_fee <= MAX_U64; + assume cur_active + cur_pending_inactive + cur_pending_active + cur_reward + cur_fee <= MAX_U64; + }; + let new_voting_power = + cur_active + + if (lockup_expired) { 0 } else { cur_pending_inactive } + + cur_pending_active + + cur_reward + cur_fee; + + if (new_voting_power >= minimum_stake) { + let config = *borrow_global(candidate.addr); + config.validator_index = num_new_actives; + let new_validator_info = ValidatorInfo { + addr: candidate.addr, + voting_power: new_voting_power, + config, + }; + + // Update ValidatorSet. + spec { + assume new_total_power + new_voting_power <= MAX_U128; + }; + new_total_power = new_total_power + (new_voting_power as u128); + vector::push_back(&mut new_active_validators, new_validator_info); + num_new_actives = num_new_actives + 1; + + }; + candidate_idx = candidate_idx + 1; + }; + + let new_validator_set = ValidatorSet { + consensus_scheme: cur_validator_set.consensus_scheme, + active_validators: new_active_validators, + pending_inactive: vector[], + pending_active: vector[], + total_voting_power: new_total_power, + total_joining_power: 0, + }; + + validator_consensus_infos_from_validator_set(&new_validator_set) + } + + fun validator_consensus_infos_from_validator_set(validator_set: &ValidatorSet): vector { + let validator_consensus_infos = vector[]; + + let num_active = vector::length(&validator_set.active_validators); + let num_pending_inactive = vector::length(&validator_set.pending_inactive); + spec { + assume num_active + num_pending_inactive <= MAX_U64; + }; + let total = num_active + num_pending_inactive; + + // Pre-fill the return value with dummy values. + let idx = 0; + while ({ + spec { + invariant idx <= len(validator_set.active_validators) + len(validator_set.pending_inactive); + invariant len(validator_consensus_infos) == idx; + invariant len(validator_consensus_infos) <= len(validator_set.active_validators) + len(validator_set.pending_inactive); + }; + idx < total + }) { + vector::push_back(&mut validator_consensus_infos, validator_consensus_info::default()); + idx = idx + 1; + }; + spec { + assert len(validator_consensus_infos) == len(validator_set.active_validators) + len(validator_set.pending_inactive); + assert spec_validator_indices_are_valid_config(validator_set.active_validators, + len(validator_set.active_validators) + len(validator_set.pending_inactive)); + }; + + vector::for_each_ref(&validator_set.active_validators, |obj| { + let vi: &ValidatorInfo = obj; + spec { + assume len(validator_consensus_infos) == len(validator_set.active_validators) + len(validator_set.pending_inactive); + assert vi.config.validator_index < len(validator_consensus_infos); + }; + let vci = vector::borrow_mut(&mut validator_consensus_infos, vi.config.validator_index); + *vci = validator_consensus_info::new( + vi.addr, + vi.config.consensus_pubkey, + vi.voting_power + ); + spec { + assert len(validator_consensus_infos) == len(validator_set.active_validators) + len(validator_set.pending_inactive); + }; + }); + + vector::for_each_ref(&validator_set.pending_inactive, |obj| { + let vi: &ValidatorInfo = obj; + spec { + assume len(validator_consensus_infos) == len(validator_set.active_validators) + len(validator_set.pending_inactive); + assert vi.config.validator_index < len(validator_consensus_infos); + }; + let vci = vector::borrow_mut(&mut validator_consensus_infos, vi.config.validator_index); + *vci = validator_consensus_info::new( + vi.addr, + vi.config.consensus_pubkey, + vi.voting_power + ); + spec { + assert len(validator_consensus_infos) == len(validator_set.active_validators) + len(validator_set.pending_inactive); + }; + }); + + validator_consensus_infos + } + + fun addresses_from_validator_infos(infos: &vector): vector
{ + vector::map_ref(infos, |obj| { + let info: &ValidatorInfo = obj; + info.addr + }) + } + + /// Calculate the stake amount of a stake pool for the next epoch. + /// Update individual validator's stake pool if `commit == true`. + /// + /// 1. distribute transaction fees to active/pending_inactive delegations + /// 2. distribute rewards to active/pending_inactive delegations + /// 3. process pending_active, pending_inactive correspondingly + /// This function shouldn't abort. + fun update_stake_pool( + validator_perf: &ValidatorPerformance, + pool_address: address, + staking_config: &StakingConfig, + ) acquires StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorFees { + let stake_pool = borrow_global_mut(pool_address); + let validator_config = borrow_global(pool_address); + let cur_validator_perf = vector::borrow(&validator_perf.validators, validator_config.validator_index); + let num_successful_proposals = cur_validator_perf.successful_proposals; + spec { + // The following addition should not overflow because `num_total_proposals` cannot be larger than 86400, + // the maximum number of proposals in a day (1 proposal per second). + assume cur_validator_perf.successful_proposals + cur_validator_perf.failed_proposals <= MAX_U64; + }; + let num_total_proposals = cur_validator_perf.successful_proposals + cur_validator_perf.failed_proposals; + let (rewards_rate, rewards_rate_denominator) = staking_config::get_reward_rate(staking_config); + let rewards_active = distribute_rewards( + &mut stake_pool.active, + num_successful_proposals, + num_total_proposals, + rewards_rate, + rewards_rate_denominator + ); + let rewards_pending_inactive = distribute_rewards( + &mut stake_pool.pending_inactive, + num_successful_proposals, + num_total_proposals, + rewards_rate, + rewards_rate_denominator + ); + spec { + assume rewards_active + rewards_pending_inactive <= MAX_U64; + }; + let rewards_amount = rewards_active + rewards_pending_inactive; + // Pending active stake can now be active. + coin::merge(&mut stake_pool.active, coin::extract_all(&mut stake_pool.pending_active)); + + // Additionally, distribute transaction fees. + if (features::collect_and_distribute_gas_fees()) { + let fees_table = &mut borrow_global_mut(@aptos_framework).fees_table; + if (table::contains(fees_table, pool_address)) { + let coin = table::remove(fees_table, pool_address); + coin::merge(&mut stake_pool.active, coin); + }; + }; + + // Pending inactive stake is only fully unlocked and moved into inactive if the current lockup cycle has expired + let current_lockup_expiration = stake_pool.locked_until_secs; + if (get_reconfig_start_time_secs() >= current_lockup_expiration) { + coin::merge( + &mut stake_pool.inactive, + coin::extract_all(&mut stake_pool.pending_inactive), + ); + }; + + if (std::features::module_event_migration_enabled()) { + event::emit(DistributeRewards { pool_address, rewards_amount }); + }; + event::emit_event( + &mut stake_pool.distribute_rewards_events, + DistributeRewardsEvent { + pool_address, + rewards_amount, + }, + ); + } + + /// Assuming we are in a middle of a reconfiguration (no matter it is immediate or async), get its start time. + fun get_reconfig_start_time_secs(): u64 { + if (reconfiguration_state::is_initialized()) { + reconfiguration_state::start_time_secs() + } else { + timestamp::now_seconds() + } + } + + /// Calculate the rewards amount. + fun calculate_rewards_amount( + stake_amount: u64, + num_successful_proposals: u64, + num_total_proposals: u64, + rewards_rate: u64, + rewards_rate_denominator: u64, + ): u64 { + spec { + // The following condition must hold because + // (1) num_successful_proposals <= num_total_proposals, and + // (2) `num_total_proposals` cannot be larger than 86400, the maximum number of proposals + // in a day (1 proposal per second), and `num_total_proposals` is reset to 0 every epoch. + assume num_successful_proposals * MAX_REWARDS_RATE <= MAX_U64; + }; + // The rewards amount is equal to (stake amount * rewards rate * performance multiplier). + // We do multiplication in u128 before division to avoid the overflow and minimize the rounding error. + let rewards_numerator = (stake_amount as u128) * (rewards_rate as u128) * (num_successful_proposals as u128); + let rewards_denominator = (rewards_rate_denominator as u128) * (num_total_proposals as u128); + if (rewards_denominator > 0) { + ((rewards_numerator / rewards_denominator) as u64) + } else { + 0 + } + } + + /// Mint rewards corresponding to current epoch's `stake` and `num_successful_votes`. + fun distribute_rewards( + stake: &mut Coin, + num_successful_proposals: u64, + num_total_proposals: u64, + rewards_rate: u64, + rewards_rate_denominator: u64, + ): u64 acquires AptosCoinCapabilities { + let stake_amount = coin::value(stake); + let rewards_amount = if (stake_amount > 0) { + calculate_rewards_amount( + stake_amount, + num_successful_proposals, + num_total_proposals, + rewards_rate, + rewards_rate_denominator + ) + } else { + 0 + }; + if (rewards_amount > 0) { + let mint_cap = &borrow_global(@aptos_framework).mint_cap; + let rewards = coin::mint(rewards_amount, mint_cap); + coin::merge(stake, rewards); + }; + rewards_amount + } + + fun append(v1: &mut vector, v2: &mut vector) { + while (!vector::is_empty(v2)) { + vector::push_back(v1, vector::pop_back(v2)); + } + } + + fun find_validator(v: &vector, addr: address): Option { + let i = 0; + let len = vector::length(v); + while ({ + spec { + invariant !(exists j in 0..i: v[j].addr == addr); + }; + i < len + }) { + if (vector::borrow(v, i).addr == addr) { + return option::some(i) + }; + i = i + 1; + }; + option::none() + } + + fun generate_validator_info(addr: address, stake_pool: &StakePool, config: ValidatorConfig): ValidatorInfo { + let voting_power = get_next_epoch_voting_power(stake_pool); + ValidatorInfo { + addr, + voting_power, + config, + } + } + + /// Returns validator's next epoch voting power, including pending_active, active, and pending_inactive stake. + fun get_next_epoch_voting_power(stake_pool: &StakePool): u64 { + let value_pending_active = coin::value(&stake_pool.pending_active); + let value_active = coin::value(&stake_pool.active); + let value_pending_inactive = coin::value(&stake_pool.pending_inactive); + spec { + assume value_pending_active + value_active + value_pending_inactive <= MAX_U64; + }; + value_pending_active + value_active + value_pending_inactive + } + + fun update_voting_power_increase(increase_amount: u64) acquires ValidatorSet { + let validator_set = borrow_global_mut(@aptos_framework); + let voting_power_increase_limit = + (staking_config::get_voting_power_increase_limit(&staking_config::get()) as u128); + validator_set.total_joining_power = validator_set.total_joining_power + (increase_amount as u128); + + // Only validator voting power increase if the current validator set's voting power > 0. + if (validator_set.total_voting_power > 0) { + assert!( + validator_set.total_joining_power <= validator_set.total_voting_power * voting_power_increase_limit / 100, + error::invalid_argument(EVOTING_POWER_INCREASE_EXCEEDS_LIMIT), + ); + } + } + + fun assert_stake_pool_exists(pool_address: address) { + assert!(stake_pool_exists(pool_address), error::invalid_argument(ESTAKE_POOL_DOES_NOT_EXIST)); + } + + /// This provides an ACL for Testnet purposes. In testnet, everyone is a whale, a whale can be a validator. + /// This allows a testnet to bring additional entities into the validator set without compromising the + /// security of the testnet. This will NOT be enabled in Mainnet. + struct AllowedValidators has key { + accounts: vector
, + } + + public fun configure_allowed_validators( + aptos_framework: &signer, + accounts: vector
+ ) acquires AllowedValidators { + let aptos_framework_address = signer::address_of(aptos_framework); + system_addresses::assert_aptos_framework(aptos_framework); + if (!exists(aptos_framework_address)) { + move_to(aptos_framework, AllowedValidators { accounts }); + } else { + let allowed = borrow_global_mut(aptos_framework_address); + allowed.accounts = accounts; + } + } + + fun is_allowed(account: address): bool acquires AllowedValidators { + if (!exists(@aptos_framework)) { + true + } else { + let allowed = borrow_global(@aptos_framework); + vector::contains(&allowed.accounts, &account) + } + } + + fun assert_owner_cap_exists(owner: address) { + assert!(exists(owner), error::not_found(EOWNER_CAP_NOT_FOUND)); + } + + fun assert_reconfig_not_in_progress() { + assert!(!reconfiguration_state::is_in_progress(), error::invalid_state(ERECONFIGURATION_IN_PROGRESS)); + } + + #[test_only] + use aptos_framework::aptos_coin; + use aptos_std::bls12381::proof_of_possession_from_bytes; + use aptos_framework::reconfiguration_state; + use aptos_framework::validator_consensus_info; + use aptos_framework::validator_consensus_info::ValidatorConsensusInfo; + #[test_only] + use aptos_std::fixed_point64; + + #[test_only] + const EPOCH_DURATION: u64 = 60; + + #[test_only] + const LOCKUP_CYCLE_SECONDS: u64 = 3600; + + #[test_only] + public fun initialize_for_test(aptos_framework: &signer) { + reconfiguration_state::initialize(aptos_framework); + initialize_for_test_custom(aptos_framework, 100, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 100, 1000000); + } + + #[test_only] + public fun join_validator_set_for_test( + pk: &bls12381::PublicKey, + pop: &bls12381::ProofOfPossession, + operator: &signer, + pool_address: address, + should_end_epoch: bool, + ) acquires AptosCoinCapabilities, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + let pk_bytes = bls12381::public_key_to_bytes(pk); + let pop_bytes = bls12381::proof_of_possession_to_bytes(pop); + rotate_consensus_key(operator, pool_address, pk_bytes, pop_bytes); + join_validator_set(operator, pool_address); + if (should_end_epoch) { + end_epoch(); + } + } + + #[test_only] + public fun fast_forward_to_unlock(pool_address: address) + acquires AptosCoinCapabilities, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + let expiration_time = get_lockup_secs(pool_address); + timestamp::update_global_time_for_test_secs(expiration_time); + end_epoch(); + } + + // Convenient function for setting up all required stake initializations. + #[test_only] + public fun initialize_for_test_custom( + aptos_framework: &signer, + minimum_stake: u64, + maximum_stake: u64, + recurring_lockup_secs: u64, + allow_validator_set_change: bool, + rewards_rate_numerator: u64, + rewards_rate_denominator: u64, + voting_power_increase_limit: u64, + ) { + timestamp::set_time_has_started_for_testing(aptos_framework); + reconfiguration_state::initialize(aptos_framework); + if (!exists(@aptos_framework)) { + initialize(aptos_framework); + }; + staking_config::initialize_for_test( + aptos_framework, + minimum_stake, + maximum_stake, + recurring_lockup_secs, + allow_validator_set_change, + rewards_rate_numerator, + rewards_rate_denominator, + voting_power_increase_limit, + ); + + if (!exists(@aptos_framework)) { + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(aptos_framework); + store_aptos_coin_mint_cap(aptos_framework, mint_cap); + coin::destroy_burn_cap(burn_cap); + }; + } + + // This function assumes the stake module already the capability to mint aptos coins. + #[test_only] + public fun mint_coins(amount: u64): Coin acquires AptosCoinCapabilities { + let mint_cap = &borrow_global(@aptos_framework).mint_cap; + coin::mint(amount, mint_cap) + } + + #[test_only] + public fun mint(account: &signer, amount: u64) acquires AptosCoinCapabilities { + coin::register(account); + coin::deposit(signer::address_of(account), mint_coins(amount)); + } + + #[test_only] + public fun mint_and_add_stake( + account: &signer, amount: u64) acquires AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorSet { + mint(account, amount); + add_stake(account, amount); + } + + #[test_only] + public fun initialize_test_validator( + public_key: &bls12381::PublicKey, + proof_of_possession: &bls12381::ProofOfPossession, + validator: &signer, + amount: u64, + should_join_validator_set: bool, + should_end_epoch: bool, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + let validator_address = signer::address_of(validator); + if (!account::exists_at(signer::address_of(validator))) { + account::create_account_for_test(validator_address); + }; + + let pk_bytes = bls12381::public_key_to_bytes(public_key); + let pop_bytes = bls12381::proof_of_possession_to_bytes(proof_of_possession); + initialize_validator(validator, pk_bytes, pop_bytes, vector::empty(), vector::empty()); + + if (amount > 0) { + mint_and_add_stake(validator, amount); + }; + + if (should_join_validator_set) { + join_validator_set(validator, validator_address); + }; + if (should_end_epoch) { + end_epoch(); + }; + } + + #[test_only] + public fun create_validator_set( + aptos_framework: &signer, + active_validator_addresses: vector
, + public_keys: vector, + ) { + let active_validators = vector::empty(); + let i = 0; + while (i < vector::length(&active_validator_addresses)) { + let validator_address = vector::borrow(&active_validator_addresses, i); + let pk = vector::borrow(&public_keys, i); + vector::push_back(&mut active_validators, ValidatorInfo { + addr: *validator_address, + voting_power: 0, + config: ValidatorConfig { + consensus_pubkey: bls12381::public_key_to_bytes(pk), + network_addresses: b"", + fullnode_addresses: b"", + validator_index: 0, + } + }); + i = i + 1; + }; + + move_to(aptos_framework, ValidatorSet { + consensus_scheme: 0, + // active validators for the current epoch + active_validators, + // pending validators to leave in next epoch (still active) + pending_inactive: vector::empty(), + // pending validators to join in next epoch + pending_active: vector::empty(), + total_voting_power: 0, + total_joining_power: 0, + }); + } + + #[test_only] + public fun create_stake_pool( + account: &signer, + active: Coin, + pending_inactive: Coin, + locked_until_secs: u64, + ) acquires AllowedValidators, OwnerCapability, StakePool, ValidatorSet { + let account_address = signer::address_of(account); + initialize_stake_owner(account, 0, account_address, account_address); + let stake_pool = borrow_global_mut(account_address); + coin::merge(&mut stake_pool.active, active); + coin::merge(&mut stake_pool.pending_inactive, pending_inactive); + stake_pool.locked_until_secs = locked_until_secs; + } + + // Allows unit tests to set custom validator performances. + #[test_only] + public fun update_validator_performances_for_test( + proposer_index: Option, + failed_proposer_indices: vector, + ) acquires ValidatorPerformance { + update_performance_statistics(proposer_index, failed_proposer_indices); + } + + #[test_only] + public fun generate_identity(): (bls12381::SecretKey, bls12381::PublicKey, bls12381::ProofOfPossession) { + let (sk, pkpop) = bls12381::generate_keys(); + let pop = bls12381::generate_proof_of_possession(&sk); + let unvalidated_pk = bls12381::public_key_with_pop_to_normal(&pkpop); + (sk, unvalidated_pk, pop) + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_inactive_validator_can_add_stake_if_exceeding_max_allowed( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, false, false); + + // Add more stake to exceed max. This should fail. + mint_and_add_stake(validator, 9901); + } + + #[test(aptos_framework = @0x1, validator_1 = @0x123, validator_2 = @0x234)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_pending_active_validator_cannot_add_stake_if_exceeding_max_allowed( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 100000); + // Have one validator join the set to ensure the validator set is not empty when main validator joins. + let (_sk_1, pk_1, pop_1) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, true, true); + + // Validator 2 joins validator set but epoch has not ended so validator is in pending_active state. + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, false); + + // Add more stake to exceed max. This should fail. + mint_and_add_stake(validator_2, 9901); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_active_validator_cannot_add_stake_if_exceeding_max_allowed( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + // Validator joins validator set and waits for epoch end so it's in the validator set. + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Add more stake to exceed max. This should fail. + mint_and_add_stake(validator, 9901); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_active_validator_with_pending_inactive_stake_cannot_add_stake_if_exceeding_max_allowed( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + // Validator joins validator set and waits for epoch end so it's in the validator set. + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Request to unlock 50 coins, which go to pending_inactive. Validator has 50 remaining in active. + unlock(validator, 50); + assert_validator_state(signer::address_of(validator), 50, 0, 0, 50, 0); + + // Add 9901 more. Total stake is 50 (active) + 50 (pending_inactive) + 9901 > 10000 so still exceeding max. + mint_and_add_stake(validator, 9901); + } + + #[test(aptos_framework = @aptos_framework, validator_1 = @0x123, validator_2 = @0x234)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_pending_inactive_cannot_add_stake_if_exceeding_max_allowed( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, true, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, true); + + // Leave validator set so validator is in pending_inactive state. + leave_validator_set(validator_1, signer::address_of(validator_1)); + + // Add 9901 more. Total stake is 50 (active) + 50 (pending_inactive) + 9901 > 10000 so still exceeding max. + mint_and_add_stake(validator_1, 9901); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_end_to_end( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Validator has a lockup now that they've joined the validator set. + let validator_address = signer::address_of(validator); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 1); + + // Validator adds more stake while already being active. + // The added stake should go to pending_active to wait for activation when next epoch starts. + mint(validator, 900); + add_stake(validator, 100); + assert!(coin::balance(validator_address) == 800, 2); + assert_validator_state(validator_address, 100, 0, 100, 0, 0); + + // Pending_active stake is activated in the new epoch. + // Rewards of 1 coin are also distributed for the existing active stake of 100 coins. + end_epoch(); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 3); + assert_validator_state(validator_address, 201, 0, 0, 0, 0); + + // Request unlock of 100 coins. These 100 coins are moved to pending_inactive and will be unlocked when the + // current lockup expires. + unlock(validator, 100); + assert_validator_state(validator_address, 101, 0, 0, 100, 0); + + // Enough time has passed so the current lockup cycle should have ended. + // The first epoch after the lockup cycle ended should automatically move unlocked (pending_inactive) stake + // to inactive. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + // Rewards were also minted to pending_inactive, which got all moved to inactive. + assert_validator_state(validator_address, 102, 101, 0, 0, 0); + // Lockup is renewed and validator is still active. + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 4); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 5); + + // Validator withdraws from inactive stake multiple times. + withdraw(validator, 50); + assert!(coin::balance(validator_address) == 850, 6); + assert_validator_state(validator_address, 102, 51, 0, 0, 0); + withdraw(validator, 51); + assert!(coin::balance(validator_address) == 901, 7); + assert_validator_state(validator_address, 102, 0, 0, 0, 0); + + // Enough time has passed again and the validator's lockup is renewed once more. Validator is still active. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 8); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 9); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_inactive_validator_with_existing_lockup_join_validator_set( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, false, false); + + // Validator sets lockup before even joining the set and lets half of lockup pass by. + increase_lockup(validator); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS / 2); + let validator_address = signer::address_of(validator); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS / 2, 1); + + // Join the validator set with an existing lockup + join_validator_set(validator, validator_address); + + // Validator is added to the set but lockup time shouldn't have changed. + end_epoch(); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 2); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS / 2 - EPOCH_DURATION, 3); + assert_validator_state(validator_address, 100, 0, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x10012, location = Self)] + public entry fun test_cannot_reduce_lockup( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, false, false); + + // Increase lockup. + increase_lockup(validator); + // Reduce recurring lockup to 0. + staking_config::update_recurring_lockup_duration_secs(aptos_framework, 1); + // INcrease lockup should now fail because the new lockup < old lockup. + increase_lockup(validator); + } + + #[test(aptos_framework = @aptos_framework, validator_1 = @0x123, validator_2 = @0x234)] + #[expected_failure(abort_code = 0x1000D, location = Self)] + public entry fun test_inactive_validator_cannot_join_if_exceed_increase_limit( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // Only 50% voting power increase is allowed in each epoch. + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 50); + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, false, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, false, false); + + // Validator 1 needs to be in the set so validator 2's added stake counts against the limit. + join_validator_set(validator_1, signer::address_of(validator_1)); + end_epoch(); + + // Validator 2 joins the validator set but their stake would lead to exceeding the voting power increase limit. + // Therefore, this should fail. + join_validator_set(validator_2, signer::address_of(validator_2)); + } + + #[test(aptos_framework = @aptos_framework, validator_1 = @0x123, validator_2 = @0x234)] + public entry fun test_pending_active_validator_can_add_more_stake( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 10000); + // Need 1 validator to be in the active validator set so joining limit works. + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, false, true); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, false, false); + + // Add more stake while still pending_active. + let validator_2_address = signer::address_of(validator_2); + join_validator_set(validator_2, validator_2_address); + assert!(get_validator_state(validator_2_address) == VALIDATOR_STATUS_PENDING_ACTIVE, 0); + mint_and_add_stake(validator_2, 100); + assert_validator_state(validator_2_address, 200, 0, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator_1 = @0x123, validator_2 = @0x234)] + #[expected_failure(abort_code = 0x1000D, location = Self)] + public entry fun test_pending_active_validator_cannot_add_more_stake_than_limit( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // 100% voting power increase is allowed in each epoch. + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 100); + // Need 1 validator to be in the active validator set so joining limit works. + let (_sk_1, pk_1, pop_1) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, true, true); + + // Validator 2 joins the validator set but epoch has not ended so they're still pending_active. + // Current voting power increase is already 100%. This is not failing yet. + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, false); + + // Add more stake, which now exceeds the 100% limit. This should fail. + mint_and_add_stake(validator_2, 1); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_pending_active_validator_leaves_validator_set( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + // Validator joins but epoch hasn't ended, so the validator is still pending_active. + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, false); + let validator_address = signer::address_of(validator); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_PENDING_ACTIVE, 0); + + // Check that voting power increase is tracked. + assert!(borrow_global(@aptos_framework).total_joining_power == 100, 0); + + // Leave the validator set immediately. + leave_validator_set(validator, validator_address); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_INACTIVE, 1); + + // Check that voting power increase has been decreased when the pending active validator leaves. + assert!(borrow_global(@aptos_framework).total_joining_power == 0, 1); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x1000D, location = Self)] + public entry fun test_active_validator_cannot_add_more_stake_than_limit_in_multiple_epochs( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // Only 50% voting power increase is allowed in each epoch. + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 50); + // Add initial stake and join the validator set. + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + let validator_address = signer::address_of(validator); + assert_validator_state(validator_address, 100, 0, 0, 0, 0); + end_epoch(); + assert_validator_state(validator_address, 110, 0, 0, 0, 0); + end_epoch(); + assert_validator_state(validator_address, 121, 0, 0, 0, 0); + // Add more than 50% limit. The following line should fail. + mint_and_add_stake(validator, 99); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x1000D, location = Self)] + public entry fun test_active_validator_cannot_add_more_stake_than_limit( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // Only 50% voting power increase is allowed in each epoch. + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 50); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Add more than 50% limit. This should fail. + mint_and_add_stake(validator, 51); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_validator_unlock_partial_stake( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // Reward rate = 10%. + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 100); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Unlock half of the coins. + let validator_address = signer::address_of(validator); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 1); + unlock(validator, 50); + assert_validator_state(validator_address, 50, 0, 0, 50, 0); + + // Enough time has passed so the current lockup cycle should have ended. + // 50 coins should have unlocked while the remaining 51 (50 + rewards) should stay locked for another cycle. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 2); + // Validator received rewards in both active and pending inactive. + assert_validator_state(validator_address, 55, 55, 0, 0, 0); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 3); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_validator_can_withdraw_all_stake_and_rewards_at_once( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + let validator_address = signer::address_of(validator); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 0); + + // One more epoch passes to generate rewards. + end_epoch(); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 1); + assert_validator_state(validator_address, 101, 0, 0, 0, 0); + + // Unlock all coins while still having a lockup. + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS - EPOCH_DURATION, 2); + unlock(validator, 101); + assert_validator_state(validator_address, 0, 0, 0, 101, 0); + + // One more epoch passes while the current lockup cycle (3600 secs) has not ended. + timestamp::fast_forward_seconds(1000); + end_epoch(); + // Validator should not be removed from the validator set since their 100 coins in pending_inactive state should + // still count toward voting power. + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 3); + assert_validator_state(validator_address, 0, 0, 0, 102, 0); + + // Enough time has passed so the current lockup cycle should have ended. Funds are now fully unlocked. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + assert_validator_state(validator_address, 0, 103, 0, 0, 0); + // Validator ahs been kicked out of the validator set as their stake is 0 now. + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_INACTIVE, 4); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_validator_unlocking_more_than_available_stake_should_cap( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, false, false); + + // Validator unlocks more stake than they have active. This should limit the unlock to 100. + unlock(validator, 200); + assert_validator_state(signer::address_of(validator), 0, 0, 0, 100, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_validator_withdraw_should_cap_by_inactive_stake( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + // Initial balance = 900 (idle) + 100 (staked) = 1000. + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + mint(validator, 900); + + // Validator unlocks stake. + unlock(validator, 100); + // Enough time has passed so the stake is fully unlocked. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + + // Validator can only withdraw a max of 100 unlocked coins even if they request to withdraw more than 100. + withdraw(validator, 200); + let validator_address = signer::address_of(validator); + // Receive back all coins with an extra 1 for rewards. + assert!(coin::balance(validator_address) == 1001, 2); + assert_validator_state(validator_address, 0, 0, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_validator_can_reactivate_pending_inactive_stake( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Validator unlocks stake, which gets moved into pending_inactive. + unlock(validator, 50); + let validator_address = signer::address_of(validator); + assert_validator_state(validator_address, 50, 0, 0, 50, 0); + + // Validator can reactivate pending_inactive stake. + reactivate_stake(validator, 50); + assert_validator_state(validator_address, 100, 0, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_validator_reactivate_more_than_available_pending_inactive_stake_should_cap( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Validator tries to reactivate more than available pending_inactive stake, which should limit to 50. + unlock(validator, 50); + let validator_address = signer::address_of(validator); + assert_validator_state(validator_address, 50, 0, 0, 50, 0); + reactivate_stake(validator, 51); + assert_validator_state(validator_address, 100, 0, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_active_validator_having_insufficient_remaining_stake_after_withdrawal_gets_kicked( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + // Unlock enough coins that the remaining is not enough to meet the min required. + let validator_address = signer::address_of(validator); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 1); + unlock(validator, 50); + assert_validator_state(validator_address, 50, 0, 0, 50, 0); + + // Enough time has passed so the current lockup cycle should have ended. + // 50 coins should have unlocked while the remaining 51 (50 + rewards) is not enough so the validator is kicked + // from the validator set. + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 2); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_INACTIVE, 2); + assert_validator_state(validator_address, 50, 50, 0, 0, 0); + // Lockup is no longer renewed since the validator is no longer a part of the validator set. + assert!(get_remaining_lockup_secs(validator_address) == 0, 3); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, validator_2 = @0x234)] + public entry fun test_active_validator_leaves_staking_but_still_has_a_lockup( + aptos_framework: &signer, + validator: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator, 100, true, false); + // We need a second validator here just so the first validator can leave. + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, true); + + // Leave the validator set while still having a lockup. + let validator_address = signer::address_of(validator); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 0); + leave_validator_set(validator, validator_address); + // Validator is in pending_inactive state but is technically still part of the validator set. + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_PENDING_INACTIVE, 2); + assert_validator_state(validator_address, 100, 0, 0, 0, 1); + end_epoch(); + + // Epoch has ended so validator is no longer part of the validator set. + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_INACTIVE, 3); + // However, their stake, including rewards, should still subject to the existing lockup. + assert_validator_state(validator_address, 101, 0, 0, 0, 1); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS - EPOCH_DURATION, 4); + + // If they try to unlock, their stake is moved to pending_inactive and would only be withdrawable after the + // lockup has expired. + unlock(validator, 50); + assert_validator_state(validator_address, 51, 0, 0, 50, 1); + // A couple of epochs passed but lockup has not expired so the validator's stake remains the same. + end_epoch(); + end_epoch(); + end_epoch(); + assert_validator_state(validator_address, 51, 0, 0, 50, 1); + // Fast forward enough so the lockup expires. Now the validator can just call withdraw directly to withdraw + // pending_inactive stakes. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + withdraw(validator, 50); + assert_validator_state(validator_address, 51, 0, 0, 0, 1); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123, validator_2 = @0x234)] + public entry fun test_active_validator_leaves_staking_and_rejoins_with_expired_lockup_should_be_renewed( + aptos_framework: &signer, + validator: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator, 100, true, false); + // We need a second validator here just so the first validator can leave. + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, true); + + // Leave the validator set while still having a lockup. + let validator_address = signer::address_of(validator); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 0); + leave_validator_set(validator, validator_address); + end_epoch(); + + // Fast forward enough so the lockup expires. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + assert!(get_remaining_lockup_secs(validator_address) == 0, 1); + + // Validator rejoins the validator set. Once the current epoch ends, their lockup should be automatically + // renewed. + join_validator_set(validator, validator_address); + end_epoch(); + assert!(get_validator_state(validator_address) == VALIDATOR_STATUS_ACTIVE, 2); + assert!(get_remaining_lockup_secs(validator_address) == LOCKUP_CYCLE_SECONDS, 2); + } + + #[test(aptos_framework = @aptos_framework, validator_1 = @0x123, validator_2 = @0x234)] + public entry fun test_pending_inactive_validator_does_not_count_in_increase_limit( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // Only 50% voting power increase is allowed in each epoch. + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 10, 50); + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, true, false); + // We need a second validator here just so the first validator can leave. + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, true); + + // Validator 1 leaves the validator set. Epoch has not ended so they're still pending_inactive. + leave_validator_set(validator_1, signer::address_of(validator_1)); + // Validator 1 adds more stake. This should not succeed as it should not count as a voting power increase. + mint_and_add_stake(validator_1, 51); + } + + #[test(aptos_framework = @0x1, validator_1 = @0x123, validator_2 = @0x234, validator_3 = @0x345)] + public entry fun test_multiple_validators_join_and_leave( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + validator_3: &signer + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + let validator_1_address = signer::address_of(validator_1); + let validator_2_address = signer::address_of(validator_2); + let validator_3_address = signer::address_of(validator_3); + + initialize_for_test_custom(aptos_framework, 100, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 100, 100); + let (_sk_1, pk_1, pop_1) = generate_identity(); + let pk_1_bytes = bls12381::public_key_to_bytes(&pk_1); + let (_sk_2, pk_2, pop_2) = generate_identity(); + let (_sk_3, pk_3, pop_3) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, false, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, false, false); + initialize_test_validator(&pk_3, &pop_3, validator_3, 100, false, false); + + // Validator 1 and 2 join the validator set. + join_validator_set(validator_2, validator_2_address); + join_validator_set(validator_1, validator_1_address); + end_epoch(); + assert!(get_validator_state(validator_1_address) == VALIDATOR_STATUS_ACTIVE, 0); + assert!(get_validator_state(validator_2_address) == VALIDATOR_STATUS_ACTIVE, 1); + + // Validator indices is the reverse order of the joining order. + assert_validator_state(validator_1_address, 100, 0, 0, 0, 0); + assert_validator_state(validator_2_address, 100, 0, 0, 0, 1); + let validator_set = borrow_global(@aptos_framework); + let validator_config_1 = vector::borrow(&validator_set.active_validators, 0); + assert!(validator_config_1.addr == validator_1_address, 2); + assert!(validator_config_1.config.validator_index == 0, 3); + let validator_config_2 = vector::borrow(&validator_set.active_validators, 1); + assert!(validator_config_2.addr == validator_2_address, 4); + assert!(validator_config_2.config.validator_index == 1, 5); + + // Validator 1 rotates consensus key. Validator 2 leaves. Validator 3 joins. + let (_sk_1b, pk_1b, pop_1b) = generate_identity(); + let pk_1b_bytes = bls12381::public_key_to_bytes(&pk_1b); + let pop_1b_bytes = bls12381::proof_of_possession_to_bytes(&pop_1b); + rotate_consensus_key(validator_1, validator_1_address, pk_1b_bytes, pop_1b_bytes); + leave_validator_set(validator_2, validator_2_address); + join_validator_set(validator_3, validator_3_address); + // Validator 2 is not effectively removed until next epoch. + assert!(get_validator_state(validator_2_address) == VALIDATOR_STATUS_PENDING_INACTIVE, 6); + assert!( + vector::borrow( + &borrow_global(@aptos_framework).pending_inactive, + 0 + ).addr == validator_2_address, + 0 + ); + // Validator 3 is not effectively added until next epoch. + assert!(get_validator_state(validator_3_address) == VALIDATOR_STATUS_PENDING_ACTIVE, 7); + assert!( + vector::borrow( + &borrow_global(@aptos_framework).pending_active, + 0 + ).addr == validator_3_address, + 0 + ); + assert!( + vector::borrow( + &borrow_global(@aptos_framework).active_validators, + 0 + ).config.consensus_pubkey == pk_1_bytes, + 0 + ); + + // Changes applied after new epoch + end_epoch(); + assert!(get_validator_state(validator_1_address) == VALIDATOR_STATUS_ACTIVE, 8); + assert_validator_state(validator_1_address, 101, 0, 0, 0, 0); + assert!(get_validator_state(validator_2_address) == VALIDATOR_STATUS_INACTIVE, 9); + // The validator index of validator 2 stays the same but this doesn't matter as the next time they rejoin the + // validator set, their index will get set correctly. + assert_validator_state(validator_2_address, 101, 0, 0, 0, 1); + assert!(get_validator_state(validator_3_address) == VALIDATOR_STATUS_ACTIVE, 10); + assert_validator_state(validator_3_address, 100, 0, 0, 0, 1); + assert!( + vector::borrow( + &borrow_global(@aptos_framework).active_validators, + 0 + ).config.consensus_pubkey == pk_1b_bytes, + 0 + ); + + // Validators without enough stake will be removed. + unlock(validator_1, 50); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + assert!(get_validator_state(validator_1_address) == VALIDATOR_STATUS_INACTIVE, 11); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_delegated_staking_with_owner_cap( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test_custom(aptos_framework, 100, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 100, 100); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 0, false, false); + let owner_cap = extract_owner_cap(validator); + + // Add stake when the validator is not yet activated. + add_stake_with_cap(&owner_cap, mint_coins(100)); + let pool_address = signer::address_of(validator); + assert_validator_state(pool_address, 100, 0, 0, 0, 0); + + // Join the validator set with enough stake. + join_validator_set(validator, pool_address); + end_epoch(); + assert!(get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 0); + + // Unlock the entire stake. + unlock_with_cap(100, &owner_cap); + assert_validator_state(pool_address, 0, 0, 0, 100, 0); + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + + // Withdraw stake + rewards. + assert_validator_state(pool_address, 0, 101, 0, 0, 0); + let coins = withdraw_with_cap(&owner_cap, 101); + assert!(coin::value(&coins) == 101, 1); + assert_validator_state(pool_address, 0, 0, 0, 0, 0); + + // Operator can separately rotate consensus key. + let (_sk_new, pk_new, pop_new) = generate_identity(); + let pk_new_bytes = bls12381::public_key_to_bytes(&pk_new); + let pop_new_bytes = bls12381::proof_of_possession_to_bytes(&pop_new); + rotate_consensus_key(validator, pool_address, pk_new_bytes, pop_new_bytes); + let validator_config = borrow_global(pool_address); + assert!(validator_config.consensus_pubkey == pk_new_bytes, 2); + + // Operator can update network and fullnode addresses. + update_network_and_fullnode_addresses(validator, pool_address, b"1", b"2"); + let validator_config = borrow_global(pool_address); + assert!(validator_config.network_addresses == b"1", 3); + assert!(validator_config.fullnode_addresses == b"2", 4); + + // Cleanups. + coin::register(validator); + coin::deposit(pool_address, coins); + deposit_owner_cap(validator, owner_cap); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x1000A, location = Self)] + public entry fun test_validator_cannot_join_post_genesis( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test_custom(aptos_framework, 100, 10000, LOCKUP_CYCLE_SECONDS, false, 1, 100, 100); + + // Joining the validator set should fail as post genesis validator set change is not allowed. + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x1000E, location = Self)] + public entry fun test_invalid_pool_address( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + join_validator_set(validator, @0x234); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x1000A, location = Self)] + public entry fun test_validator_cannot_leave_post_genesis( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test_custom(aptos_framework, 100, 10000, LOCKUP_CYCLE_SECONDS, false, 1, 100, 100); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, false, false); + + // Bypass the check to join. This is the same function called during Genesis. + let validator_address = signer::address_of(validator); + join_validator_set_internal(validator, validator_address); + end_epoch(); + + // Leaving the validator set should fail as post genesis validator set change is not allowed. + leave_validator_set(validator, validator_address); + } + + #[test( + aptos_framework = @aptos_framework, + validator_1 = @aptos_framework, + validator_2 = @0x2, + validator_3 = @0x3, + validator_4 = @0x4, + validator_5 = @0x5 + )] + fun test_validator_consensus_infos_from_validator_set( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + validator_3: &signer, + validator_4: &signer, + validator_5: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + let v1_addr = signer::address_of(validator_1); + let v2_addr = signer::address_of(validator_2); + let v3_addr = signer::address_of(validator_3); + let v4_addr = signer::address_of(validator_4); + let v5_addr = signer::address_of(validator_5); + + initialize_for_test(aptos_framework); + + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + let (_sk_3, pk_3, pop_3) = generate_identity(); + let (_sk_4, pk_4, pop_4) = generate_identity(); + let (_sk_5, pk_5, pop_5) = generate_identity(); + let pk_1_bytes = bls12381::public_key_to_bytes(&pk_1); + let pk_3_bytes = bls12381::public_key_to_bytes(&pk_3); + let pk_5_bytes = bls12381::public_key_to_bytes(&pk_5); + + initialize_test_validator(&pk_1, &pop_1, validator_1, 101, false, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 102, false, false); + initialize_test_validator(&pk_3, &pop_3, validator_3, 103, false, false); + initialize_test_validator(&pk_4, &pop_4, validator_4, 104, false, false); + initialize_test_validator(&pk_5, &pop_5, validator_5, 105, false, false); + + join_validator_set(validator_3, v3_addr); + join_validator_set(validator_1, v1_addr); + join_validator_set(validator_5, v5_addr); + end_epoch(); + let vci_vec_0 = validator_consensus_infos_from_validator_set(borrow_global(@aptos_framework)); + let vci_addrs = vector::map_ref(&vci_vec_0, |obj|{ + let vci: &ValidatorConsensusInfo = obj; + validator_consensus_info::get_addr(vci) + }); + let vci_pks = vector::map_ref(&vci_vec_0, |obj|{ + let vci: &ValidatorConsensusInfo = obj; + validator_consensus_info::get_pk_bytes(vci) + }); + let vci_voting_powers = vector::map_ref(&vci_vec_0, |obj|{ + let vci: &ValidatorConsensusInfo = obj; + validator_consensus_info::get_voting_power(vci) + }); + assert!(vector[@0x5, @aptos_framework, @0x3] == vci_addrs, 1); + assert!(vector[pk_5_bytes, pk_1_bytes, pk_3_bytes] == vci_pks, 2); + assert!(vector[105, 101, 103] == vci_voting_powers, 3); + leave_validator_set(validator_3, v3_addr); + let vci_vec_1 = validator_consensus_infos_from_validator_set(borrow_global(@aptos_framework)); + assert!(vci_vec_0 == vci_vec_1, 11); + join_validator_set(validator_2, v2_addr); + let vci_vec_2 = validator_consensus_infos_from_validator_set(borrow_global(@aptos_framework)); + assert!(vci_vec_0 == vci_vec_2, 12); + leave_validator_set(validator_1, v1_addr); + let vci_vec_3 = validator_consensus_infos_from_validator_set(borrow_global(@aptos_framework)); + assert!(vci_vec_0 == vci_vec_3, 13); + join_validator_set(validator_4, v4_addr); + let vci_vec_4 = validator_consensus_infos_from_validator_set(borrow_global(@aptos_framework)); + assert!(vci_vec_0 == vci_vec_4, 14); + } + + #[test( + aptos_framework = @aptos_framework, + validator_1 = @aptos_framework, + validator_2 = @0x2, + validator_3 = @0x3, + validator_4 = @0x4, + validator_5 = @0x5 + )] + public entry fun test_staking_validator_index( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + validator_3: &signer, + validator_4: &signer, + validator_5: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + let v1_addr = signer::address_of(validator_1); + let v2_addr = signer::address_of(validator_2); + let v3_addr = signer::address_of(validator_3); + let v4_addr = signer::address_of(validator_4); + let v5_addr = signer::address_of(validator_5); + + initialize_for_test(aptos_framework); + + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + let (_sk_3, pk_3, pop_3) = generate_identity(); + let (_sk_4, pk_4, pop_4) = generate_identity(); + let (_sk_5, pk_5, pop_5) = generate_identity(); + + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, false, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, false, false); + initialize_test_validator(&pk_3, &pop_3, validator_3, 100, false, false); + initialize_test_validator(&pk_4, &pop_4, validator_4, 100, false, false); + initialize_test_validator(&pk_5, &pop_5, validator_5, 100, false, false); + + join_validator_set(validator_3, v3_addr); + end_epoch(); + assert!(get_validator_index(v3_addr) == 0, 0); + + join_validator_set(validator_4, v4_addr); + end_epoch(); + assert!(get_validator_index(v3_addr) == 0, 1); + assert!(get_validator_index(v4_addr) == 1, 2); + + join_validator_set(validator_1, v1_addr); + join_validator_set(validator_2, v2_addr); + // pending_inactive is appended in reverse order + end_epoch(); + assert!(get_validator_index(v3_addr) == 0, 6); + assert!(get_validator_index(v4_addr) == 1, 7); + assert!(get_validator_index(v2_addr) == 2, 8); + assert!(get_validator_index(v1_addr) == 3, 9); + + join_validator_set(validator_5, v5_addr); + end_epoch(); + assert!(get_validator_index(v3_addr) == 0, 10); + assert!(get_validator_index(v4_addr) == 1, 11); + assert!(get_validator_index(v2_addr) == 2, 12); + assert!(get_validator_index(v1_addr) == 3, 13); + assert!(get_validator_index(v5_addr) == 4, 14); + + // after swap remove, it's 3,4,2,5 + leave_validator_set(validator_1, v1_addr); + // after swap remove, it's 5,4,2 + leave_validator_set(validator_3, v3_addr); + end_epoch(); + + assert!(get_validator_index(v5_addr) == 0, 15); + assert!(get_validator_index(v4_addr) == 1, 16); + assert!(get_validator_index(v2_addr) == 2, 17); + } + + #[test(aptos_framework = @aptos_framework, validator_1 = @0x123, validator_2 = @0x234)] + public entry fun test_validator_rewards_are_performance_based( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + + let validator_1_address = signer::address_of(validator_1); + let validator_2_address = signer::address_of(validator_2); + + // Both validators join the set. + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, true, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, true); + + // Validator 2 failed proposal. + let failed_proposer_indices = vector::empty(); + let validator_1_index = borrow_global(validator_1_address).validator_index; + let validator_2_index = borrow_global(validator_2_address).validator_index; + vector::push_back(&mut failed_proposer_indices, validator_2_index); + let proposer_indices = option::some(validator_1_index); + update_performance_statistics(proposer_indices, failed_proposer_indices); + end_epoch(); + + // Validator 2 received no rewards. Validator 1 didn't fail proposals, so it still receives rewards. + assert_validator_state(validator_1_address, 101, 0, 0, 0, 1); + assert_validator_state(validator_2_address, 100, 0, 0, 0, 0); + + // Validator 2 decides to leave. Both validators failed proposals. + unlock(validator_2, 100); + leave_validator_set(validator_2, validator_2_address); + let failed_proposer_indices = vector::empty(); + let validator_1_index = borrow_global(validator_1_address).validator_index; + let validator_2_index = borrow_global(validator_2_address).validator_index; + vector::push_back(&mut failed_proposer_indices, validator_1_index); + vector::push_back(&mut failed_proposer_indices, validator_2_index); + update_performance_statistics(option::none(), failed_proposer_indices); + // Fast forward so validator 2's stake is fully unlocked. + timestamp::fast_forward_seconds(LOCKUP_CYCLE_SECONDS); + end_epoch(); + + // Validator 1 and 2 received no additional rewards due to failed proposals + assert_validator_state(validator_1_address, 101, 0, 0, 0, 0); + assert_validator_state(validator_2_address, 0, 100, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator_1 = @0x123, validator_2 = @0x234)] + public entry fun test_validator_rewards_rate_decrease_over_time( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + + let genesis_time_in_secs = timestamp::now_seconds(); + + let validator_1_address = signer::address_of(validator_1); + let validator_2_address = signer::address_of(validator_2); + + // Both validators join the set. + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 1000, true, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 10000, true, true); + + // One epoch passed. Validator 1 and validator 2 should receive rewards at rewards rate = 1% every epoch. + end_epoch(); + assert_validator_state(validator_1_address, 1010, 0, 0, 0, 1); + assert_validator_state(validator_2_address, 10100, 0, 0, 0, 0); + + // Enable rewards rate decrease. Initially rewards rate is still 1% every epoch. Rewards rate halves every year. + let one_year_in_secs: u64 = 31536000; + staking_config::initialize_rewards( + aptos_framework, + fixed_point64::create_from_rational(1, 100), + fixed_point64::create_from_rational(3, 1000), + one_year_in_secs, + genesis_time_in_secs, + fixed_point64::create_from_rational(50, 100), + ); + features::change_feature_flags_for_testing(aptos_framework, vector[features::get_periodical_reward_rate_decrease_feature()], vector[]); + + // For some reason, this epoch is very long. It has been 1 year since genesis when the epoch ends. + timestamp::fast_forward_seconds(one_year_in_secs - EPOCH_DURATION * 3); + end_epoch(); + // Validator 1 and validator 2 should still receive rewards at rewards rate = 1% every epoch. Rewards rate has halved after this epoch. + assert_validator_state(validator_1_address, 1020, 0, 0, 0, 1); + assert_validator_state(validator_2_address, 10200, 0, 0, 0, 0); + + // For some reason, this epoch is also very long. One year passed. + timestamp::fast_forward_seconds(one_year_in_secs - EPOCH_DURATION); + end_epoch(); + // Validator 1 and validator 2 should still receive rewards at rewards rate = 0.5% every epoch. Rewards rate has halved after this epoch. + assert_validator_state(validator_1_address, 1025, 0, 0, 0, 1); + assert_validator_state(validator_2_address, 10250, 0, 0, 0, 0); + + end_epoch(); + // Rewards rate has halved but cannot become lower than min_rewards_rate. + // Validator 1 and validator 2 should receive rewards at rewards rate = 0.3% every epoch. + assert_validator_state(validator_1_address, 1028, 0, 0, 0, 1); + assert_validator_state(validator_2_address, 10280, 0, 0, 0, 0); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_update_performance_statistics_should_not_fail_due_to_out_of_bounds( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + + let validator_address = signer::address_of(validator); + let (_sk, pk, pop) = generate_identity(); + initialize_test_validator(&pk, &pop, validator, 100, true, true); + + let valid_validator_index = borrow_global(validator_address).validator_index; + let out_of_bounds_index = valid_validator_index + 100; + + // Invalid validator index in the failed proposers vector should not lead to abort. + let failed_proposer_indices = vector::empty(); + vector::push_back(&mut failed_proposer_indices, valid_validator_index); + vector::push_back(&mut failed_proposer_indices, out_of_bounds_index); + update_performance_statistics(option::none(), failed_proposer_indices); + end_epoch(); + + // Validator received no rewards due to failing to propose. + assert_validator_state(validator_address, 100, 0, 0, 0, 0); + + // Invalid validator index in the proposer should not lead to abort. + let proposer_index_optional = option::some(out_of_bounds_index); + update_performance_statistics(proposer_index_optional, vector::empty()); + end_epoch(); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + #[expected_failure(abort_code = 0x1000B, location = Self)] + public entry fun test_invalid_config( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorSet { + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 100, 100); + + // Call initialize_stake_owner, which only initializes the stake pool but not validator config. + let validator_address = signer::address_of(validator); + account::create_account_for_test(validator_address); + initialize_stake_owner(validator, 0, validator_address, validator_address); + mint_and_add_stake(validator, 100); + + // Join the validator set with enough stake. This should fail because the validator didn't initialize validator + // config. + join_validator_set(validator, validator_address); + } + + #[test(aptos_framework = @aptos_framework, validator = @0x123)] + public entry fun test_valid_config( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorSet { + initialize_for_test_custom(aptos_framework, 50, 10000, LOCKUP_CYCLE_SECONDS, true, 1, 100, 100); + + // Call initialize_stake_owner, which only initializes the stake pool but not validator config. + let validator_address = signer::address_of(validator); + account::create_account_for_test(validator_address); + initialize_stake_owner(validator, 0, validator_address, validator_address); + mint_and_add_stake(validator, 100); + + // Initialize validator config. + let validator_address = signer::address_of(validator); + let (_sk_new, pk_new, pop_new) = generate_identity(); + let pk_new_bytes = bls12381::public_key_to_bytes(&pk_new); + let pop_new_bytes = bls12381::proof_of_possession_to_bytes(&pop_new); + rotate_consensus_key(validator, validator_address, pk_new_bytes, pop_new_bytes); + + // Join the validator set with enough stake. This now wouldn't fail since the validator config already exists. + join_validator_set(validator, validator_address); + } + + #[test] + public entry fun test_rewards_calculation() { + let stake_amount = 2000; + let num_successful_proposals = 199; + let num_total_proposals = 200; + let rewards_rate = 700; + let rewards_rate_denominator = 777; + let rewards_amount = calculate_rewards_amount( + stake_amount, + num_successful_proposals, + num_total_proposals, + rewards_rate, + rewards_rate_denominator + ); + // Consider `amount_imprecise` and `amount_precise` defined as follows: + // amount_imprecise = (stake_amount * rewards_rate / rewards_rate_denominator) * num_successful_proposals / num_total_proposals + // amount_precise = stake_amount * rewards_rate * num_successful_proposals / (rewards_rate_denominator * num_total_proposals) + // Although they are equivalent in the real arithmetic, they are not in the integer arithmetic due to a rounding error. + // With the test parameters above, `amount_imprecise` is equal to 1791 because of an unbounded rounding error + // while `amount_precise` is equal to 1792. We expect the output of `calculate_rewards_amount` to be 1792. + assert!(rewards_amount == 1792, 0); + + let stake_amount = 100000000000000000; + let num_successful_proposals = 9999; + let num_total_proposals = 10000; + let rewards_rate = 3141592; + let rewards_rate_denominator = 10000000; + // This should not abort due to an arithmetic overflow. + let rewards_amount = calculate_rewards_amount( + stake_amount, + num_successful_proposals, + num_total_proposals, + rewards_rate, + rewards_rate_denominator + ); + assert!(rewards_amount == 31412778408000000, 0); + } + + #[test_only] + public fun set_validator_perf_at_least_one_block() acquires ValidatorPerformance { + let validator_perf = borrow_global_mut(@aptos_framework); + vector::for_each_mut(&mut validator_perf.validators, |validator|{ + let validator: &mut IndividualValidatorPerformance = validator; + if (validator.successful_proposals + validator.failed_proposals < 1) { + validator.successful_proposals = 1; + }; + }); + } + + #[test(aptos_framework = @0x1, validator_1 = @0x123, validator_2 = @0x234)] + public entry fun test_removing_validator_from_active_set( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + initialize_for_test(aptos_framework); + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, true, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, true); + assert!(vector::length(&borrow_global(@aptos_framework).active_validators) == 2, 0); + + // Remove validator 1 from the active validator set. Only validator 2 remains. + let validator_to_remove = signer::address_of(validator_1); + remove_validators(aptos_framework, &vector[validator_to_remove]); + assert!(vector::length(&borrow_global(@aptos_framework).active_validators) == 1, 0); + assert!(get_validator_state(validator_to_remove) == VALIDATOR_STATUS_PENDING_INACTIVE, 1); + } + + #[test_only] + public fun end_epoch( + ) acquires StakePool, AptosCoinCapabilities, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // Set the number of blocks to 1, to give out rewards to non-failing validators. + set_validator_perf_at_least_one_block(); + timestamp::fast_forward_seconds(EPOCH_DURATION); + reconfiguration_state::on_reconfig_start(); + on_new_epoch(); + reconfiguration_state::on_reconfig_finish(); + } + + #[test_only] + public fun assert_stake_pool( + pool_address: address, + active_stake: u64, + inactive_stake: u64, + pending_active_stake: u64, + pending_inactive_stake: u64, + ) acquires StakePool { + let stake_pool = borrow_global(pool_address); + let actual_active_stake = coin::value(&stake_pool.active); + assert!(actual_active_stake == active_stake, actual_active_stake); + let actual_inactive_stake = coin::value(&stake_pool.inactive); + assert!(actual_inactive_stake == inactive_stake, actual_inactive_stake); + let actual_pending_active_stake = coin::value(&stake_pool.pending_active); + assert!(actual_pending_active_stake == pending_active_stake, actual_pending_active_stake); + let actual_pending_inactive_stake = coin::value(&stake_pool.pending_inactive); + assert!(actual_pending_inactive_stake == pending_inactive_stake, actual_pending_inactive_stake); + } + + #[test_only] + public fun assert_validator_state( + pool_address: address, + active_stake: u64, + inactive_stake: u64, + pending_active_stake: u64, + pending_inactive_stake: u64, + validator_index: u64, + ) acquires StakePool, ValidatorConfig { + assert_stake_pool(pool_address, active_stake, inactive_stake, pending_active_stake, pending_inactive_stake); + let validator_config = borrow_global(pool_address); + assert!(validator_config.validator_index == validator_index, validator_config.validator_index); + } + + #[test(aptos_framework = @0x1, validator = @0x123)] + public entry fun test_allowed_validators( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, ValidatorSet { + let addr = signer::address_of(validator); + let (burn, mint) = aptos_coin::initialize_for_test(aptos_framework); + configure_allowed_validators(aptos_framework, vector[addr]); + + account::create_account_for_test(addr); + coin::register(validator); + initialize_stake_owner(validator, 0, addr, addr); + coin::destroy_burn_cap(burn); + coin::destroy_mint_cap(mint); + } + + #[test(aptos_framework = @0x1, validator = @0x123)] + #[expected_failure(abort_code = 0x60011, location = Self)] + public entry fun test_not_allowed_validators( + aptos_framework: &signer, + validator: &signer, + ) acquires AllowedValidators, OwnerCapability, StakePool, ValidatorSet { + configure_allowed_validators(aptos_framework, vector[]); + let (burn, mint) = aptos_coin::initialize_for_test(aptos_framework); + + let addr = signer::address_of(validator); + account::create_account_for_test(addr); + coin::register(validator); + initialize_stake_owner(validator, 0, addr, addr); + coin::destroy_burn_cap(burn); + coin::destroy_mint_cap(mint); + } + + #[test_only] + public fun with_rewards(amount: u64): u64 { + let (numerator, denominator) = staking_config::get_reward_rate(&staking_config::get()); + amount + amount * numerator / denominator + } + + #[test_only] + public fun get_validator_fee(validator_addr: address): u64 acquires ValidatorFees { + let fees_table = &borrow_global(@aptos_framework).fees_table; + let coin = table::borrow(fees_table, validator_addr); + coin::value(coin) + } + + #[test_only] + public fun assert_no_fees_for_validator(validator_addr: address) acquires ValidatorFees { + let fees_table = &borrow_global(@aptos_framework).fees_table; + assert!(!table::contains(fees_table, validator_addr), 0); + } + + #[test_only] + const COLLECT_AND_DISTRIBUTE_GAS_FEES: u64 = 6; + + #[test(aptos_framework = @0x1, validator_1 = @0x123, validator_2 = @0x234, validator_3 = @0x345)] + fun test_distribute_validator_fees( + aptos_framework: &signer, + validator_1: &signer, + validator_2: &signer, + validator_3: &signer, + ) acquires AllowedValidators, AptosCoinCapabilities, OwnerCapability, StakePool, ValidatorConfig, ValidatorPerformance, ValidatorSet, ValidatorFees { + // Make sure that fees collection and distribution is enabled. + features::change_feature_flags_for_testing(aptos_framework, vector[COLLECT_AND_DISTRIBUTE_GAS_FEES], vector[]); + assert!(features::collect_and_distribute_gas_fees(), 0); + + // Initialize staking and validator fees table. + initialize_for_test(aptos_framework); + initialize_validator_fees(aptos_framework); + + let validator_1_address = signer::address_of(validator_1); + let validator_2_address = signer::address_of(validator_2); + let validator_3_address = signer::address_of(validator_3); + + // Validators join the set and epoch ends. + let (_sk_1, pk_1, pop_1) = generate_identity(); + let (_sk_2, pk_2, pop_2) = generate_identity(); + let (_sk_3, pk_3, pop_3) = generate_identity(); + initialize_test_validator(&pk_1, &pop_1, validator_1, 100, true, false); + initialize_test_validator(&pk_2, &pop_2, validator_2, 100, true, false); + initialize_test_validator(&pk_3, &pop_3, validator_3, 100, true, true); + + // Next, simulate fees collection during three blocks, where proposers are + // validators 1, 2, and 1 again. + add_transaction_fee(validator_1_address, mint_coins(100)); + add_transaction_fee(validator_2_address, mint_coins(500)); + add_transaction_fee(validator_1_address, mint_coins(200)); + + // Fess have to be assigned to the right validators, but not + // distributed yet. + assert!(get_validator_fee(validator_1_address) == 300, 0); + assert!(get_validator_fee(validator_2_address) == 500, 0); + assert_no_fees_for_validator(validator_3_address); + assert_validator_state(validator_1_address, 100, 0, 0, 0, 2); + assert_validator_state(validator_2_address, 100, 0, 0, 0, 1); + assert_validator_state(validator_3_address, 100, 0, 0, 0, 0); + + end_epoch(); + + // Epoch ended. Validators must have recieved their rewards and, most importantly, + // their fees. + assert_no_fees_for_validator(validator_1_address); + assert_no_fees_for_validator(validator_2_address); + assert_no_fees_for_validator(validator_3_address); + assert_validator_state(validator_1_address, 401, 0, 0, 0, 2); + assert_validator_state(validator_2_address, 601, 0, 0, 0, 1); + assert_validator_state(validator_3_address, 101, 0, 0, 0, 0); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/staking_config.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/staking_config.move new file mode 100644 index 000000000..aff41b494 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/staking_config.move @@ -0,0 +1,686 @@ +/// Provides the configuration for staking and rewards +module aptos_framework::staking_config { + use std::error; + use std::features; + + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + + use aptos_std::fixed_point64::{Self, FixedPoint64, less_or_equal}; + use aptos_std::math_fixed64; + + friend aptos_framework::genesis; + friend aptos_framework::stake; + + /// Stake lockup duration cannot be zero. + const EZERO_LOCKUP_DURATION: u64 = 1; + /// Reward rate denominator cannot be zero. + const EZERO_REWARDS_RATE_DENOMINATOR: u64 = 2; + /// Specified stake range is invalid. Max must be greater than min. + const EINVALID_STAKE_RANGE: u64 = 3; + /// The voting power increase limit percentage must be within (0, 50]. + const EINVALID_VOTING_POWER_INCREASE_LIMIT: u64 = 4; + /// Specified rewards rate is invalid, which must be within [0, MAX_REWARDS_RATE]. + const EINVALID_REWARDS_RATE: u64 = 5; + /// Specified min rewards rate is invalid, which must be within [0, rewards_rate]. + const EINVALID_MIN_REWARDS_RATE: u64 = 6; + /// Specified start time of last rewards rate period is invalid, which must be not late than the current timestamp. + const EINVALID_LAST_REWARDS_RATE_PERIOD_START: u64 = 7; + /// Specified rewards rate decrease rate is invalid, which must be not greater than BPS_DENOMINATOR. + const EINVALID_REWARDS_RATE_DECREASE_RATE: u64 = 8; + /// Specified rewards rate period is invalid. It must be larger than 0 and cannot be changed if configured. + const EINVALID_REWARDS_RATE_PERIOD: u64 = 9; + /// The function has been deprecated. + const EDEPRECATED_FUNCTION: u64 = 10; + /// The function is disabled or hasn't been enabled. + const EDISABLED_FUNCTION: u64 = 11; + + /// Limit the maximum value of `rewards_rate` in order to avoid any arithmetic overflow. + const MAX_REWARDS_RATE: u64 = 1000000; + /// Denominator of number in basis points. 1 bps(basis points) = 0.01%. + const BPS_DENOMINATOR: u64 = 10000; + /// 1 year => 365 * 24 * 60 * 60 + const ONE_YEAR_IN_SECS: u64 = 31536000; + + const MAX_U64: u128 = 18446744073709551615; + + + /// Validator set configurations that will be stored with the @aptos_framework account. + struct StakingConfig has copy, drop, key { + // A validator needs to stake at least this amount to be able to join the validator set. + // If after joining the validator set and at the start of any epoch, a validator's stake drops below this amount + // they will be removed from the set. + minimum_stake: u64, + // A validator can only stake at most this amount. Any larger stake will be rejected. + // If after joining the validator set and at the start of any epoch, a validator's stake exceeds this amount, + // their voting power and rewards would only be issued for the max stake amount. + maximum_stake: u64, + recurring_lockup_duration_secs: u64, + // Whether validators are allow to join/leave post genesis. + allow_validator_set_change: bool, + // DEPRECATING: staking reward configurations will be in StakingRewardsConfig once REWARD_RATE_DECREASE flag is enabled. + // The maximum rewards given out every epoch. This will be divided by the rewards rate denominator. + // For example, 0.001% (0.00001) can be represented as 10 / 1000000. + rewards_rate: u64, + // DEPRECATING: staking reward configurations will be in StakingRewardsConfig once REWARD_RATE_DECREASE flag is enabled. + rewards_rate_denominator: u64, + // Only this % of current total voting power is allowed to join the validator set in each epoch. + // This is necessary to prevent a massive amount of new stake from joining that can potentially take down the + // network if corresponding validators are not ready to participate in consensus in time. + // This value is within (0, 50%), not inclusive. + voting_power_increase_limit: u64, + } + + /// Staking reward configurations that will be stored with the @aptos_framework account. + struct StakingRewardsConfig has copy, drop, key { + // The target rewards rate given out every epoch. This will be divided by the rewards rate denominator. + // For example, 0.001% (0.00001) can be represented as 10 / 1000000. + rewards_rate: FixedPoint64, + // The minimum threshold for rewards_rate. rewards_rate won't be lower than this. + // This will be divided by the rewards rate denominator. + min_rewards_rate: FixedPoint64, + // Reward rate decreases every rewards_rate_period_in_secs seconds. + // Currently it can only equal to 1 year. Keep this field as a plceholder so we can change the reward period + // without adding new struct. + rewards_rate_period_in_secs: u64, + // Timestamp of start of last rewards period. + last_rewards_rate_period_start_in_secs: u64, + // Rate of reward rate decrease in BPS. 1 bps(basis points) = 0.01%. + rewards_rate_decrease_rate: FixedPoint64, + } + + /// Only called during genesis. + public(friend) fun initialize( + aptos_framework: &signer, + minimum_stake: u64, + maximum_stake: u64, + recurring_lockup_duration_secs: u64, + allow_validator_set_change: bool, + rewards_rate: u64, + rewards_rate_denominator: u64, + voting_power_increase_limit: u64, + ) { + system_addresses::assert_aptos_framework(aptos_framework); + + // This can fail genesis but is necessary so that any misconfigurations can be corrected before genesis succeeds + validate_required_stake(minimum_stake, maximum_stake); + + assert!(recurring_lockup_duration_secs > 0, error::invalid_argument(EZERO_LOCKUP_DURATION)); + assert!( + rewards_rate_denominator > 0, + error::invalid_argument(EZERO_REWARDS_RATE_DENOMINATOR), + ); + assert!( + voting_power_increase_limit > 0 && voting_power_increase_limit <= 50, + error::invalid_argument(EINVALID_VOTING_POWER_INCREASE_LIMIT), + ); + + // `rewards_rate` which is the numerator is limited to be `<= MAX_REWARDS_RATE` in order to avoid the arithmetic + // overflow in the rewards calculation. `rewards_rate_denominator` can be adjusted to get the desired rewards + // rate (i.e., rewards_rate / rewards_rate_denominator). + assert!(rewards_rate <= MAX_REWARDS_RATE, error::invalid_argument(EINVALID_REWARDS_RATE)); + + // We assert that (rewards_rate / rewards_rate_denominator <= 1). + assert!(rewards_rate <= rewards_rate_denominator, error::invalid_argument(EINVALID_REWARDS_RATE)); + + move_to(aptos_framework, StakingConfig { + minimum_stake, + maximum_stake, + recurring_lockup_duration_secs, + allow_validator_set_change, + rewards_rate, + rewards_rate_denominator, + voting_power_increase_limit, + }); + } + + #[view] + /// Return the reward rate of this epoch as a tuple (numerator, denominator). + public fun reward_rate(): (u64, u64) acquires StakingRewardsConfig, StakingConfig { + get_reward_rate(borrow_global(@aptos_framework)) + } + + /// Initialize rewards configurations. + /// Can only be called as part of the Aptos governance proposal process established by the AptosGovernance module. + public fun initialize_rewards( + aptos_framework: &signer, + rewards_rate: FixedPoint64, + min_rewards_rate: FixedPoint64, + rewards_rate_period_in_secs: u64, + last_rewards_rate_period_start_in_secs: u64, + rewards_rate_decrease_rate: FixedPoint64, + ) { + system_addresses::assert_aptos_framework(aptos_framework); + + validate_rewards_config( + rewards_rate, + min_rewards_rate, + rewards_rate_period_in_secs, + rewards_rate_decrease_rate, + ); + assert!( + timestamp::now_seconds() >= last_rewards_rate_period_start_in_secs, + error::invalid_argument(EINVALID_LAST_REWARDS_RATE_PERIOD_START) + ); + + move_to(aptos_framework, StakingRewardsConfig { + rewards_rate, + min_rewards_rate, + rewards_rate_period_in_secs, + last_rewards_rate_period_start_in_secs, + rewards_rate_decrease_rate, + }); + } + + public fun get(): StakingConfig acquires StakingConfig { + *borrow_global(@aptos_framework) + } + + /// Return whether validator set changes are allowed + public fun get_allow_validator_set_change(config: &StakingConfig): bool { + config.allow_validator_set_change + } + + /// Return the required min/max stake. + public fun get_required_stake(config: &StakingConfig): (u64, u64) { + (config.minimum_stake, config.maximum_stake) + } + + /// Return the recurring lockup duration that every validator is automatically renewed for (unless they unlock and + /// withdraw all funds). + public fun get_recurring_lockup_duration(config: &StakingConfig): u64 { + config.recurring_lockup_duration_secs + } + + /// Return the reward rate of this epoch. + public fun get_reward_rate(config: &StakingConfig): (u64, u64) acquires StakingRewardsConfig { + if (features::periodical_reward_rate_decrease_enabled()) { + let epoch_rewards_rate = borrow_global(@aptos_framework).rewards_rate; + if (fixed_point64::is_zero(epoch_rewards_rate)) { + (0u64, 1u64) + } else { + // Maximize denominator for higher precision. + // Restriction: nominator <= MAX_REWARDS_RATE && denominator <= MAX_U64 + let denominator = fixed_point64::divide_u128((MAX_REWARDS_RATE as u128), epoch_rewards_rate); + if (denominator > MAX_U64) { + denominator = MAX_U64 + }; + let nominator = (fixed_point64::multiply_u128(denominator, epoch_rewards_rate) as u64); + (nominator, (denominator as u64)) + } + } else { + (config.rewards_rate, config.rewards_rate_denominator) + } + } + + /// Return the joining limit %. + public fun get_voting_power_increase_limit(config: &StakingConfig): u64 { + config.voting_power_increase_limit + } + + /// Calculate and save the latest rewards rate. + public(friend) fun calculate_and_save_latest_epoch_rewards_rate(): FixedPoint64 acquires StakingRewardsConfig { + assert!(features::periodical_reward_rate_decrease_enabled(), error::invalid_state(EDISABLED_FUNCTION)); + let staking_rewards_config = calculate_and_save_latest_rewards_config(); + staking_rewards_config.rewards_rate + } + + /// Calculate and return the up-to-date StakingRewardsConfig. + fun calculate_and_save_latest_rewards_config(): StakingRewardsConfig acquires StakingRewardsConfig { + let staking_rewards_config = borrow_global_mut(@aptos_framework); + let current_time_in_secs = timestamp::now_seconds(); + assert!( + current_time_in_secs >= staking_rewards_config.last_rewards_rate_period_start_in_secs, + error::invalid_argument(EINVALID_LAST_REWARDS_RATE_PERIOD_START) + ); + if (current_time_in_secs - staking_rewards_config.last_rewards_rate_period_start_in_secs < staking_rewards_config.rewards_rate_period_in_secs) { + return *staking_rewards_config + }; + // Rewards rate decrease rate cannot be greater than 100%. Otherwise rewards rate will be negative. + assert!( + fixed_point64::ceil(staking_rewards_config.rewards_rate_decrease_rate) <= 1, + error::invalid_argument(EINVALID_REWARDS_RATE_DECREASE_RATE) + ); + let new_rate = math_fixed64::mul_div( + staking_rewards_config.rewards_rate, + fixed_point64::sub( + fixed_point64::create_from_u128(1), + staking_rewards_config.rewards_rate_decrease_rate, + ), + fixed_point64::create_from_u128(1), + ); + new_rate = fixed_point64::max(new_rate, staking_rewards_config.min_rewards_rate); + + staking_rewards_config.rewards_rate = new_rate; + staking_rewards_config.last_rewards_rate_period_start_in_secs = + staking_rewards_config.last_rewards_rate_period_start_in_secs + + staking_rewards_config.rewards_rate_period_in_secs; + return *staking_rewards_config + } + + /// Update the min and max stake amounts. + /// Can only be called as part of the Aptos governance proposal process established by the AptosGovernance module. + public fun update_required_stake( + aptos_framework: &signer, + minimum_stake: u64, + maximum_stake: u64, + ) acquires StakingConfig { + system_addresses::assert_aptos_framework(aptos_framework); + validate_required_stake(minimum_stake, maximum_stake); + + let staking_config = borrow_global_mut(@aptos_framework); + staking_config.minimum_stake = minimum_stake; + staking_config.maximum_stake = maximum_stake; + } + + /// Update the recurring lockup duration. + /// Can only be called as part of the Aptos governance proposal process established by the AptosGovernance module. + public fun update_recurring_lockup_duration_secs( + aptos_framework: &signer, + new_recurring_lockup_duration_secs: u64, + ) acquires StakingConfig { + assert!(new_recurring_lockup_duration_secs > 0, error::invalid_argument(EZERO_LOCKUP_DURATION)); + system_addresses::assert_aptos_framework(aptos_framework); + + let staking_config = borrow_global_mut(@aptos_framework); + staking_config.recurring_lockup_duration_secs = new_recurring_lockup_duration_secs; + } + + /// DEPRECATING + /// Update the rewards rate. + /// Can only be called as part of the Aptos governance proposal process established by the AptosGovernance module. + public fun update_rewards_rate( + aptos_framework: &signer, + new_rewards_rate: u64, + new_rewards_rate_denominator: u64, + ) acquires StakingConfig { + assert!(!features::periodical_reward_rate_decrease_enabled(), error::invalid_state(EDEPRECATED_FUNCTION)); + system_addresses::assert_aptos_framework(aptos_framework); + assert!( + new_rewards_rate_denominator > 0, + error::invalid_argument(EZERO_REWARDS_RATE_DENOMINATOR), + ); + // `rewards_rate` which is the numerator is limited to be `<= MAX_REWARDS_RATE` in order to avoid the arithmetic + // overflow in the rewards calculation. `rewards_rate_denominator` can be adjusted to get the desired rewards + // rate (i.e., rewards_rate / rewards_rate_denominator). + assert!(new_rewards_rate <= MAX_REWARDS_RATE, error::invalid_argument(EINVALID_REWARDS_RATE)); + + // We assert that (rewards_rate / rewards_rate_denominator <= 1). + assert!(new_rewards_rate <= new_rewards_rate_denominator, error::invalid_argument(EINVALID_REWARDS_RATE)); + + let staking_config = borrow_global_mut(@aptos_framework); + staking_config.rewards_rate = new_rewards_rate; + staking_config.rewards_rate_denominator = new_rewards_rate_denominator; + } + + public fun update_rewards_config( + aptos_framework: &signer, + rewards_rate: FixedPoint64, + min_rewards_rate: FixedPoint64, + rewards_rate_period_in_secs: u64, + rewards_rate_decrease_rate: FixedPoint64, + ) acquires StakingRewardsConfig { + system_addresses::assert_aptos_framework(aptos_framework); + + validate_rewards_config( + rewards_rate, + min_rewards_rate, + rewards_rate_period_in_secs, + rewards_rate_decrease_rate, + ); + + let staking_rewards_config = borrow_global_mut(@aptos_framework); + // Currently rewards_rate_period_in_secs is not allowed to be changed because this could bring complicated + // logics. At the moment the argument is just a placeholder for future use. + assert!( + rewards_rate_period_in_secs == staking_rewards_config.rewards_rate_period_in_secs, + error::invalid_argument(EINVALID_REWARDS_RATE_PERIOD), + ); + staking_rewards_config.rewards_rate = rewards_rate; + staking_rewards_config.min_rewards_rate = min_rewards_rate; + staking_rewards_config.rewards_rate_period_in_secs = rewards_rate_period_in_secs; + staking_rewards_config.rewards_rate_decrease_rate = rewards_rate_decrease_rate; + } + + /// Update the joining limit %. + /// Can only be called as part of the Aptos governance proposal process established by the AptosGovernance module. + public fun update_voting_power_increase_limit( + aptos_framework: &signer, + new_voting_power_increase_limit: u64, + ) acquires StakingConfig { + system_addresses::assert_aptos_framework(aptos_framework); + assert!( + new_voting_power_increase_limit > 0 && new_voting_power_increase_limit <= 50, + error::invalid_argument(EINVALID_VOTING_POWER_INCREASE_LIMIT), + ); + + let staking_config = borrow_global_mut(@aptos_framework); + staking_config.voting_power_increase_limit = new_voting_power_increase_limit; + } + + fun validate_required_stake(minimum_stake: u64, maximum_stake: u64) { + assert!(minimum_stake <= maximum_stake && maximum_stake > 0, error::invalid_argument(EINVALID_STAKE_RANGE)); + } + + fun validate_rewards_config( + rewards_rate: FixedPoint64, + min_rewards_rate: FixedPoint64, + rewards_rate_period_in_secs: u64, + rewards_rate_decrease_rate: FixedPoint64, + ) { + // Bound rewards rate to avoid arithmetic overflow. + assert!( + less_or_equal(rewards_rate, fixed_point64::create_from_u128((1u128))), + error::invalid_argument(EINVALID_REWARDS_RATE) + ); + assert!( + less_or_equal(min_rewards_rate, rewards_rate), + error::invalid_argument(EINVALID_MIN_REWARDS_RATE) + ); + // Rewards rate decrease rate cannot be greater than 100%. Otherwise rewards rate will be negative. + assert!( + fixed_point64::ceil(rewards_rate_decrease_rate) <= 1, + error::invalid_argument(EINVALID_REWARDS_RATE_DECREASE_RATE) + ); + // This field, rewards_rate_period_in_secs must be greater than 0. + // TODO: rewards_rate_period_in_secs should be longer than the epoch duration but reading epoch duration causes a circular dependency. + assert!( + rewards_rate_period_in_secs > 0, + error::invalid_argument(EINVALID_REWARDS_RATE_PERIOD), + ); + } + + #[test_only] + use aptos_std::fixed_point64::{equal, create_from_rational}; + + #[test(aptos_framework = @aptos_framework)] + public entry fun test_change_staking_configs(aptos_framework: signer) acquires StakingConfig { + initialize(&aptos_framework, 0, 1, 1, false, 1, 1, 1); + + update_required_stake(&aptos_framework, 100, 1000); + update_recurring_lockup_duration_secs(&aptos_framework, 10000); + update_rewards_rate(&aptos_framework, 10, 100); + update_voting_power_increase_limit(&aptos_framework, 10); + + let config = borrow_global(@aptos_framework); + assert!(config.minimum_stake == 100, 0); + assert!(config.maximum_stake == 1000, 1); + assert!(config.recurring_lockup_duration_secs == 10000, 3); + assert!(config.rewards_rate == 10, 4); + assert!(config.rewards_rate_denominator == 100, 4); + assert!(config.voting_power_increase_limit == 10, 5); + } + + #[test(aptos_framework = @aptos_framework)] + public entry fun test_staking_rewards_rate_decrease_over_time(aptos_framework: signer) acquires StakingRewardsConfig { + let start_time_in_secs: u64 = 100001000000; + initialize_rewards_for_test( + &aptos_framework, + create_from_rational(1, 100), + create_from_rational(3, 1000), + ONE_YEAR_IN_SECS, + start_time_in_secs, + create_from_rational(50, 100) + ); + + let epoch_reward_rate = calculate_and_save_latest_epoch_rewards_rate(); + assert!(equal(epoch_reward_rate, create_from_rational(1, 100)), 0); + // Rewards rate should not change until the current reward rate period ends. + timestamp::fast_forward_seconds(ONE_YEAR_IN_SECS / 2); + epoch_reward_rate = calculate_and_save_latest_epoch_rewards_rate(); + assert!(equal(epoch_reward_rate, create_from_rational(1, 100)), 1); + + // Rewards rate decreases to 1 / 100 * 5000 / 10000 = 5 / 1000. + timestamp::fast_forward_seconds(ONE_YEAR_IN_SECS / 2); + epoch_reward_rate = calculate_and_save_latest_epoch_rewards_rate(); + assert!(equal(epoch_reward_rate, create_from_rational(5, 1000)), 2); + + // Rewards rate decreases to 5 / 1000 * 5000 / 10000 = 2.5 / 1000. + // But rewards_rate cannot be lower than min_rewards_rate = 3 / 1000. + timestamp::fast_forward_seconds(ONE_YEAR_IN_SECS); + epoch_reward_rate = calculate_and_save_latest_epoch_rewards_rate(); + assert!(equal(epoch_reward_rate, create_from_rational(3, 1000)), 3); + + // Test when rewards_rate_decrease_rate is very small + update_rewards_config( + &aptos_framework, + epoch_reward_rate, + create_from_rational(0, 1000), + ONE_YEAR_IN_SECS, + create_from_rational(15, 1000), + ); + // Rewards rate decreases to 3 / 1000 * 985 / 1000 = 2955 / 1000000. + timestamp::fast_forward_seconds(ONE_YEAR_IN_SECS); + epoch_reward_rate = calculate_and_save_latest_epoch_rewards_rate(); + assert!( + fixed_point64::almost_equal( + epoch_reward_rate, + create_from_rational(2955, 1000000), + create_from_rational(1, 100000000) + ), + 4); + } + + #[test(aptos_framework = @aptos_framework)] + public entry fun test_change_staking_rewards_configs(aptos_framework: signer) acquires StakingRewardsConfig { + let start_time_in_secs: u64 = 100001000000; + initialize_rewards_for_test( + &aptos_framework, + create_from_rational(1, 100), + create_from_rational(3, 1000), + ONE_YEAR_IN_SECS, + start_time_in_secs, + create_from_rational(50, 100), + ); + + update_rewards_config( + &aptos_framework, + create_from_rational(2, 100), + create_from_rational(6, 1000), + ONE_YEAR_IN_SECS, + create_from_rational(25, 100), + ); + + let config = borrow_global(@aptos_framework); + assert!(equal(config.rewards_rate, create_from_rational(2, 100)), 0); + assert!(equal(config.min_rewards_rate, create_from_rational(6, 1000)), 1); + assert!(config.rewards_rate_period_in_secs == ONE_YEAR_IN_SECS, 4); + assert!(config.last_rewards_rate_period_start_in_secs == start_time_in_secs, 4); + assert!(equal(config.rewards_rate_decrease_rate, create_from_rational(25, 100)), 5); + } + + #[test(account = @0x123)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + public entry fun test_update_required_stake_unauthorized_should_fail(account: signer) acquires StakingConfig { + update_required_stake(&account, 1, 2); + } + + #[test(account = @0x123)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + public entry fun test_update_required_lockup_unauthorized_should_fail(account: signer) acquires StakingConfig { + update_recurring_lockup_duration_secs(&account, 1); + } + + #[test(account = @0x123)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + public entry fun test_update_rewards_unauthorized_should_fail(account: signer) acquires StakingConfig { + update_rewards_rate(&account, 1, 10); + } + + #[test(account = @0x123)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + public entry fun test_update_voting_power_increase_limit_unauthorized_should_fail(account: signer) acquires StakingConfig { + update_voting_power_increase_limit(&account, 10); + } + + #[test(account = @0x123, aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x50003, location = aptos_framework::system_addresses)] + public entry fun test_update_rewards_config_unauthorized_should_fail(account: signer, aptos_framework: signer) acquires StakingRewardsConfig { + features::change_feature_flags_for_testing(&aptos_framework, vector[features::get_periodical_reward_rate_decrease_feature()], vector[]); + update_rewards_config( + &account, + create_from_rational(1, 100), + create_from_rational(1, 100), + ONE_YEAR_IN_SECS, + create_from_rational(1, 100), + ); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10003, location = Self)] + public entry fun test_update_required_stake_invalid_range_should_fail(aptos_framework: signer) acquires StakingConfig { + update_required_stake(&aptos_framework, 10, 5); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10003, location = Self)] + public entry fun test_update_required_stake_zero_max_stake_should_fail(aptos_framework: signer) acquires StakingConfig { + update_required_stake(&aptos_framework, 0, 0); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10001, location = Self)] + public entry fun test_update_required_lockup_to_zero_should_fail(aptos_framework: signer) acquires StakingConfig { + update_recurring_lockup_duration_secs(&aptos_framework, 0); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10002, location = Self)] + public entry fun test_update_rewards_invalid_denominator_should_fail(aptos_framework: signer) acquires StakingConfig { + update_rewards_rate(&aptos_framework, 1, 0); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10005, location = Self)] + public entry fun test_update_rewards_config_rewards_rate_greater_than_1_should_fail(aptos_framework: signer) acquires StakingRewardsConfig { + let start_time_in_secs: u64 = 100001000000; + initialize_rewards_for_test( + &aptos_framework, + create_from_rational(15981, 1000000000), + create_from_rational(7991, 1000000000), + ONE_YEAR_IN_SECS, + start_time_in_secs, + create_from_rational(15, 1000), + ); + update_rewards_config( + &aptos_framework, + create_from_rational(101, 100), + create_from_rational(1, 100), + ONE_YEAR_IN_SECS, + create_from_rational(1, 100), + ); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10008, location = Self)] + public entry fun test_update_rewards_config_invalid_rewards_rate_decrease_rate_should_fail(aptos_framework: signer) acquires StakingRewardsConfig { + let start_time_in_secs: u64 = 100001000000; + initialize_rewards_for_test( + &aptos_framework, + create_from_rational(15981, 1000000000), + create_from_rational(7991, 1000000000), + ONE_YEAR_IN_SECS, + start_time_in_secs, + create_from_rational(15, 1000), + ); + update_rewards_config( + &aptos_framework, + create_from_rational(1, 100), + create_from_rational(1, 100), + ONE_YEAR_IN_SECS, + create_from_rational(101, 100), + ); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10009, location = Self)] + public entry fun test_update_rewards_config_cannot_change_rewards_rate_period(aptos_framework: signer) acquires StakingRewardsConfig { + let start_time_in_secs: u64 = 100001000000; + initialize_rewards_for_test( + &aptos_framework, + create_from_rational(15981, 1000000000), + create_from_rational(7991, 1000000000), + ONE_YEAR_IN_SECS, + start_time_in_secs, + create_from_rational(15, 1000), + ); + update_rewards_config( + &aptos_framework, + create_from_rational(15981, 1000000000), + create_from_rational(7991, 1000000000), + ONE_YEAR_IN_SECS - 1, + create_from_rational(15, 1000), + ); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x3000B, location = Self)] + public entry fun test_feature_flag_disabled_get_epoch_rewards_rate_should_fail(aptos_framework: signer) acquires StakingRewardsConfig { + features::change_feature_flags_for_testing(&aptos_framework, vector[], vector[features::get_periodical_reward_rate_decrease_feature()]); + calculate_and_save_latest_epoch_rewards_rate(); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10004, location = Self)] + public entry fun test_update_voting_power_increase_limit_to_zero_should_fail( + aptos_framework: signer + ) acquires StakingConfig { + update_voting_power_increase_limit(&aptos_framework, 0); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = 0x10004, location = aptos_framework::staking_config)] + public entry fun test_update_voting_power_increase_limit_to_more_than_upper_bound_should_fail( + aptos_framework: signer + ) acquires StakingConfig { + update_voting_power_increase_limit(&aptos_framework, 51); + } + + // For tests to bypass all validations. + #[test_only] + public fun initialize_for_test( + aptos_framework: &signer, + minimum_stake: u64, + maximum_stake: u64, + recurring_lockup_duration_secs: u64, + allow_validator_set_change: bool, + rewards_rate: u64, + rewards_rate_denominator: u64, + voting_power_increase_limit: u64, + ) { + if (!exists(@aptos_framework)) { + move_to(aptos_framework, StakingConfig { + minimum_stake, + maximum_stake, + recurring_lockup_duration_secs, + allow_validator_set_change, + rewards_rate, + rewards_rate_denominator, + voting_power_increase_limit, + }); + }; + } + + // For tests to bypass all validations. + #[test_only] + public fun initialize_rewards_for_test( + aptos_framework: &signer, + rewards_rate: FixedPoint64, + min_rewards_rate: FixedPoint64, + rewards_rate_period_in_micros: u64, + last_rewards_rate_period_start_in_secs: u64, + rewards_rate_decrease_rate: FixedPoint64, + ) { + features::change_feature_flags_for_testing(aptos_framework, vector[features::get_periodical_reward_rate_decrease_feature()], vector[]); + timestamp::set_time_has_started_for_testing(aptos_framework); + timestamp::update_global_time_for_test_secs(last_rewards_rate_period_start_in_secs); + initialize_rewards( + aptos_framework, + rewards_rate, + min_rewards_rate, + rewards_rate_period_in_micros, + last_rewards_rate_period_start_in_secs, + rewards_rate_decrease_rate, + ); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/staking_contract.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/staking_contract.move new file mode 100644 index 000000000..8de013987 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/staking_contract.move @@ -0,0 +1,1618 @@ +/// Allow stakers and operators to enter a staking contract with reward sharing. +/// The main accounting logic in a staking contract consists of 2 parts: +/// 1. Tracks how much commission needs to be paid out to the operator. This is tracked with an increasing principal +/// amount that's updated every time the operator requests commission, the staker withdraws funds, or the staker +/// switches operators. +/// 2. Distributions of funds to operators (commissions) and stakers (stake withdrawals) use the shares model provided +/// by the pool_u64 to track shares that increase in price as the stake pool accumulates rewards. +/// +/// Example flow: +/// 1. A staker creates a staking contract with an operator by calling create_staking_contract() with 100 coins of +/// initial stake and commission = 10%. This means the operator will receive 10% of any accumulated rewards. A new stake +/// pool will be created and hosted in a separate account that's controlled by the staking contract. +/// 2. The operator sets up a validator node and, once ready, joins the validator set by calling stake::join_validator_set +/// 3. After some time, the stake pool gains rewards and now has 150 coins. +/// 4. Operator can now call request_commission. 10% of (150 - 100) = 5 coins will be unlocked from the stake pool. The +/// staker's principal is now updated from 100 to 145 (150 coins - 5 coins of commission). The pending distribution pool +/// has 5 coins total and the operator owns all 5 shares of it. +/// 5. Some more time has passed. The pool now has 50 more coins in rewards and a total balance of 195. The operator +/// calls request_commission again. Since the previous 5 coins have now become withdrawable, it'll be deposited into the +/// operator's account first. Their new commission will be 10% of (195 coins - 145 principal) = 5 coins. Principal is +/// updated to be 190 (195 - 5). Pending distribution pool has 5 coins and operator owns all 5 shares. +/// 6. Staker calls unlock_stake to unlock 50 coins of stake, which gets added to the pending distribution pool. Based +/// on shares math, staker will be owning 50 shares and operator still owns 5 shares of the 55-coin pending distribution +/// pool. +/// 7. Some time passes and the 55 coins become fully withdrawable from the stake pool. Due to accumulated rewards, the +/// 55 coins become 70 coins. Calling distribute() distributes 6 coins to the operator and 64 coins to the validator. +module aptos_framework::staking_contract { + use std::bcs; + use std::error; + use std::features; + use std::signer; + use std::vector; + + use aptos_std::pool_u64::{Self, Pool}; + use aptos_std::simple_map::{Self, SimpleMap}; + + use aptos_framework::account::{Self, SignerCapability}; + use aptos_framework::aptos_account; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::coin::{Self, Coin}; + use aptos_framework::event::{EventHandle, emit, emit_event}; + use aptos_framework::stake::{Self, OwnerCapability}; + use aptos_framework::staking_config; + + const SALT: vector = b"aptos_framework::staking_contract"; + + /// Store amount must be at least the min stake required for a stake pool to join the validator set. + const EINSUFFICIENT_STAKE_AMOUNT: u64 = 1; + /// Commission percentage has to be between 0 and 100. + const EINVALID_COMMISSION_PERCENTAGE: u64 = 2; + /// Staker has no staking contracts. + const ENO_STAKING_CONTRACT_FOUND_FOR_STAKER: u64 = 3; + /// No staking contract between the staker and operator found. + const ENO_STAKING_CONTRACT_FOUND_FOR_OPERATOR: u64 = 4; + /// Staking contracts can't be merged. + const ECANT_MERGE_STAKING_CONTRACTS: u64 = 5; + /// The staking contract already exists and cannot be re-created. + const ESTAKING_CONTRACT_ALREADY_EXISTS: u64 = 6; + /// Not enough active stake to withdraw. Some stake might still pending and will be active in the next epoch. + const EINSUFFICIENT_ACTIVE_STAKE_TO_WITHDRAW: u64 = 7; + /// Caller must be either the staker, operator, or beneficiary. + const ENOT_STAKER_OR_OPERATOR_OR_BENEFICIARY: u64 = 8; + /// Chaning beneficiaries for operators is not supported. + const EOPERATOR_BENEFICIARY_CHANGE_NOT_SUPPORTED: u64 = 9; + + /// Maximum number of distributions a stake pool can support. + const MAXIMUM_PENDING_DISTRIBUTIONS: u64 = 20; + + #[resource_group(scope = module_)] + struct StakingGroupContainer {} + + struct StakingContract has store { + // Recorded principal after the last commission distribution. + // This is only used to calculate the commission the operator should be receiving. + principal: u64, + pool_address: address, + // The stake pool's owner capability. This can be used to control funds in the stake pool. + owner_cap: OwnerCapability, + commission_percentage: u64, + // Current distributions, including operator commission withdrawals and staker's partial withdrawals. + distribution_pool: Pool, + // Just in case we need the SignerCap for stake pool account in the future. + signer_cap: SignerCapability, + } + + struct Store has key { + staking_contracts: SimpleMap, + + // Events. + create_staking_contract_events: EventHandle, + update_voter_events: EventHandle, + reset_lockup_events: EventHandle, + add_stake_events: EventHandle, + request_commission_events: EventHandle, + unlock_stake_events: EventHandle, + switch_operator_events: EventHandle, + add_distribution_events: EventHandle, + distribute_events: EventHandle, + } + + struct BeneficiaryForOperator has key { + beneficiary_for_operator: address, + } + + struct UpdateCommissionEvent has drop, store { + staker: address, + operator: address, + old_commission_percentage: u64, + new_commission_percentage: u64, + } + + #[event] + struct UpdateCommission has drop, store { + staker: address, + operator: address, + old_commission_percentage: u64, + new_commission_percentage: u64, + } + + #[resource_group_member(group = aptos_framework::staking_contract::StakingGroupContainer)] + struct StakingGroupUpdateCommissionEvent has key { + update_commission_events: EventHandle, + } + + #[event] + struct CreateStakingContract has drop, store { + operator: address, + voter: address, + pool_address: address, + principal: u64, + commission_percentage: u64, + } + + #[event] + struct UpdateVoter has drop, store { + operator: address, + pool_address: address, + old_voter: address, + new_voter: address, + } + + #[event] + struct ResetLockup has drop, store { + operator: address, + pool_address: address, + } + + #[event] + struct AddStake has drop, store { + operator: address, + pool_address: address, + amount: u64 + } + + #[event] + struct RequestCommission has drop, store { + operator: address, + pool_address: address, + accumulated_rewards: u64, + commission_amount: u64, + } + + #[event] + struct UnlockStake has drop, store { + operator: address, + pool_address: address, + amount: u64, + commission_paid: u64, + } + + #[event] + struct SwitchOperator has drop, store { + old_operator: address, + new_operator: address, + pool_address: address, + } + + #[event] + struct AddDistribution has drop, store { + operator: address, + pool_address: address, + amount: u64, + } + + #[event] + struct Distribute has drop, store { + operator: address, + pool_address: address, + recipient: address, + amount: u64, + } + + #[event] + struct SetBeneficiaryForOperator has drop, store { + operator: address, + old_beneficiary: address, + new_beneficiary: address, + } + + struct CreateStakingContractEvent has drop, store { + operator: address, + voter: address, + pool_address: address, + principal: u64, + commission_percentage: u64, + } + + struct UpdateVoterEvent has drop, store { + operator: address, + pool_address: address, + old_voter: address, + new_voter: address, + } + + struct ResetLockupEvent has drop, store { + operator: address, + pool_address: address, + } + + struct AddStakeEvent has drop, store { + operator: address, + pool_address: address, + amount: u64 + } + + struct RequestCommissionEvent has drop, store { + operator: address, + pool_address: address, + accumulated_rewards: u64, + commission_amount: u64, + } + + struct UnlockStakeEvent has drop, store { + operator: address, + pool_address: address, + amount: u64, + commission_paid: u64, + } + + struct SwitchOperatorEvent has drop, store { + old_operator: address, + new_operator: address, + pool_address: address, + } + + struct AddDistributionEvent has drop, store { + operator: address, + pool_address: address, + amount: u64, + } + + struct DistributeEvent has drop, store { + operator: address, + pool_address: address, + recipient: address, + amount: u64, + } + + #[view] + /// Return the address of the underlying stake pool for the staking contract between the provided staker and + /// operator. + /// + /// This errors out the staking contract with the provided staker and operator doesn't exist. + public fun stake_pool_address(staker: address, operator: address): address acquires Store { + assert_staking_contract_exists(staker, operator); + let staking_contracts = &borrow_global(staker).staking_contracts; + simple_map::borrow(staking_contracts, &operator).pool_address + } + + #[view] + /// Return the last recorded principal (the amount that 100% belongs to the staker with commission already paid for) + /// for staking contract between the provided staker and operator. + /// + /// This errors out the staking contract with the provided staker and operator doesn't exist. + public fun last_recorded_principal(staker: address, operator: address): u64 acquires Store { + assert_staking_contract_exists(staker, operator); + let staking_contracts = &borrow_global(staker).staking_contracts; + simple_map::borrow(staking_contracts, &operator).principal + } + + #[view] + /// Return percentage of accumulated rewards that will be paid to the operator as commission for staking contract + /// between the provided staker and operator. + /// + /// This errors out the staking contract with the provided staker and operator doesn't exist. + public fun commission_percentage(staker: address, operator: address): u64 acquires Store { + assert_staking_contract_exists(staker, operator); + let staking_contracts = &borrow_global(staker).staking_contracts; + simple_map::borrow(staking_contracts, &operator).commission_percentage + } + + #[view] + /// Return a tuple of three numbers: + /// 1. The total active stake in the underlying stake pool + /// 2. The total accumulated rewards that haven't had commission paid out + /// 3. The commission amount owned from those accumulated rewards. + /// + /// This errors out the staking contract with the provided staker and operator doesn't exist. + public fun staking_contract_amounts(staker: address, operator: address): (u64, u64, u64) acquires Store { + assert_staking_contract_exists(staker, operator); + let staking_contracts = &borrow_global(staker).staking_contracts; + let staking_contract = simple_map::borrow(staking_contracts, &operator); + get_staking_contract_amounts_internal(staking_contract) + } + + #[view] + /// Return the number of pending distributions (e.g. commission, withdrawals from stakers). + /// + /// This errors out the staking contract with the provided staker and operator doesn't exist. + public fun pending_distribution_counts(staker: address, operator: address): u64 acquires Store { + assert_staking_contract_exists(staker, operator); + let staking_contracts = &borrow_global(staker).staking_contracts; + pool_u64::shareholders_count(&simple_map::borrow(staking_contracts, &operator).distribution_pool) + } + + #[view] + /// Return true if the staking contract between the provided staker and operator exists. + public fun staking_contract_exists(staker: address, operator: address): bool acquires Store { + if (!exists(staker)) { + return false + }; + + let store = borrow_global(staker); + simple_map::contains_key(&store.staking_contracts, &operator) + } + + #[view] + /// Return the beneficiary address of the operator. + public fun beneficiary_for_operator(operator: address): address acquires BeneficiaryForOperator { + if (exists(operator)) { + return borrow_global(operator).beneficiary_for_operator + } else { + operator + } + } + + #[view] + /// Return the address of the stake pool to be created with the provided staker, operator and seed. + public fun get_expected_stake_pool_address( + staker: address, + operator: address, + contract_creation_seed: vector, + ): address { + let seed = create_resource_account_seed(staker, operator, contract_creation_seed); + account::create_resource_address(&staker, seed) + } + + /// Staker can call this function to create a simple staking contract with a specified operator. + public entry fun create_staking_contract( + staker: &signer, + operator: address, + voter: address, + amount: u64, + commission_percentage: u64, + // Optional seed used when creating the staking contract account. + contract_creation_seed: vector, + ) acquires Store { + let staked_coins = coin::withdraw(staker, amount); + create_staking_contract_with_coins( + staker, operator, voter, staked_coins, commission_percentage, contract_creation_seed); + } + + /// Staker can call this function to create a simple staking contract with a specified operator. + public fun create_staking_contract_with_coins( + staker: &signer, + operator: address, + voter: address, + coins: Coin, + commission_percentage: u64, + // Optional seed used when creating the staking contract account. + contract_creation_seed: vector, + ): address acquires Store { + assert!( + commission_percentage >= 0 && commission_percentage <= 100, + error::invalid_argument(EINVALID_COMMISSION_PERCENTAGE), + ); + // The amount should be at least the min_stake_required, so the stake pool will be eligible to join the + // validator set. + let (min_stake_required, _) = staking_config::get_required_stake(&staking_config::get()); + let principal = coin::value(&coins); + assert!(principal >= min_stake_required, error::invalid_argument(EINSUFFICIENT_STAKE_AMOUNT)); + + // Initialize Store resource if this is the first time the staker has delegated to anyone. + let staker_address = signer::address_of(staker); + if (!exists(staker_address)) { + move_to(staker, new_staking_contracts_holder(staker)); + }; + + // Cannot create the staking contract if it already exists. + let store = borrow_global_mut(staker_address); + let staking_contracts = &mut store.staking_contracts; + assert!( + !simple_map::contains_key(staking_contracts, &operator), + error::already_exists(ESTAKING_CONTRACT_ALREADY_EXISTS) + ); + + // Initialize the stake pool in a new resource account. This allows the same staker to contract with multiple + // different operators. + let (stake_pool_signer, stake_pool_signer_cap, owner_cap) = + create_stake_pool(staker, operator, voter, contract_creation_seed); + + // Add the stake to the stake pool. + stake::add_stake_with_cap(&owner_cap, coins); + + // Create the contract record. + let pool_address = signer::address_of(&stake_pool_signer); + simple_map::add(staking_contracts, operator, StakingContract { + principal, + pool_address, + owner_cap, + commission_percentage, + // Make sure we don't have too many pending recipients in the distribution pool. + // Otherwise, a griefing attack is possible where the staker can keep switching operators and create too + // many pending distributions. This can lead to out-of-gas failure whenever distribute() is called. + distribution_pool: pool_u64::create(MAXIMUM_PENDING_DISTRIBUTIONS), + signer_cap: stake_pool_signer_cap, + }); + + if (std::features::module_event_migration_enabled()) { + emit(CreateStakingContract { operator, voter, pool_address, principal, commission_percentage }); + }; + emit_event( + &mut store.create_staking_contract_events, + CreateStakingContractEvent { operator, voter, pool_address, principal, commission_percentage }, + ); + pool_address + } + + /// Add more stake to an existing staking contract. + public entry fun add_stake(staker: &signer, operator: address, amount: u64) acquires Store { + let staker_address = signer::address_of(staker); + assert_staking_contract_exists(staker_address, operator); + + let store = borrow_global_mut(staker_address); + let staking_contract = simple_map::borrow_mut(&mut store.staking_contracts, &operator); + + // Add the stake to the stake pool. + let staked_coins = coin::withdraw(staker, amount); + stake::add_stake_with_cap(&staking_contract.owner_cap, staked_coins); + + staking_contract.principal = staking_contract.principal + amount; + let pool_address = staking_contract.pool_address; + if (std::features::module_event_migration_enabled()) { + emit(AddStake { operator, pool_address, amount }); + }; + emit_event( + &mut store.add_stake_events, + AddStakeEvent { operator, pool_address, amount }, + ); + } + + /// Convenient function to allow the staker to update the voter address in a staking contract they made. + public entry fun update_voter(staker: &signer, operator: address, new_voter: address) acquires Store { + let staker_address = signer::address_of(staker); + assert_staking_contract_exists(staker_address, operator); + + let store = borrow_global_mut(staker_address); + let staking_contract = simple_map::borrow_mut(&mut store.staking_contracts, &operator); + let pool_address = staking_contract.pool_address; + let old_voter = stake::get_delegated_voter(pool_address); + stake::set_delegated_voter_with_cap(&staking_contract.owner_cap, new_voter); + + if (std::features::module_event_migration_enabled()) { + emit(UpdateVoter { operator, pool_address, old_voter, new_voter }); + }; + emit_event( + &mut store.update_voter_events, + UpdateVoterEvent { operator, pool_address, old_voter, new_voter }, + ); + + } + + /// Convenient function to allow the staker to reset their stake pool's lockup period to start now. + public entry fun reset_lockup(staker: &signer, operator: address) acquires Store { + let staker_address = signer::address_of(staker); + assert_staking_contract_exists(staker_address, operator); + + let store = borrow_global_mut(staker_address); + let staking_contract = simple_map::borrow_mut(&mut store.staking_contracts, &operator); + let pool_address = staking_contract.pool_address; + stake::increase_lockup_with_cap(&staking_contract.owner_cap); + + if (std::features::module_event_migration_enabled()) { + emit(ResetLockup { operator, pool_address }); + }; + emit_event(&mut store.reset_lockup_events, ResetLockupEvent { operator, pool_address }); + } + + /// Convenience function to allow a staker to update the commission percentage paid to the operator. + /// TODO: fix the typo in function name. commision -> commission + public entry fun update_commision( + staker: &signer, + operator: address, + new_commission_percentage: u64 + ) acquires Store, BeneficiaryForOperator, StakingGroupUpdateCommissionEvent { + assert!( + new_commission_percentage >= 0 && new_commission_percentage <= 100, + error::invalid_argument(EINVALID_COMMISSION_PERCENTAGE), + ); + + let staker_address = signer::address_of(staker); + assert!(exists(staker_address), error::not_found(ENO_STAKING_CONTRACT_FOUND_FOR_STAKER)); + + let store = borrow_global_mut(staker_address); + let staking_contract = simple_map::borrow_mut(&mut store.staking_contracts, &operator); + distribute_internal(staker_address, operator, staking_contract, &mut store.distribute_events); + request_commission_internal( + operator, + staking_contract, + &mut store.add_distribution_events, + &mut store.request_commission_events, + ); + let old_commission_percentage = staking_contract.commission_percentage; + staking_contract.commission_percentage = new_commission_percentage; + if (!exists(staker_address)) { + move_to( + staker, + StakingGroupUpdateCommissionEvent { + update_commission_events: account::new_event_handle( + staker + ) + } + ) + }; + if (std::features::module_event_migration_enabled()) { + emit( + UpdateCommission { staker: staker_address, operator, old_commission_percentage, new_commission_percentage } + ); + }; + emit_event( + &mut borrow_global_mut(staker_address).update_commission_events, + UpdateCommissionEvent { staker: staker_address, operator, old_commission_percentage, new_commission_percentage } + ); + } + + /// Unlock commission amount from the stake pool. Operator needs to wait for the amount to become withdrawable + /// at the end of the stake pool's lockup period before they can actually can withdraw_commission. + /// + /// Only staker, operator or beneficiary can call this. + public entry fun request_commission( + account: &signer, + staker: address, + operator: address + ) acquires Store, BeneficiaryForOperator { + let account_addr = signer::address_of(account); + assert!( + account_addr == staker || account_addr == operator || account_addr == beneficiary_for_operator(operator), + error::unauthenticated(ENOT_STAKER_OR_OPERATOR_OR_BENEFICIARY) + ); + assert_staking_contract_exists(staker, operator); + + let store = borrow_global_mut(staker); + let staking_contract = simple_map::borrow_mut(&mut store.staking_contracts, &operator); + // Short-circuit if zero commission. + if (staking_contract.commission_percentage == 0) { + return + }; + + // Force distribution of any already inactive stake. + distribute_internal(staker, operator, staking_contract, &mut store.distribute_events); + + request_commission_internal( + operator, + staking_contract, + &mut store.add_distribution_events, + &mut store.request_commission_events, + ); + } + + fun request_commission_internal( + operator: address, + staking_contract: &mut StakingContract, + add_distribution_events: &mut EventHandle, + request_commission_events: &mut EventHandle, + ): u64 { + // Unlock just the commission portion from the stake pool. + let (total_active_stake, accumulated_rewards, commission_amount) = + get_staking_contract_amounts_internal(staking_contract); + staking_contract.principal = total_active_stake - commission_amount; + + // Short-circuit if there's no commission to pay. + if (commission_amount == 0) { + return 0 + }; + + // Add a distribution for the operator. + add_distribution(operator, staking_contract, operator, commission_amount, add_distribution_events); + + // Request to unlock the commission from the stake pool. + // This won't become fully unlocked until the stake pool's lockup expires. + stake::unlock_with_cap(commission_amount, &staking_contract.owner_cap); + + let pool_address = staking_contract.pool_address; + if (std::features::module_event_migration_enabled()) { + emit(RequestCommission { operator, pool_address, accumulated_rewards, commission_amount }); + }; + emit_event( + request_commission_events, + RequestCommissionEvent { operator, pool_address, accumulated_rewards, commission_amount }, + ); + + commission_amount + } + + /// Staker can call this to request withdrawal of part or all of their staking_contract. + /// This also triggers paying commission to the operator for accounting simplicity. + public entry fun unlock_stake( + staker: &signer, + operator: address, + amount: u64 + ) acquires Store, BeneficiaryForOperator { + // Short-circuit if amount is 0. + if (amount == 0) return; + + let staker_address = signer::address_of(staker); + assert_staking_contract_exists(staker_address, operator); + + let store = borrow_global_mut(staker_address); + let staking_contract = simple_map::borrow_mut(&mut store.staking_contracts, &operator); + + // Force distribution of any already inactive stake. + distribute_internal(staker_address, operator, staking_contract, &mut store.distribute_events); + + // For simplicity, we request commission to be paid out first. This avoids having to ensure to staker doesn't + // withdraw into the commission portion. + let commission_paid = request_commission_internal( + operator, + staking_contract, + &mut store.add_distribution_events, + &mut store.request_commission_events, + ); + + // If there's less active stake remaining than the amount requested (potentially due to commission), + // only withdraw up to the active amount. + let (active, _, _, _) = stake::get_stake(staking_contract.pool_address); + if (active < amount) { + amount = active; + }; + staking_contract.principal = staking_contract.principal - amount; + + // Record a distribution for the staker. + add_distribution(operator, staking_contract, staker_address, amount, &mut store.add_distribution_events); + + // Request to unlock the distribution amount from the stake pool. + // This won't become fully unlocked until the stake pool's lockup expires. + stake::unlock_with_cap(amount, &staking_contract.owner_cap); + + let pool_address = staking_contract.pool_address; + if (std::features::module_event_migration_enabled()) { + emit(UnlockStake { pool_address, operator, amount, commission_paid }); + }; + emit_event( + &mut store.unlock_stake_events, + UnlockStakeEvent { pool_address, operator, amount, commission_paid }, + ); + } + + /// Unlock all accumulated rewards since the last recorded principals. + public entry fun unlock_rewards(staker: &signer, operator: address) acquires Store, BeneficiaryForOperator { + let staker_address = signer::address_of(staker); + assert_staking_contract_exists(staker_address, operator); + + // Calculate how much rewards belongs to the staker after commission is paid. + let (_, accumulated_rewards, unpaid_commission) = staking_contract_amounts(staker_address, operator); + let staker_rewards = accumulated_rewards - unpaid_commission; + unlock_stake(staker, operator, staker_rewards); + } + + /// Allows staker to switch operator without going through the lenghthy process to unstake, without resetting commission. + public entry fun switch_operator_with_same_commission( + staker: &signer, + old_operator: address, + new_operator: address, + ) acquires Store, BeneficiaryForOperator { + let staker_address = signer::address_of(staker); + assert_staking_contract_exists(staker_address, old_operator); + + let commission_percentage = commission_percentage(staker_address, old_operator); + switch_operator(staker, old_operator, new_operator, commission_percentage); + } + + /// Allows staker to switch operator without going through the lenghthy process to unstake. + public entry fun switch_operator( + staker: &signer, + old_operator: address, + new_operator: address, + new_commission_percentage: u64, + ) acquires Store, BeneficiaryForOperator { + let staker_address = signer::address_of(staker); + assert_staking_contract_exists(staker_address, old_operator); + + // Merging two existing staking contracts is too complex as we'd need to merge two separate stake pools. + let store = borrow_global_mut(staker_address); + let staking_contracts = &mut store.staking_contracts; + assert!( + !simple_map::contains_key(staking_contracts, &new_operator), + error::invalid_state(ECANT_MERGE_STAKING_CONTRACTS), + ); + + let (_, staking_contract) = simple_map::remove(staking_contracts, &old_operator); + // Force distribution of any already inactive stake. + distribute_internal(staker_address, old_operator, &mut staking_contract, &mut store.distribute_events); + + // For simplicity, we request commission to be paid out first. This avoids having to ensure to staker doesn't + // withdraw into the commission portion. + request_commission_internal( + old_operator, + &mut staking_contract, + &mut store.add_distribution_events, + &mut store.request_commission_events, + ); + + // Update the staking contract's commission rate and stake pool's operator. + stake::set_operator_with_cap(&staking_contract.owner_cap, new_operator); + staking_contract.commission_percentage = new_commission_percentage; + + let pool_address = staking_contract.pool_address; + simple_map::add(staking_contracts, new_operator, staking_contract); + if (std::features::module_event_migration_enabled()) { + emit(SwitchOperator { pool_address, old_operator, new_operator }); + }; + emit_event( + &mut store.switch_operator_events, + SwitchOperatorEvent { pool_address, old_operator, new_operator } + ); + } + + /// Allows an operator to change its beneficiary. Any existing unpaid commission rewards will be paid to the new + /// beneficiary. To ensures payment to the current beneficiary, one should first call `distribute` before switching + /// the beneficiary. An operator can set one beneficiary for staking contract pools, not a separate one for each pool. + public entry fun set_beneficiary_for_operator( + operator: &signer, + new_beneficiary: address + ) acquires BeneficiaryForOperator { + assert!(features::operator_beneficiary_change_enabled(), std::error::invalid_state( + EOPERATOR_BENEFICIARY_CHANGE_NOT_SUPPORTED + )); + // The beneficiay address of an operator is stored under the operator's address. + // So, the operator does not need to be validated with respect to a staking pool. + let operator_addr = signer::address_of(operator); + let old_beneficiary = beneficiary_for_operator(operator_addr); + if (exists(operator_addr)) { + borrow_global_mut(operator_addr).beneficiary_for_operator = new_beneficiary; + } else { + move_to(operator, BeneficiaryForOperator { beneficiary_for_operator: new_beneficiary }); + }; + + emit(SetBeneficiaryForOperator { + operator: operator_addr, + old_beneficiary, + new_beneficiary, + }); + } + + /// Allow anyone to distribute already unlocked funds. This does not affect reward compounding and therefore does + /// not need to be restricted to just the staker or operator. + public entry fun distribute(staker: address, operator: address) acquires Store, BeneficiaryForOperator { + assert_staking_contract_exists(staker, operator); + let store = borrow_global_mut(staker); + let staking_contract = simple_map::borrow_mut(&mut store.staking_contracts, &operator); + distribute_internal(staker, operator, staking_contract, &mut store.distribute_events); + } + + /// Distribute all unlocked (inactive) funds according to distribution shares. + fun distribute_internal( + staker: address, + operator: address, + staking_contract: &mut StakingContract, + distribute_events: &mut EventHandle, + ) acquires BeneficiaryForOperator { + let pool_address = staking_contract.pool_address; + let (_, inactive, _, pending_inactive) = stake::get_stake(pool_address); + let total_potential_withdrawable = inactive + pending_inactive; + let coins = stake::withdraw_with_cap(&staking_contract.owner_cap, total_potential_withdrawable); + let distribution_amount = coin::value(&coins); + if (distribution_amount == 0) { + coin::destroy_zero(coins); + return + }; + + let distribution_pool = &mut staking_contract.distribution_pool; + update_distribution_pool( + distribution_pool, distribution_amount, operator, staking_contract.commission_percentage); + + // Buy all recipients out of the distribution pool. + while (pool_u64::shareholders_count(distribution_pool) > 0) { + let recipients = pool_u64::shareholders(distribution_pool); + let recipient = *vector::borrow(&mut recipients, 0); + let current_shares = pool_u64::shares(distribution_pool, recipient); + let amount_to_distribute = pool_u64::redeem_shares(distribution_pool, recipient, current_shares); + // If the recipient is the operator, send the commission to the beneficiary instead. + if (recipient == operator) { + recipient = beneficiary_for_operator(operator); + }; + aptos_account::deposit_coins(recipient, coin::extract(&mut coins, amount_to_distribute)); + + if (std::features::module_event_migration_enabled()) { + emit(Distribute { operator, pool_address, recipient, amount: amount_to_distribute }); + }; + emit_event( + distribute_events, + DistributeEvent { operator, pool_address, recipient, amount: amount_to_distribute } + ); + }; + + // In case there's any dust left, send them all to the staker. + if (coin::value(&coins) > 0) { + aptos_account::deposit_coins(staker, coins); + pool_u64::update_total_coins(distribution_pool, 0); + } else { + coin::destroy_zero(coins); + } + } + + /// Assert that a staking_contract exists for the staker/operator pair. + fun assert_staking_contract_exists(staker: address, operator: address) acquires Store { + assert!(exists(staker), error::not_found(ENO_STAKING_CONTRACT_FOUND_FOR_STAKER)); + let staking_contracts = &mut borrow_global_mut(staker).staking_contracts; + assert!( + simple_map::contains_key(staking_contracts, &operator), + error::not_found(ENO_STAKING_CONTRACT_FOUND_FOR_OPERATOR), + ); + } + + /// Add a new distribution for `recipient` and `amount` to the staking contract's distributions list. + fun add_distribution( + operator: address, + staking_contract: &mut StakingContract, + recipient: address, + coins_amount: u64, + add_distribution_events: &mut EventHandle + ) { + let distribution_pool = &mut staking_contract.distribution_pool; + let (_, _, _, total_distribution_amount) = stake::get_stake(staking_contract.pool_address); + update_distribution_pool( + distribution_pool, total_distribution_amount, operator, staking_contract.commission_percentage); + + pool_u64::buy_in(distribution_pool, recipient, coins_amount); + let pool_address = staking_contract.pool_address; + if (std::features::module_event_migration_enabled()) { + emit(AddDistribution { operator, pool_address, amount: coins_amount }); + }; + emit_event( + add_distribution_events, + AddDistributionEvent { operator, pool_address, amount: coins_amount } + ); + } + + /// Calculate accumulated rewards and commissions since last update. + fun get_staking_contract_amounts_internal(staking_contract: &StakingContract): (u64, u64, u64) { + // Pending_inactive is not included in the calculation because pending_inactive can only come from: + // 1. Outgoing commissions. This means commission has already been extracted. + // 2. Stake withdrawals from stakers. This also means commission has already been extracted as + // request_commission_internal is called in unlock_stake + let (active, _, pending_active, _) = stake::get_stake(staking_contract.pool_address); + let total_active_stake = active + pending_active; + let accumulated_rewards = total_active_stake - staking_contract.principal; + let commission_amount = accumulated_rewards * staking_contract.commission_percentage / 100; + + (total_active_stake, accumulated_rewards, commission_amount) + } + + fun create_stake_pool( + staker: &signer, + operator: address, + voter: address, + contract_creation_seed: vector, + ): (signer, SignerCapability, OwnerCapability) { + // Generate a seed that will be used to create the resource account that hosts the staking contract. + let seed = create_resource_account_seed( + signer::address_of(staker), operator, contract_creation_seed); + + let (stake_pool_signer, stake_pool_signer_cap) = account::create_resource_account(staker, seed); + stake::initialize_stake_owner(&stake_pool_signer, 0, operator, voter); + + // Extract owner_cap from the StakePool, so we have control over it in the staking_contracts flow. + // This is stored as part of the staking_contract. Thus, the staker would not have direct control over it without + // going through well-defined functions in this module. + let owner_cap = stake::extract_owner_cap(&stake_pool_signer); + + (stake_pool_signer, stake_pool_signer_cap, owner_cap) + } + + fun update_distribution_pool( + distribution_pool: &mut Pool, + updated_total_coins: u64, + operator: address, + commission_percentage: u64, + ) { + // Short-circuit and do nothing if the pool's total value has not changed. + if (pool_u64::total_coins(distribution_pool) == updated_total_coins) { + return + }; + + // Charge all stakeholders (except for the operator themselves) commission on any rewards earnt relatively to the + // previous value of the distribution pool. + let shareholders = &pool_u64::shareholders(distribution_pool); + vector::for_each_ref(shareholders, |shareholder| { + let shareholder: address = *shareholder; + if (shareholder != operator) { + let shares = pool_u64::shares(distribution_pool, shareholder); + let previous_worth = pool_u64::balance(distribution_pool, shareholder); + let current_worth = pool_u64::shares_to_amount_with_total_coins( + distribution_pool, shares, updated_total_coins); + let unpaid_commission = (current_worth - previous_worth) * commission_percentage / 100; + // Transfer shares from current shareholder to the operator as payment. + // The value of the shares should use the updated pool's total value. + let shares_to_transfer = pool_u64::amount_to_shares_with_total_coins( + distribution_pool, unpaid_commission, updated_total_coins); + pool_u64::transfer_shares(distribution_pool, shareholder, operator, shares_to_transfer); + }; + }); + + pool_u64::update_total_coins(distribution_pool, updated_total_coins); + } + + /// Create the seed to derive the resource account address. + fun create_resource_account_seed( + staker: address, + operator: address, + contract_creation_seed: vector, + ): vector { + let seed = bcs::to_bytes(&staker); + vector::append(&mut seed, bcs::to_bytes(&operator)); + // Include a salt to avoid conflicts with any other modules out there that might also generate + // deterministic resource accounts for the same staker + operator addresses. + vector::append(&mut seed, SALT); + // Add an extra salt given by the staker in case an account with the same address has already been created. + vector::append(&mut seed, contract_creation_seed); + seed + } + + /// Create a new staking_contracts resource. + fun new_staking_contracts_holder(staker: &signer): Store { + Store { + staking_contracts: simple_map::create(), + // Events. + create_staking_contract_events: account::new_event_handle(staker), + update_voter_events: account::new_event_handle(staker), + reset_lockup_events: account::new_event_handle(staker), + add_stake_events: account::new_event_handle(staker), + request_commission_events: account::new_event_handle(staker), + unlock_stake_events: account::new_event_handle(staker), + switch_operator_events: account::new_event_handle(staker), + add_distribution_events: account::new_event_handle(staker), + distribute_events: account::new_event_handle(staker), + } + } + + #[test_only] + const VALIDATOR_STATUS_ACTIVE: u64 = 2; + #[test_only] + const VALIDATOR_STATUS_INACTIVE: u64 = 4; + + #[test_only] + use aptos_framework::stake::with_rewards; + + #[test_only] + const INITIAL_BALANCE: u64 = 100000000000000; // 1M APT coins with 8 decimals. + + #[test_only] + const MAXIMUM_STAKE: u64 = 100000000000000000; // 1B APT coins with 8 decimals. + + #[test_only] + const MODULE_EVENT: u64 = 26; + + #[test_only] + const OPERATOR_BENEFICIARY_CHANGE: u64 = 39; + + #[test_only] + public fun setup(aptos_framework: &signer, staker: &signer, operator: &signer, initial_balance: u64) { + // Reward rate of 0.1% per epoch. + stake::initialize_for_test_custom( + aptos_framework, + INITIAL_BALANCE, + MAXIMUM_STAKE, + 3600, + true, + 10, + 10000, + 1000000 + ); + + let staker_address = signer::address_of(staker); + if (!account::exists_at(staker_address)) { + account::create_account_for_test(staker_address); + }; + let operator_address = signer::address_of(operator); + if (!account::exists_at(operator_address)) { + account::create_account_for_test(operator_address); + }; + stake::mint(staker, initial_balance); + stake::mint(operator, initial_balance); + } + + #[test_only] + public fun setup_staking_contract( + aptos_framework: &signer, + staker: &signer, + operator: &signer, + amount: u64, + commission: u64, + ) acquires Store { + setup(aptos_framework, staker, operator, amount); + let operator_address = signer::address_of(operator); + + // Voter is initially set to operator but then updated to be staker. + create_staking_contract(staker, operator_address, operator_address, amount, commission, vector::empty()); + std::features::change_feature_flags_for_testing(aptos_framework, vector[MODULE_EVENT, OPERATOR_BENEFICIARY_CHANGE], vector[]); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_end_to_end( + aptos_framework: &signer, + staker: &signer, + operator: &signer + ) acquires Store, BeneficiaryForOperator { + setup_staking_contract(aptos_framework, staker, operator, INITIAL_BALANCE, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + assert_staking_contract_exists(staker_address, operator_address); + assert_staking_contract(staker_address, operator_address, INITIAL_BALANCE, 10); + + // Verify that the stake pool has been set up properly. + let pool_address = stake_pool_address(staker_address, operator_address); + stake::assert_stake_pool(pool_address, INITIAL_BALANCE, 0, 0, 0); + assert!(last_recorded_principal(staker_address, operator_address) == INITIAL_BALANCE, 0); + + // Operator joins the validator set. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, pool_address, true); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 1); + + // Fast forward to generate rewards. + stake::end_epoch(); + let new_balance = with_rewards(INITIAL_BALANCE); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, 0); + + // Operator claims 10% of rewards so far as commissions. + let expected_commission_1 = (new_balance - last_recorded_principal(staker_address, operator_address)) / 10; + new_balance = new_balance - expected_commission_1; + request_commission(operator, staker_address, operator_address); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, expected_commission_1); + assert!(last_recorded_principal(staker_address, operator_address) == new_balance, 0); + assert_distribution(staker_address, operator_address, operator_address, expected_commission_1); + stake::fast_forward_to_unlock(pool_address); + + // Both original stake and operator commissions have received rewards. + expected_commission_1 = with_rewards(expected_commission_1); + new_balance = with_rewards(new_balance); + stake::assert_stake_pool(pool_address, new_balance, expected_commission_1, 0, 0); + distribute(staker_address, operator_address); + let operator_balance = coin::balance(operator_address); + let expected_operator_balance = INITIAL_BALANCE + expected_commission_1; + assert!(operator_balance == expected_operator_balance, operator_balance); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, 0); + assert_no_pending_distributions(staker_address, operator_address); + + // Staker adds more stake. + stake::mint(staker, INITIAL_BALANCE); + let previous_principal = last_recorded_principal(staker_address, operator_address); + add_stake(staker, operator_address, INITIAL_BALANCE); + stake::assert_stake_pool(pool_address, new_balance, 0, INITIAL_BALANCE, 0); + assert!(last_recorded_principal(staker_address, operator_address) == previous_principal + INITIAL_BALANCE, 0); + + // The newly added stake didn't receive any rewards because it was only added in the new epoch. + stake::end_epoch(); + new_balance = with_rewards(new_balance) + INITIAL_BALANCE; + + // Second round of commission request/withdrawal. + let expected_commission_2 = (new_balance - last_recorded_principal(staker_address, operator_address)) / 10; + new_balance = new_balance - expected_commission_2; + request_commission(operator, staker_address, operator_address); + assert_distribution(staker_address, operator_address, operator_address, expected_commission_2); + assert!(last_recorded_principal(staker_address, operator_address) == new_balance, 0); + stake::fast_forward_to_unlock(pool_address); + expected_commission_2 = with_rewards(expected_commission_2); + distribute(staker_address, operator_address); + operator_balance = coin::balance(operator_address); + expected_operator_balance = expected_operator_balance + expected_commission_2; + assert!(operator_balance == expected_operator_balance, operator_balance); + assert_no_pending_distributions(staker_address, operator_address); + new_balance = with_rewards(new_balance); + + // New rounds of rewards. + stake::fast_forward_to_unlock(pool_address); + new_balance = with_rewards(new_balance); + + // Staker withdraws all stake, which should also request commission distribution. + let unpaid_commission = (new_balance - last_recorded_principal(staker_address, operator_address)) / 10; + unlock_stake(staker, operator_address, new_balance); + stake::assert_stake_pool(pool_address, 0, 0, 0, new_balance); + assert_distribution(staker_address, operator_address, operator_address, unpaid_commission); + let withdrawn_amount = new_balance - unpaid_commission; + assert_distribution(staker_address, operator_address, staker_address, withdrawn_amount); + assert!(last_recorded_principal(staker_address, operator_address) == 0, 0); + + // End epoch. The stake pool should get kicked out of the validator set as it has 0 remaining active stake. + stake::fast_forward_to_unlock(pool_address); + // Operator should still earn 10% commission on the rewards on top of the staker's withdrawn_amount. + let commission_on_withdrawn_amount = (with_rewards(withdrawn_amount) - withdrawn_amount) / 10; + unpaid_commission = with_rewards(unpaid_commission) + commission_on_withdrawn_amount; + withdrawn_amount = with_rewards(withdrawn_amount) - commission_on_withdrawn_amount; + stake::assert_stake_pool(pool_address, 0, with_rewards(new_balance), 0, 0); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_INACTIVE, 0); + + // Distribute and verify balances. + distribute(staker_address, operator_address); + assert_no_pending_distributions(staker_address, operator_address); + operator_balance = coin::balance(operator_address); + assert!(operator_balance == expected_operator_balance + unpaid_commission, operator_balance); + let staker_balance = coin::balance(staker_address); + // Staker receives the extra dust due to rounding error. + assert!(staker_balance == withdrawn_amount + 1, staker_balance); + assert_no_pending_distributions(staker_address, operator_address); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_operator_cannot_request_same_commission_multiple_times( + aptos_framework: &signer, staker: &signer, operator: &signer) acquires Store, BeneficiaryForOperator { + setup_staking_contract(aptos_framework, staker, operator, INITIAL_BALANCE, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + let pool_address = stake_pool_address(staker_address, operator_address); + + // Operator joins the validator set. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, pool_address, true); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 1); + + // Fast forward to generate rewards. + stake::end_epoch(); + let new_balance = with_rewards(INITIAL_BALANCE); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, 0); + + // Operator tries to request commission multiple times. But their distribution shouldn't change. + let expected_commission = (new_balance - last_recorded_principal(staker_address, operator_address)) / 10; + request_commission(operator, staker_address, operator_address); + assert_distribution(staker_address, operator_address, operator_address, expected_commission); + request_commission(operator, staker_address, operator_address); + assert_distribution(staker_address, operator_address, operator_address, expected_commission); + request_commission(operator, staker_address, operator_address); + assert_distribution(staker_address, operator_address, operator_address, expected_commission); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_unlock_rewards( + aptos_framework: &signer, staker: &signer, operator: &signer) acquires Store, BeneficiaryForOperator { + setup_staking_contract(aptos_framework, staker, operator, INITIAL_BALANCE, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + let pool_address = stake_pool_address(staker_address, operator_address); + + // Operator joins the validator set. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, pool_address, true); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 1); + + // Fast forward to generate rewards. + stake::end_epoch(); + let new_balance = with_rewards(INITIAL_BALANCE); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, 0); + + // Staker withdraws all accumulated rewards, which should pay commission first. + unlock_rewards(staker, operator_address); + let accumulated_rewards = new_balance - INITIAL_BALANCE; + let expected_commission = accumulated_rewards / 10; + let staker_rewards = accumulated_rewards - expected_commission; + assert_distribution(staker_address, operator_address, staker_address, staker_rewards); + assert_distribution(staker_address, operator_address, operator_address, expected_commission); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + #[expected_failure(abort_code = 0x80006, location = Self)] + public entry fun test_staker_cannot_create_same_staking_contract_multiple_times( + aptos_framework: &signer, + staker: &signer, + operator: &signer, + ) acquires Store { + setup_staking_contract(aptos_framework, staker, operator, INITIAL_BALANCE, 10); + let operator_address = signer::address_of(operator); + stake::mint(staker, INITIAL_BALANCE); + create_staking_contract(staker, operator_address, operator_address, INITIAL_BALANCE, 10, vector::empty()); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + #[expected_failure(abort_code = 0x10002, location = Self)] + public entry fun test_staker_cannot_create_staking_contract_with_invalid_commission( + aptos_framework: &signer, + staker: &signer, + operator: &signer, + ) acquires Store { + setup_staking_contract(aptos_framework, staker, operator, INITIAL_BALANCE, 101); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + #[expected_failure(abort_code = 0x10001, location = Self)] + public entry fun test_staker_cannot_create_staking_contract_with_less_than_min_stake_required( + aptos_framework: &signer, + staker: &signer, + operator: &signer, + ) acquires Store { + setup_staking_contract(aptos_framework, staker, operator, 50, 100); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_update_voter( + aptos_framework: &signer, + staker: &signer, + operator: &signer, + ) acquires Store { + setup_staking_contract(aptos_framework, staker, operator, INITIAL_BALANCE, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + + // Voter is initially set to operator but then updated to be staker. + let pool_address = stake_pool_address(staker_address, operator_address); + assert!(stake::get_delegated_voter(pool_address) == operator_address, 0); + update_voter(staker, operator_address, staker_address); + assert!(stake::get_delegated_voter(pool_address) == staker_address, 1); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_reset_lockup( + aptos_framework: &signer, + staker: &signer, + operator: &signer, + ) acquires Store { + setup_staking_contract(aptos_framework, staker, operator, INITIAL_BALANCE, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + let pool_address = stake_pool_address(staker_address, operator_address); + + let origin_lockup_expiration = stake::get_lockup_secs(pool_address); + reset_lockup(staker, operator_address); + assert!(origin_lockup_expiration < stake::get_lockup_secs(pool_address), 0); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator_1 = @0x234, operator_2 = @0x345)] + public entry fun test_staker_can_switch_operator( + aptos_framework: &signer, + staker: &signer, + operator_1: &signer, + operator_2: &signer, + ) acquires Store, BeneficiaryForOperator { + setup_staking_contract(aptos_framework, staker, operator_1, INITIAL_BALANCE, 10); + account::create_account_for_test(signer::address_of(operator_2)); + stake::mint(operator_2, INITIAL_BALANCE); + let staker_address = signer::address_of(staker); + let operator_1_address = signer::address_of(operator_1); + let operator_2_address = signer::address_of(operator_2); + + // Join validator set and earn some rewards. + let pool_address = stake_pool_address(staker_address, operator_1_address); + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator_1, pool_address, true); + stake::end_epoch(); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 0); + + // Switch operators. + switch_operator(staker, operator_1_address, operator_2_address, 20); + // The staking_contract is now associated with operator 2 but there should be a pending distribution of unpaid + // commission to operator 1. + let new_balance = with_rewards(INITIAL_BALANCE); + let commission_for_operator_1 = (new_balance - INITIAL_BALANCE) / 10; + assert_distribution(staker_address, operator_2_address, operator_1_address, commission_for_operator_1); + // Unpaid commission should be unlocked from the stake pool. + new_balance = new_balance - commission_for_operator_1; + stake::assert_stake_pool(pool_address, new_balance, 0, 0, commission_for_operator_1); + assert!(last_recorded_principal(staker_address, operator_2_address) == new_balance, 0); + + // The stake pool's validator should not have left the validator set. + assert!(stake_pool_address(staker_address, operator_2_address) == pool_address, 1); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 2); + + // End epoch to get more rewards. + stake::fast_forward_to_unlock(pool_address); + new_balance = with_rewards(new_balance); + // Rewards on the commission being paid to operator_1 should still be charged commission that will go to + // operator_2; + let commission_on_operator_1_distribution = + (with_rewards(commission_for_operator_1) - commission_for_operator_1) / 5; + commission_for_operator_1 = with_rewards(commission_for_operator_1) - commission_on_operator_1_distribution; + + // Verify that when commissions are withdrawn, previous pending distribution to operator 1 also happens. + // Then new commission of 20% is paid to operator 2. + let commission_for_operator_2 = + (new_balance - last_recorded_principal(staker_address, operator_2_address)) / 5; + new_balance = new_balance - commission_for_operator_2; + request_commission(operator_2, staker_address, operator_2_address); + assert_distribution(staker_address, operator_2_address, operator_2_address, commission_for_operator_2); + let operator_1_balance = coin::balance(operator_1_address); + assert!(operator_1_balance == INITIAL_BALANCE + commission_for_operator_1, operator_1_balance); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, commission_for_operator_2); + assert!(last_recorded_principal(staker_address, operator_2_address) == new_balance, 0); + stake::fast_forward_to_unlock(pool_address); + + // Operator 2's commission is distributed. + distribute(staker_address, operator_2_address); + let operator_2_balance = coin::balance(operator_2_address); + new_balance = with_rewards(new_balance); + commission_for_operator_2 = with_rewards(commission_for_operator_2); + assert!( + operator_2_balance == INITIAL_BALANCE + commission_for_operator_2 + commission_on_operator_1_distribution, + operator_2_balance, + ); + stake::assert_stake_pool( + pool_address, + new_balance, + 0, + 0, + 0, + ); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator_1 = @0x234, operator_2 = @0x345)] + public entry fun test_staker_can_switch_operator_with_same_commission( + aptos_framework: &signer, + staker: &signer, + operator_1: &signer, + operator_2: &signer, + ) acquires Store, BeneficiaryForOperator { + setup_staking_contract(aptos_framework, staker, operator_1, INITIAL_BALANCE, 10); + let staker_address = signer::address_of(staker); + let operator_1_address = signer::address_of(operator_1); + let operator_2_address = signer::address_of(operator_2); + + // Switch operators. + switch_operator_with_same_commission(staker, operator_1_address, operator_2_address); + // The staking_contract should now be associated with operator 2 but with same commission rate. + assert!(staking_contract_exists(staker_address, operator_2_address), 0); + assert!(!staking_contract_exists(staker_address, operator_1_address), 1); + assert!(commission_percentage(staker_address, operator_2_address) == 10, 2); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator1 = @0x234, beneficiary = @0x345, operator2 = @0x456)] + public entry fun test_operator_can_set_beneficiary( + aptos_framework: &signer, + staker: &signer, + operator1: &signer, + beneficiary: &signer, + operator2: &signer, + ) acquires Store, BeneficiaryForOperator { + setup_staking_contract(aptos_framework, staker, operator1, INITIAL_BALANCE, 10); + let staker_address = signer::address_of(staker); + let operator1_address = signer::address_of(operator1); + let operator2_address = signer::address_of(operator2); + let beneficiary_address = signer::address_of(beneficiary); + + // account::create_account_for_test(beneficiary_address); + aptos_framework::aptos_account::create_account(beneficiary_address); + assert_staking_contract_exists(staker_address, operator1_address); + assert_staking_contract(staker_address, operator1_address, INITIAL_BALANCE, 10); + + // Verify that the stake pool has been set up properly. + let pool_address = stake_pool_address(staker_address, operator1_address); + stake::assert_stake_pool(pool_address, INITIAL_BALANCE, 0, 0, 0); + assert!(last_recorded_principal(staker_address, operator1_address) == INITIAL_BALANCE, 0); + assert!(stake::get_operator(pool_address) == operator1_address, 0); + assert!(beneficiary_for_operator(operator1_address) == operator1_address, 0); + + // Operator joins the validator set. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator1, pool_address, true); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 1); + + // Set beneficiary. + set_beneficiary_for_operator(operator1, beneficiary_address); + assert!(beneficiary_for_operator(operator1_address) == beneficiary_address, 0); + + // Fast forward to generate rewards. + stake::end_epoch(); + let new_balance = with_rewards(INITIAL_BALANCE); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, 0); + + // Operator claims 10% of rewards so far as commissions. + let expected_commission_1 = (new_balance - last_recorded_principal(staker_address, operator1_address)) / 10; + new_balance = new_balance - expected_commission_1; + request_commission(operator1, staker_address, operator1_address); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, expected_commission_1); + assert!(last_recorded_principal(staker_address, operator1_address) == new_balance, 0); + assert_distribution(staker_address, operator1_address, operator1_address, expected_commission_1); + stake::fast_forward_to_unlock(pool_address); + + // Both original stake and operator commissions have received rewards. + expected_commission_1 = with_rewards(expected_commission_1); + new_balance = with_rewards(new_balance); + stake::assert_stake_pool(pool_address, new_balance, expected_commission_1, 0, 0); + distribute(staker_address, operator1_address); + let operator_balance = coin::balance(operator1_address); + let beneficiary_balance = coin::balance(beneficiary_address); + let expected_operator_balance = INITIAL_BALANCE; + let expected_beneficiary_balance = expected_commission_1; + assert!(operator_balance == expected_operator_balance, operator_balance); + assert!(beneficiary_balance == expected_beneficiary_balance, beneficiary_balance); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, 0); + assert_no_pending_distributions(staker_address, operator1_address); + + // switch operator to operator2. The rewards should go to operator2 not to the beneficiay of operator1. + let old_beneficiay_balance = beneficiary_balance; + switch_operator(staker, operator1_address, operator2_address, 10); + + stake::end_epoch(); + let (_, accumulated_rewards, _) = staking_contract_amounts(staker_address, operator2_address); + + let expected_commission = accumulated_rewards / 10; + + // Request commission. + request_commission(operator2, staker_address, operator2_address); + // Unlocks the commission. + stake::fast_forward_to_unlock(pool_address); + expected_commission = with_rewards(expected_commission); + + // Distribute the commission to the operator. + distribute(staker_address, operator2_address); + + // Assert that the rewards go to operator2, and the balance of the operator1's beneficiay remains the same. + assert!(coin::balance(operator2_address) >= expected_commission, 1); + assert!(coin::balance(beneficiary_address) == old_beneficiay_balance, 1); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_staker_can_withdraw_partial_stake( + aptos_framework: &signer, staker: &signer, operator: &signer) acquires Store, BeneficiaryForOperator { + let initial_balance = INITIAL_BALANCE * 2; + setup_staking_contract(aptos_framework, staker, operator, initial_balance, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + let pool_address = stake_pool_address(staker_address, operator_address); + + // Operator joins the validator set so rewards are generated. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, pool_address, true); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 1); + + // Fast forward to generate rewards. + stake::end_epoch(); + let new_balance = with_rewards(initial_balance); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, 0); + + // Staker withdraws 1/4 of the stake, which should also request commission distribution. + let withdrawn_stake = new_balance / 4; + let unpaid_commission = (new_balance - initial_balance) / 10; + let new_balance = new_balance - withdrawn_stake - unpaid_commission; + unlock_stake(staker, operator_address, withdrawn_stake); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, withdrawn_stake + unpaid_commission); + assert_distribution(staker_address, operator_address, operator_address, unpaid_commission); + assert_distribution(staker_address, operator_address, staker_address, withdrawn_stake); + assert!(last_recorded_principal(staker_address, operator_address) == new_balance, 0); + + // The validator is still in the active set as its remaining stake is still above min required. + stake::fast_forward_to_unlock(pool_address); + new_balance = with_rewards(new_balance); + unpaid_commission = with_rewards(unpaid_commission); + // Commission should still be charged on the rewards on top of withdrawn_stake. + // So the operator should receive 10% of the rewards on top of withdrawn_stake. + let commission_on_withdrawn_stake = (with_rewards(withdrawn_stake) - withdrawn_stake) / 10; + unpaid_commission = unpaid_commission + commission_on_withdrawn_stake; + withdrawn_stake = with_rewards(withdrawn_stake) - commission_on_withdrawn_stake; + stake::assert_stake_pool(pool_address, new_balance, withdrawn_stake + unpaid_commission, 0, 0); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 0); + + // Distribute and verify balances. + distribute(staker_address, operator_address); + assert_no_pending_distributions(staker_address, operator_address); + let operator_balance = coin::balance(operator_address); + assert!(operator_balance == initial_balance + unpaid_commission, operator_balance); + let staker_balance = coin::balance(staker_address); + assert!(staker_balance == withdrawn_stake, staker_balance); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_staker_can_withdraw_partial_stake_if_operator_never_joined_validator_set( + aptos_framework: &signer, staker: &signer, operator: &signer) acquires Store, BeneficiaryForOperator { + let initial_balance = INITIAL_BALANCE * 2; + setup_staking_contract(aptos_framework, staker, operator, initial_balance, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + let pool_address = stake_pool_address(staker_address, operator_address); + + // Epoch ended, but since validator never joined the set, no rewards were minted. + stake::end_epoch(); + stake::assert_stake_pool(pool_address, initial_balance, 0, 0, 0); + + // Staker withdraws 1/4 of the stake, which doesn't create any commission distribution as there's no rewards. + let withdrawn_stake = initial_balance / 4; + let new_balance = initial_balance - withdrawn_stake; + unlock_stake(staker, operator_address, withdrawn_stake); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, withdrawn_stake); + assert_distribution(staker_address, operator_address, operator_address, 0); + assert_distribution(staker_address, operator_address, staker_address, withdrawn_stake); + assert!(last_recorded_principal(staker_address, operator_address) == new_balance, 0); + + // Distribute and verify balances. + distribute(staker_address, operator_address); + assert_no_pending_distributions(staker_address, operator_address); + // Operator's balance shouldn't change as there are no rewards. + let operator_balance = coin::balance(operator_address); + assert!(operator_balance == initial_balance, operator_balance); + // Staker receives back the withdrawn amount (no rewards). + let staker_balance = coin::balance(staker_address); + assert!(staker_balance == withdrawn_stake, staker_balance); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_multiple_distributions_added_before_distribute( + aptos_framework: &signer, staker: &signer, operator: &signer) acquires Store, BeneficiaryForOperator { + let initial_balance = INITIAL_BALANCE * 2; + setup_staking_contract(aptos_framework, staker, operator, initial_balance, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + let pool_address = stake_pool_address(staker_address, operator_address); + + // Operator joins the validator set so rewards are generated. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, pool_address, true); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 1); + + // Fast forward to generate rewards. + stake::end_epoch(); + let new_balance = with_rewards(initial_balance); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, 0); + + // Staker withdraws 1/4 of the stake, which should also request commission distribution. + let withdrawn_stake = new_balance / 4; + let unpaid_commission = (new_balance - initial_balance) / 10; + let new_balance = new_balance - withdrawn_stake - unpaid_commission; + unlock_stake(staker, operator_address, withdrawn_stake); + stake::assert_stake_pool(pool_address, new_balance, 0, 0, withdrawn_stake + unpaid_commission); + assert_distribution(staker_address, operator_address, operator_address, unpaid_commission); + assert_distribution(staker_address, operator_address, staker_address, withdrawn_stake); + assert!(last_recorded_principal(staker_address, operator_address) == new_balance, 0); + + // End epoch to generate some rewards. Staker withdraws another 1/4 of the stake. + // Commission should be charged on the rewards earned on the previous 1/4 stake withdrawal. + stake::end_epoch(); + let commission_on_withdrawn_stake = (with_rewards(withdrawn_stake) - withdrawn_stake) / 10; + let commission_on_new_balance = (with_rewards(new_balance) - new_balance) / 10; + unpaid_commission = with_rewards(unpaid_commission) + commission_on_withdrawn_stake + commission_on_new_balance; + new_balance = with_rewards(new_balance) - commission_on_new_balance; + let new_withdrawn_stake = new_balance / 4; + unlock_stake(staker, operator_address, new_withdrawn_stake); + new_balance = new_balance - new_withdrawn_stake; + withdrawn_stake = with_rewards(withdrawn_stake) - commission_on_withdrawn_stake + new_withdrawn_stake; + stake::assert_stake_pool(pool_address, new_balance, 0, 0, withdrawn_stake + unpaid_commission); + // There's some small rounding error here. + assert_distribution(staker_address, operator_address, operator_address, unpaid_commission - 1); + assert_distribution(staker_address, operator_address, staker_address, withdrawn_stake); + assert!(last_recorded_principal(staker_address, operator_address) == new_balance, 0); + } + + #[test(aptos_framework = @0x1, staker = @0x123, operator = @0x234)] + public entry fun test_update_commission( + aptos_framework: &signer, + staker: &signer, + operator: &signer + ) acquires Store, BeneficiaryForOperator, StakingGroupUpdateCommissionEvent { + let initial_balance = INITIAL_BALANCE * 2; + setup_staking_contract(aptos_framework, staker, operator, initial_balance, 10); + let staker_address = signer::address_of(staker); + let operator_address = signer::address_of(operator); + let pool_address = stake_pool_address(staker_address, operator_address); + + // Operator joins the validator set so rewards are generated. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, pool_address, true); + assert!(stake::get_validator_state(pool_address) == VALIDATOR_STATUS_ACTIVE, 1); + + // Fast forward to generate rewards. + stake::end_epoch(); + let balance_1epoch = with_rewards(initial_balance); + let unpaid_commission = (balance_1epoch - initial_balance) / 10; + stake::assert_stake_pool(pool_address, balance_1epoch, 0, 0, 0); + + update_commision(staker, operator_address, 5); + stake::end_epoch(); + let balance_2epoch = with_rewards(balance_1epoch - unpaid_commission); + stake::assert_stake_pool(pool_address, balance_2epoch, 0, 0, with_rewards(unpaid_commission)); + } + + #[test( + staker = @0xe256f4f4e2986cada739e339895cf5585082ff247464cab8ec56eea726bd2263, + operator = @0x9f0a211d218b082987408f1e393afe1ba0c202c6d280f081399788d3360c7f09 + )] + public entry fun test_get_expected_stake_pool_address(staker: address, operator: address) { + let pool_address = get_expected_stake_pool_address(staker, operator, vector[0x42, 0x42]); + assert!(pool_address == @0x9d9648031ada367c26f7878eb0b0406ae6a969b1a43090269e5cdfabe1b48f0f, 0); + } + + #[test_only] + public fun assert_staking_contract( + staker: address, operator: address, principal: u64, commission_percentage: u64) acquires Store { + let staking_contract = simple_map::borrow(&borrow_global(staker).staking_contracts, &operator); + assert!(staking_contract.principal == principal, staking_contract.principal); + assert!( + staking_contract.commission_percentage == commission_percentage, + staking_contract.commission_percentage + ); + } + + #[test_only] + public fun assert_no_pending_distributions(staker: address, operator: address) acquires Store { + let staking_contract = simple_map::borrow(&borrow_global(staker).staking_contracts, &operator); + let distribution_pool = &staking_contract.distribution_pool; + let shareholders_count = pool_u64::shareholders_count(distribution_pool); + assert!(shareholders_count == 0, shareholders_count); + let total_coins_remaining = pool_u64::total_coins(distribution_pool); + assert!(total_coins_remaining == 0, total_coins_remaining); + } + + #[test_only] + public fun assert_distribution( + staker: address, operator: address, recipient: address, coins_amount: u64) acquires Store { + let staking_contract = simple_map::borrow(&borrow_global(staker).staking_contracts, &operator); + let distribution_balance = pool_u64::balance(&staking_contract.distribution_pool, recipient); + assert!(distribution_balance == coins_amount, distribution_balance); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/staking_proxy.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/staking_proxy.move new file mode 100644 index 000000000..26d1aa333 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/staking_proxy.move @@ -0,0 +1,228 @@ +module aptos_framework::staking_proxy { + use std::signer; + use std::vector; + + use aptos_framework::stake; + use aptos_framework::staking_contract; + use aptos_framework::vesting; + + public entry fun set_operator(owner: &signer, old_operator: address, new_operator: address) { + set_vesting_contract_operator(owner, old_operator, new_operator); + set_staking_contract_operator(owner, old_operator, new_operator); + set_stake_pool_operator(owner, new_operator); + } + + public entry fun set_voter(owner: &signer, operator: address, new_voter: address) { + set_vesting_contract_voter(owner, operator, new_voter); + set_staking_contract_voter(owner, operator, new_voter); + set_stake_pool_voter(owner, new_voter); + } + + public entry fun set_vesting_contract_operator(owner: &signer, old_operator: address, new_operator: address) { + let owner_address = signer::address_of(owner); + let vesting_contracts = &vesting::vesting_contracts(owner_address); + vector::for_each_ref(vesting_contracts, |vesting_contract| { + let vesting_contract = *vesting_contract; + if (vesting::operator(vesting_contract) == old_operator) { + let current_commission_percentage = vesting::operator_commission_percentage(vesting_contract); + vesting::update_operator(owner, vesting_contract, new_operator, current_commission_percentage); + }; + }); + } + + public entry fun set_staking_contract_operator(owner: &signer, old_operator: address, new_operator: address) { + let owner_address = signer::address_of(owner); + if (staking_contract::staking_contract_exists(owner_address, old_operator)) { + let current_commission_percentage = staking_contract::commission_percentage(owner_address, old_operator); + staking_contract::switch_operator(owner, old_operator, new_operator, current_commission_percentage); + }; + } + + public entry fun set_stake_pool_operator(owner: &signer, new_operator: address) { + let owner_address = signer::address_of(owner); + if (stake::stake_pool_exists(owner_address)) { + stake::set_operator(owner, new_operator); + }; + } + + public entry fun set_vesting_contract_voter(owner: &signer, operator: address, new_voter: address) { + let owner_address = signer::address_of(owner); + let vesting_contracts = &vesting::vesting_contracts(owner_address); + vector::for_each_ref(vesting_contracts, |vesting_contract| { + let vesting_contract = *vesting_contract; + if (vesting::operator(vesting_contract) == operator) { + vesting::update_voter(owner, vesting_contract, new_voter); + }; + }); + } + + public entry fun set_staking_contract_voter(owner: &signer, operator: address, new_voter: address) { + let owner_address = signer::address_of(owner); + if (staking_contract::staking_contract_exists(owner_address, operator)) { + staking_contract::update_voter(owner, operator, new_voter); + }; + } + + public entry fun set_stake_pool_voter(owner: &signer, new_voter: address) { + if (stake::stake_pool_exists(signer::address_of(owner))) { + stake::set_delegated_voter(owner, new_voter); + }; + } + + #[test_only] + const INITIAL_BALANCE: u64 = 100000000000000; // 1M APT coins with 8 decimals. + + #[test( + aptos_framework = @0x1, + owner = @0x123, + operator_1 = @0x234, + operator_2 = @0x345, + new_operator = @0x567, + )] + public entry fun test_set_operator( + aptos_framework: &signer, + owner: &signer, + operator_1: &signer, + operator_2: &signer, + new_operator: &signer, + ) { + let owner_address = signer::address_of(owner); + let operator_1_address = signer::address_of(operator_1); + let operator_2_address = signer::address_of(operator_2); + let new_operator_address = signer::address_of(new_operator); + vesting::setup( + aptos_framework, &vector[owner_address, operator_1_address, operator_2_address, new_operator_address]); + staking_contract::setup_staking_contract(aptos_framework, owner, operator_1, INITIAL_BALANCE, 0); + staking_contract::setup_staking_contract(aptos_framework, owner, operator_2, INITIAL_BALANCE, 0); + + let vesting_contract_1 = vesting::setup_vesting_contract(owner, &vector[@11], &vector[INITIAL_BALANCE], owner_address, 0); + vesting::update_operator(owner, vesting_contract_1, operator_1_address, 0); + let vesting_contract_2 = vesting::setup_vesting_contract(owner, &vector[@12], &vector[INITIAL_BALANCE], owner_address, 0); + vesting::update_operator(owner, vesting_contract_2, operator_2_address, 0); + + let (_sk, pk, pop) = stake::generate_identity(); + stake::initialize_test_validator(&pk, &pop, owner, INITIAL_BALANCE, false, false); + stake::set_operator(owner, operator_1_address); + + set_operator(owner, operator_1_address, new_operator_address); + // Stake pool's operator has been switched from operator 1 to new operator. + assert!(stake::get_operator(owner_address) == new_operator_address, 0); + // Staking contract has been switched from operator 1 to new operator. + // Staking contract with operator_2 should stay unchanged. + assert!(staking_contract::staking_contract_exists(owner_address, new_operator_address), 1); + assert!(!staking_contract::staking_contract_exists(owner_address, operator_1_address), 2); + assert!(staking_contract::staking_contract_exists(owner_address, operator_2_address), 3); + // Vesting contract 1 has been switched from operator 1 to new operator while vesting contract 2 stays unchanged + assert!(vesting::operator(vesting_contract_1) == new_operator_address, 4); + assert!(vesting::operator(vesting_contract_2) == operator_2_address, 5); + } + + #[test( + aptos_framework = @0x1, + owner = @0x123, + operator_1 = @0x234, + operator_2 = @0x345, + new_operator = @0x567, + )] + public entry fun test_set_operator_nothing_to_change( + aptos_framework: &signer, + owner: &signer, + operator_1: &signer, + operator_2: &signer, + new_operator: &signer, + ) { + let owner_address = signer::address_of(owner); + let operator_1_address = signer::address_of(operator_1); + let operator_2_address = signer::address_of(operator_2); + let new_operator_address = signer::address_of(new_operator); + vesting::setup( + aptos_framework, &vector[owner_address, operator_1_address, operator_2_address, new_operator_address]); + staking_contract::setup_staking_contract(aptos_framework, owner, operator_2, INITIAL_BALANCE, 0); + + let vesting_contract_2 = vesting::setup_vesting_contract(owner, &vector[@12], &vector[INITIAL_BALANCE], owner_address, 0); + vesting::update_operator(owner, vesting_contract_2, operator_2_address, 0); + + set_operator(owner, operator_1_address, new_operator_address); + // No staking or vesting contracts changed. + assert!(!staking_contract::staking_contract_exists(owner_address, new_operator_address), 0); + assert!(staking_contract::staking_contract_exists(owner_address, operator_2_address), 1); + assert!(vesting::operator(vesting_contract_2) == operator_2_address, 2); + } + + #[test( + aptos_framework = @0x1, + owner = @0x123, + operator_1 = @0x234, + operator_2 = @0x345, + new_voter = @0x567, + )] + public entry fun test_set_voter( + aptos_framework: &signer, + owner: &signer, + operator_1: &signer, + operator_2: &signer, + new_voter: &signer, + ) { + let owner_address = signer::address_of(owner); + let operator_1_address = signer::address_of(operator_1); + let operator_2_address = signer::address_of(operator_2); + let new_voter_address = signer::address_of(new_voter); + vesting::setup( + aptos_framework, &vector[owner_address, operator_1_address, operator_2_address, new_voter_address]); + staking_contract::setup_staking_contract(aptos_framework, owner, operator_1, INITIAL_BALANCE, 0); + staking_contract::setup_staking_contract(aptos_framework, owner, operator_2, INITIAL_BALANCE, 0); + + let vesting_contract_1 = vesting::setup_vesting_contract(owner, &vector[@11], &vector[INITIAL_BALANCE], owner_address, 0); + vesting::update_operator(owner, vesting_contract_1, operator_1_address, 0); + let vesting_contract_2 = vesting::setup_vesting_contract(owner, &vector[@12], &vector[INITIAL_BALANCE], owner_address, 0); + vesting::update_operator(owner, vesting_contract_2, operator_2_address, 0); + + let (_sk, pk, pop) = stake::generate_identity(); + stake::initialize_test_validator(&pk, &pop, owner, INITIAL_BALANCE, false, false); + + set_voter(owner, operator_1_address, new_voter_address); + // Stake pool's voter has been updated. + assert!(stake::get_delegated_voter(owner_address) == new_voter_address, 0); + // Staking contract with operator 1's voter has been updated. + // Staking contract with operator_2 should stay unchanged. + let stake_pool_address_1 = staking_contract::stake_pool_address(owner_address, operator_1_address); + let stake_pool_address_2 = staking_contract::stake_pool_address(owner_address, operator_2_address); + assert!(stake::get_delegated_voter(stake_pool_address_1) == new_voter_address, 1); + assert!(stake::get_delegated_voter(stake_pool_address_2) == operator_2_address, 2); + // Vesting contract 1's voter has been updated while vesting contract 2's stays unchanged. + assert!(vesting::voter(vesting_contract_1) == new_voter_address, 3); + assert!(vesting::voter(vesting_contract_2) == owner_address, 4); + } + + #[test( + aptos_framework = @0x1, + owner = @0x123, + operator_1 = @0x234, + operator_2 = @0x345, + new_voter = @0x567, + )] + public entry fun test_set_voter_nothing_to_change( + aptos_framework: &signer, + owner: &signer, + operator_1: &signer, + operator_2: &signer, + new_voter: &signer, + ) { + let owner_address = signer::address_of(owner); + let operator_1_address = signer::address_of(operator_1); + let operator_2_address = signer::address_of(operator_2); + let new_voter_address = signer::address_of(new_voter); + vesting::setup( + aptos_framework, &vector[owner_address, operator_1_address, operator_2_address, new_voter_address]); + staking_contract::setup_staking_contract(aptos_framework, owner, operator_2, INITIAL_BALANCE, 0); + + let vesting_contract_2 = vesting::setup_vesting_contract(owner, &vector[@12], &vector[INITIAL_BALANCE], owner_address, 0); + vesting::update_operator(owner, vesting_contract_2, operator_2_address, 0); + + set_operator(owner, operator_1_address, new_voter_address); + // No staking or vesting contracts changed. + let stake_pool_address = staking_contract::stake_pool_address(owner_address, operator_2_address); + assert!(stake::get_delegated_voter(stake_pool_address) == operator_2_address, 0); + assert!(vesting::voter(vesting_contract_2) == owner_address, 1); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/state_storage.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/state_storage.move new file mode 100644 index 000000000..af9d74961 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/state_storage.move @@ -0,0 +1,90 @@ +module aptos_framework::state_storage { + + use aptos_framework::system_addresses; + use std::error; + + friend aptos_framework::block; + friend aptos_framework::genesis; + friend aptos_framework::storage_gas; + + const ESTATE_STORAGE_USAGE: u64 = 0; + + struct Usage has copy, drop, store { + items: u64, + bytes: u64, + } + + /// This is updated at the beginning of each epoch, reflecting the storage + /// usage after the last txn of the previous epoch is committed. + struct StateStorageUsage has key, store { + epoch: u64, + usage: Usage, + } + + public(friend) fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!( + !exists(@aptos_framework), + error::already_exists(ESTATE_STORAGE_USAGE) + ); + move_to(aptos_framework, StateStorageUsage { + epoch: 0, + usage: Usage { + items: 0, + bytes: 0, + } + }); + } + + public(friend) fun on_new_block(epoch: u64) acquires StateStorageUsage { + assert!( + exists(@aptos_framework), + error::not_found(ESTATE_STORAGE_USAGE) + ); + let usage = borrow_global_mut(@aptos_framework); + if (epoch != usage.epoch) { + usage.epoch = epoch; + usage.usage = get_state_storage_usage_only_at_epoch_beginning(); + } + } + + public(friend) fun current_items_and_bytes(): (u64, u64) acquires StateStorageUsage { + assert!( + exists(@aptos_framework), + error::not_found(ESTATE_STORAGE_USAGE) + ); + let usage = borrow_global(@aptos_framework); + (usage.usage.items, usage.usage.bytes) + } + + /// Warning: the result returned is based on the base state view held by the + /// VM for the entire block or chunk of transactions, it's only deterministic + /// if called from the first transaction of the block because the execution layer + /// guarantees a fresh state view then. + native fun get_state_storage_usage_only_at_epoch_beginning(): Usage; + + #[test_only] + public fun set_for_test(epoch: u64, items: u64, bytes: u64) acquires StateStorageUsage { + assert!( + exists(@aptos_framework), + error::not_found(ESTATE_STORAGE_USAGE) + ); + let usage = borrow_global_mut(@aptos_framework); + usage.epoch = epoch; + usage.usage = Usage { + items, + bytes + }; + } + + // ======================== deprecated ============================ + friend aptos_framework::reconfiguration; + + struct GasParameter has key, store { + usage: Usage, + } + + public(friend) fun on_reconfig() { + abort 0 + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/storage_gas.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/storage_gas.move new file mode 100644 index 000000000..991b61925 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/storage_gas.move @@ -0,0 +1,622 @@ +/// Gas parameters for global storage. +/// +/// # General overview sections +/// +/// [Definitions](#definitions) +/// +/// * [Utilization dimensions](#utilization-dimensions) +/// * [Utilization ratios](#utilization-ratios) +/// * [Gas curve lookup](#gas-curve-lookup) +/// * [Item-wise operations](#item-wise-operations) +/// * [Byte-wise operations](#byte-wise-operations) +/// +/// [Function dependencies](#function-dependencies) +/// +/// * [Initialization](#initialization) +/// * [Reconfiguration](#reconfiguration) +/// * [Setting configurations](#setting-configurations) +/// +/// # Definitions +/// +/// ## Utilization dimensions +/// +/// Global storage gas fluctuates each epoch based on total utilization, +/// which is defined across two dimensions: +/// +/// 1. The number of "items" in global storage. +/// 2. The number of bytes in global storage. +/// +/// "Items" include: +/// +/// 1. Resources having the `key` attribute, which have been moved into +/// global storage via a `move_to()` operation. +/// 2. Table entries. +/// +/// ## Utilization ratios +/// +/// `initialize()` sets an arbitrary "target" utilization for both +/// item-wise and byte-wise storage, then each epoch, gas parameters are +/// reconfigured based on the "utilization ratio" for each of the two +/// utilization dimensions. The utilization ratio for a given dimension, +/// either item-wise or byte-wise, is taken as the quotient of actual +/// utilization and target utilization. For example, given a 500 GB +/// target and 250 GB actual utilization, the byte-wise utilization +/// ratio is 50%. +/// +/// See `base_8192_exponential_curve()` for mathematical definitions. +/// +/// ## Gas curve lookup +/// +/// The utilization ratio in a given epoch is used as a lookup value in +/// a Eulerian approximation to an exponential curve, known as a +/// `GasCurve`, which is defined in `base_8192_exponential_curve()`, +/// based on a minimum gas charge and a maximum gas charge. +/// +/// The minimum gas charge and maximum gas charge at the endpoints of +/// the curve are set in `initialize()`, and correspond to the following +/// operations defined in `StorageGas`: +/// +/// 1. Per-item read +/// 2. Per-item create +/// 3. Per-item write +/// 4. Per-byte read +/// 5. Per-byte create +/// 6. Per-byte write +/// +/// For example, if the byte-wise utilization ratio is 50%, then +/// per-byte reads will charge the minimum per-byte gas cost, plus +/// 1.09% of the difference between the maximum and the minimum cost. +/// See `base_8192_exponential_curve()` for a supporting calculation. +/// +/// ## Item-wise operations +/// +/// 1. Per-item read gas is assessed whenever an item is read from +/// global storage via `borrow_global()` or via a table entry read +/// operation. +/// 2. Per-item create gas is assessed whenever an item is created in +/// global storage via `move_to()` or via a table entry creation +/// operation. +/// 3. Per-item write gas is assessed whenever an item is overwritten in +/// global storage via `borrow_global_mut` or via a table entry +/// mutation operation. +/// +/// ## Byte-wise operations +/// +/// Byte-wise operations are assessed in a manner similar to per-item +/// operations, but account for the number of bytes affected by the +/// given operation. Notably, this number denotes the total number of +/// bytes in an *entire item*. +/// +/// For example, if an operation mutates a `u8` field in a resource that +/// has 5 other `u128` fields, the per-byte gas write cost will account +/// for $(5 * 128) / 8 + 1 = 81$ bytes. Vectors are similarly treated +/// as fields. +/// +/// # Function dependencies +/// +/// The below dependency chart uses `mermaid.js` syntax, which can be +/// automatically rendered into a diagram (depending on the browser) +/// when viewing the documentation file generated from source code. If +/// a browser renders the diagrams with coloring that makes it difficult +/// to read, try a different browser. +/// +/// ## Initialization +/// +/// ```mermaid +/// +/// flowchart LR +/// +/// initialize --> base_8192_exponential_curve +/// base_8192_exponential_curve --> new_gas_curve +/// base_8192_exponential_curve --> new_point +/// new_gas_curve --> validate_points +/// +/// ``` +/// +/// ## Reconfiguration +/// +/// ```mermaid +/// +/// flowchart LR +/// +/// calculate_gas --> Interpolate %% capitalized +/// calculate_read_gas --> calculate_gas +/// calculate_create_gas --> calculate_gas +/// calculate_write_gas --> calculate_gas +/// on_reconfig --> calculate_read_gas +/// on_reconfig --> calculate_create_gas +/// on_reconfig --> calculate_write_gas +/// reconfiguration::reconfigure --> on_reconfig +/// +/// ``` +/// +/// Here, the function `interpolate()` is spelled `Interpolate` because +/// `interpolate` is a reserved word in `mermaid.js`. +/// +/// ## Setting configurations +/// +/// ```mermaid +/// +/// flowchart LR +/// +/// gas_schedule::set_storage_gas_config --> set_config +/// +/// ``` +/// +/// # Complete docgen index +/// +/// The below index is automatically generated from source code: +module aptos_framework::storage_gas { + + use aptos_framework::system_addresses; + use std::error; + use aptos_framework::state_storage; + use std::vector; + + friend aptos_framework::gas_schedule; + friend aptos_framework::genesis; + friend aptos_framework::reconfiguration; + + const ESTORAGE_GAS_CONFIG: u64 = 0; + const ESTORAGE_GAS: u64 = 1; + const EINVALID_GAS_RANGE: u64 = 2; + const EZERO_TARGET_USAGE: u64 = 3; + const ETARGET_USAGE_TOO_BIG: u64 = 4; + const EINVALID_MONOTONICALLY_NON_DECREASING_CURVE: u64 = 5; + const EINVALID_POINT_RANGE: u64 = 6; + + const BASIS_POINT_DENOMINATION: u64 = 10000; + + const MAX_U64: u64 = 18446744073709551615; + + /// Storage parameters, reconfigured each epoch. + /// + /// Parameters are updated during reconfiguration via + /// `on_reconfig()`, based on storage utilization at the beginning + /// of the epoch in which the reconfiguration transaction is + /// executed. The gas schedule derived from these parameters will + /// then be used to calculate gas for the entirety of the + /// following epoch, such that the data is one epoch older than + /// ideal. Notably, however, per this approach, the virtual machine + /// does not need to reload gas parameters after the + /// first transaction of an epoch. + struct StorageGas has key { + /// Cost to read an item from global storage. + per_item_read: u64, + /// Cost to create an item in global storage. + per_item_create: u64, + /// Cost to overwrite an item in global storage. + per_item_write: u64, + /// Cost to read a byte from global storage. + per_byte_read: u64, + /// Cost to create a byte in global storage. + per_byte_create: u64, + /// Cost to overwrite a byte in global storage. + per_byte_write: u64, + } + + /// A point in a Eulerian curve approximation, with each coordinate + /// given in basis points: + /// + /// | Field value | Percentage | + /// |-------------|------------| + /// | `1` | 00.01 % | + /// | `10` | 00.10 % | + /// | `100` | 01.00 % | + /// | `1000` | 10.00 % | + struct Point has copy, drop, store { + /// x-coordinate basis points, corresponding to utilization + /// ratio in `base_8192_exponential_curve()`. + x: u64, + /// y-coordinate basis points, corresponding to utilization + /// multiplier in `base_8192_exponential_curve()`. + y: u64 + } + + /// A gas configuration for either per-item or per-byte costs. + /// + /// Contains a target usage amount, as well as a Eulerian + /// approximation of an exponential curve for reads, creations, and + /// overwrites. See `StorageGasConfig`. + struct UsageGasConfig has copy, drop, store { + target_usage: u64, + read_curve: GasCurve, + create_curve: GasCurve, + write_curve: GasCurve, + } + + /// Eulerian approximation of an exponential curve. + /// + /// Assumes the following endpoints: + /// + /// * $(x_0, y_0) = (0, 0)$ + /// * $(x_f, y_f) = (10000, 10000)$ + /// + /// Intermediate points must satisfy: + /// + /// 1. $x_i > x_{i - 1}$ ( $x$ is strictly increasing). + /// 2. $0 \leq x_i \leq 10000$ ( $x$ is between 0 and 10000). + /// 3. $y_i \geq y_{i - 1}$ ( $y$ is non-decreasing). + /// 4. $0 \leq y_i \leq 10000$ ( $y$ is between 0 and 10000). + /// + /// Lookup between two successive points is calculated via linear + /// interpolation, e.g., as if there were a straight line between + /// them. + /// + /// See `base_8192_exponential_curve()`. + struct GasCurve has copy, drop, store { + min_gas: u64, + max_gas: u64, + points: vector, + } + + /// Default exponential curve having base 8192. + /// + /// # Function definition + /// + /// Gas price as a function of utilization ratio is defined as: + /// + /// $$g(u_r) = g_{min} + \frac{(b^{u_r} - 1)}{b - 1} \Delta_g$$ + /// + /// $$g(u_r) = g_{min} + u_m \Delta_g$$ + /// + /// | Variable | Description | + /// |-------------------------------------|------------------------| + /// | $g_{min}$ | `min_gas` | + /// | $g_{max}$ | `max_gas` | + /// | $\Delta_{g} = g_{max} - g_{min}$ | Gas delta | + /// | $u$ | Utilization | + /// | $u_t$ | Target utilization | + /// | $u_r = u / u_t$ | Utilization ratio | + /// | $u_m = \frac{(b^{u_r} - 1)}{b - 1}$ | Utilization multiplier | + /// | $b = 8192$ | Exponent base | + /// + /// # Example + /// + /// Hence for a utilization ratio of 50% ( $u_r = 0.5$ ): + /// + /// $$g(0.5) = g_{min} + \frac{8192^{0.5} - 1}{8192 - 1} \Delta_g$$ + /// + /// $$g(0.5) \approx g_{min} + 0.0109 \Delta_g$$ + /// + /// Which means that the price above `min_gas` is approximately + /// 1.09% of the difference between `max_gas` and `min_gas`. + /// + /// # Utilization multipliers + /// + /// | $u_r$ | $u_m$ (approximate) | + /// |-------|---------------------| + /// | 10% | 0.02% | + /// | 20% | 0.06% | + /// | 30% | 0.17% | + /// | 40% | 0.44% | + /// | 50% | 1.09% | + /// | 60% | 2.71% | + /// | 70% | 6.69% | + /// | 80% | 16.48% | + /// | 90% | 40.61% | + /// | 95% | 63.72% | + /// | 99% | 91.38% | + public fun base_8192_exponential_curve(min_gas: u64, max_gas: u64): GasCurve { + new_gas_curve(min_gas, max_gas, + vector[ + new_point(1000, 2), + new_point(2000, 6), + new_point(3000, 17), + new_point(4000, 44), + new_point(5000, 109), + new_point(6000, 271), + new_point(7000, 669), + new_point(8000, 1648), + new_point(9000, 4061), + new_point(9500, 6372), + new_point(9900, 9138), + ] + ) + } + + /// Gas configurations for per-item and per-byte prices. + struct StorageGasConfig has copy, drop, key { + /// Per-item gas configuration. + item_config: UsageGasConfig, + /// Per-byte gas configuration. + byte_config: UsageGasConfig, + } + + public fun new_point(x: u64, y: u64): Point { + assert!( + x <= BASIS_POINT_DENOMINATION && y <= BASIS_POINT_DENOMINATION, + error::invalid_argument(EINVALID_POINT_RANGE) + ); + Point { x, y } + } + + public fun new_gas_curve(min_gas: u64, max_gas: u64, points: vector): GasCurve { + assert!(max_gas >= min_gas, error::invalid_argument(EINVALID_GAS_RANGE)); + assert!(max_gas <= MAX_U64 / BASIS_POINT_DENOMINATION, error::invalid_argument(EINVALID_GAS_RANGE)); + validate_points(&points); + GasCurve { + min_gas, + max_gas, + points + } + } + + public fun new_usage_gas_config(target_usage: u64, read_curve: GasCurve, create_curve: GasCurve, write_curve: GasCurve): UsageGasConfig { + assert!(target_usage > 0, error::invalid_argument(EZERO_TARGET_USAGE)); + assert!(target_usage <= MAX_U64 / BASIS_POINT_DENOMINATION, error::invalid_argument(ETARGET_USAGE_TOO_BIG)); + UsageGasConfig { + target_usage, + read_curve, + create_curve, + write_curve, + } + } + + public fun new_storage_gas_config(item_config: UsageGasConfig, byte_config: UsageGasConfig): StorageGasConfig { + StorageGasConfig { + item_config, + byte_config + } + } + + public(friend) fun set_config(aptos_framework: &signer, config: StorageGasConfig) acquires StorageGasConfig { + system_addresses::assert_aptos_framework(aptos_framework); + *borrow_global_mut(@aptos_framework) = config; + } + + /// Initialize per-item and per-byte gas prices. + /// + /// Target utilization is set to 2 billion items and 1 TB. + /// + /// `GasCurve` endpoints are initialized as follows: + /// + /// | Data style | Operation | Minimum gas | Maximum gas | + /// |------------|-----------|-------------|-------------| + /// | Per item | Read | 300K | 300K * 100 | + /// | Per item | Create | 300k | 300k * 100 | + /// | Per item | Write | 300K | 300K * 100 | + /// | Per byte | Read | 300 | 300 * 100 | + /// | Per byte | Create | 5K | 5K * 100 | + /// | Per byte | Write | 5K | 5K * 100 | + /// + /// `StorageGas` values are additionally initialized, but per + /// `on_reconfig()`, they will be reconfigured for each subsequent + /// epoch after initialization. + /// + /// See `base_8192_exponential_curve()` fore more information on + /// target utilization. + public fun initialize(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!( + !exists(@aptos_framework), + error::already_exists(ESTORAGE_GAS_CONFIG) + ); + + let k: u64 = 1000; + let m: u64 = 1000 * 1000; + + let item_config = UsageGasConfig { + target_usage: 2 * k * m, // 2 billion + read_curve: base_8192_exponential_curve(300 * k, 300 * k * 100), + create_curve: base_8192_exponential_curve(300 * k, 300 * k * 100), + write_curve: base_8192_exponential_curve(300 * k, 300 * k * 100), + }; + let byte_config = UsageGasConfig { + target_usage: 1 * m * m, // 1TB + read_curve: base_8192_exponential_curve(300, 300 * 100), + create_curve: base_8192_exponential_curve(5 * k, 5 * k * 100), + write_curve: base_8192_exponential_curve(5 * k, 5 * k * 100), + }; + move_to(aptos_framework, StorageGasConfig { + item_config, + byte_config, + }); + + assert!( + !exists(@aptos_framework), + error::already_exists(ESTORAGE_GAS) + ); + move_to(aptos_framework, StorageGas { + per_item_read: 300 * k, + per_item_create: 5 * m, + per_item_write: 300 * k, + per_byte_read: 300, + per_byte_create: 5 * k, + per_byte_write: 5 * k, + }); + } + + fun validate_points(points: &vector) { + let len = vector::length(points); + spec { + assume len < MAX_U64; + }; + let i = 0; + while ({ + spec { + invariant forall j in 0..i: { + let cur = if (j == 0) { Point { x: 0, y: 0 } } else { points[j - 1] }; + let next = if (j == len) { Point { x: BASIS_POINT_DENOMINATION, y: BASIS_POINT_DENOMINATION } } else { points[j] }; + cur.x < next.x && cur.y <= next.y + }; + }; + i <= len + }) { + let cur = if (i == 0) { &Point { x: 0, y: 0 } } else { vector::borrow(points, i - 1) }; + let next = if (i == len) { &Point { x: BASIS_POINT_DENOMINATION, y: BASIS_POINT_DENOMINATION } } else { vector::borrow(points, i) }; + assert!(cur.x < next.x && cur.y <= next.y, error::invalid_argument(EINVALID_MONOTONICALLY_NON_DECREASING_CURVE)); + i = i + 1; + } + } + + fun calculate_gas(max_usage: u64, current_usage: u64, curve: &GasCurve): u64 { + let capped_current_usage = if (current_usage > max_usage) max_usage else current_usage; + let points = &curve.points; + let num_points = vector::length(points); + let current_usage_bps = capped_current_usage * BASIS_POINT_DENOMINATION / max_usage; + + // Check the corner case that current_usage_bps drops before the first point. + let (left, right) = if (num_points == 0) { + (&Point { x: 0, y: 0 }, &Point { x: BASIS_POINT_DENOMINATION, y: BASIS_POINT_DENOMINATION }) + } else if (current_usage_bps < vector::borrow(points, 0).x) { + (&Point { x: 0, y: 0 }, vector::borrow(points, 0)) + } else if (vector::borrow(points, num_points - 1).x <= current_usage_bps) { + (vector::borrow(points, num_points - 1), &Point { x: BASIS_POINT_DENOMINATION, y: BASIS_POINT_DENOMINATION }) + } else { + let (i, j) = (0, num_points - 2); + while ({ + spec { + invariant i <= j; + invariant j < num_points - 1; + invariant points[i].x <= current_usage_bps; + invariant current_usage_bps < points[j + 1].x; + }; + i < j + }) { + let mid = j - (j - i) / 2; + if (current_usage_bps < vector::borrow(points, mid).x) { + spec { + // j is strictly decreasing. + assert mid - 1 < j; + }; + j = mid - 1; + } else { + spec { + // i is strictly increasing. + assert i < mid; + }; + i = mid; + }; + }; + (vector::borrow(points, i), vector::borrow(points, i + 1)) + }; + let y_interpolated = interpolate(left.x, right.x, left.y, right.y, current_usage_bps); + interpolate(0, BASIS_POINT_DENOMINATION, curve.min_gas, curve.max_gas, y_interpolated) + } + + // Interpolates y for x on the line between (x0, y0) and (x1, y1). + fun interpolate(x0: u64, x1: u64, y0: u64, y1: u64, x: u64): u64 { + y0 + (x - x0) * (y1 - y0) / (x1 - x0) + } + + fun calculate_read_gas(config: &UsageGasConfig, usage: u64): u64 { + calculate_gas(config.target_usage, usage, &config.read_curve) + } + + fun calculate_create_gas(config: &UsageGasConfig, usage: u64): u64 { + calculate_gas(config.target_usage, usage, &config.create_curve) + } + + fun calculate_write_gas(config: &UsageGasConfig, usage: u64): u64 { + calculate_gas(config.target_usage, usage, &config.write_curve) + } + + public(friend) fun on_reconfig() acquires StorageGas, StorageGasConfig { + assert!( + exists(@aptos_framework), + error::not_found(ESTORAGE_GAS_CONFIG) + ); + assert!( + exists(@aptos_framework), + error::not_found(ESTORAGE_GAS) + ); + let (items, bytes) = state_storage::current_items_and_bytes(); + let gas_config = borrow_global(@aptos_framework); + let gas = borrow_global_mut(@aptos_framework); + gas.per_item_read = calculate_read_gas(&gas_config.item_config, items); + gas.per_item_create = calculate_create_gas(&gas_config.item_config, items); + gas.per_item_write = calculate_write_gas(&gas_config.item_config, items); + gas.per_byte_read = calculate_read_gas(&gas_config.byte_config, bytes); + gas.per_byte_create = calculate_create_gas(&gas_config.byte_config, bytes); + gas.per_byte_write = calculate_write_gas(&gas_config.byte_config, bytes); + } + + // TODO: reactivate this test after fixing assertions + //#[test(framework = @aptos_framework)] + #[test_only] + fun test_initialize_and_reconfig(framework: signer) acquires StorageGas, StorageGasConfig { + state_storage::initialize(&framework); + initialize(&framework); + on_reconfig(); + let gas_parameter = borrow_global(@aptos_framework); + assert!(gas_parameter.per_item_read == 10, 0); + assert!(gas_parameter.per_item_create == 10, 0); + assert!(gas_parameter.per_item_write == 10, 0); + assert!(gas_parameter.per_byte_read == 1, 0); + assert!(gas_parameter.per_byte_create == 1, 0); + assert!(gas_parameter.per_byte_write == 1, 0); + } + + #[test] + fun test_curve() { + let constant_curve = new_gas_curve(5, 5, vector[]); + let linear_curve = new_gas_curve(1, 1000, vector[]); + let standard_curve = base_8192_exponential_curve(1, 1000); + let target = BASIS_POINT_DENOMINATION / 2; + while (target < 2 * BASIS_POINT_DENOMINATION) { + let i = 0; + let old_standard_curve_gas = 1; + while (i <= target + 7) { + assert!(calculate_gas(target, i, &constant_curve) == 5, 0); + assert!(calculate_gas(target, i, &linear_curve) == (if (i < target) { 1 + 999 * (i * BASIS_POINT_DENOMINATION / target) / BASIS_POINT_DENOMINATION } else { 1000 }), 0); + let new_standard_curve_gas = calculate_gas(target, i, &standard_curve); + assert!(new_standard_curve_gas >= old_standard_curve_gas, 0); + old_standard_curve_gas = new_standard_curve_gas; + i = i + 3; + }; + assert!(old_standard_curve_gas == 1000, 0); + target = target + BASIS_POINT_DENOMINATION; + } + } + + #[test(framework = @aptos_framework)] + fun test_set_storage_gas_config(framework: signer) acquires StorageGas, StorageGasConfig { + state_storage::initialize(&framework); + initialize(&framework); + let item_curve = new_gas_curve(1000, 2000, + vector[new_point(3000, 0), new_point(5000, 5000), new_point(8000, 5000)] + ); + let byte_curve = new_gas_curve(0, 1000, vector::singleton(new_point(5000, 3000))); + let item_usage_config = new_usage_gas_config(100, copy item_curve, copy item_curve, copy item_curve); + let byte_usage_config = new_usage_gas_config(2000, copy byte_curve, copy byte_curve, copy byte_curve); + let storage_gas_config = new_storage_gas_config(item_usage_config, byte_usage_config); + set_config(&framework, storage_gas_config); + { + state_storage::set_for_test(0, 20, 100); + on_reconfig(); + let gas_parameter = borrow_global(@aptos_framework); + assert!(gas_parameter.per_item_read == 1000, 0); + assert!(gas_parameter.per_byte_read == 30, 0); + }; + { + state_storage::set_for_test(0, 40, 800); + on_reconfig(); + let gas_parameter = borrow_global(@aptos_framework); + assert!(gas_parameter.per_item_create == 1250, 0); + assert!(gas_parameter.per_byte_create == 240, 0); + }; + { + state_storage::set_for_test(0, 60, 1200); + on_reconfig(); + let gas_parameter = borrow_global(@aptos_framework); + assert!(gas_parameter.per_item_write == 1500, 0); + assert!(gas_parameter.per_byte_write == 440, 0); + }; + { + state_storage::set_for_test(0, 90, 1800); + on_reconfig(); + let gas_parameter = borrow_global(@aptos_framework); + assert!(gas_parameter.per_item_create == 1750, 0); + assert!(gas_parameter.per_byte_create == 860, 0); + }; + { + // usage overflow case + state_storage::set_for_test(0, 110, 2200); + on_reconfig(); + let gas_parameter = borrow_global(@aptos_framework); + assert!(gas_parameter.per_item_read == 2000, 0); + assert!(gas_parameter.per_byte_read == 1000, 0); + }; + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/system_addresses.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/system_addresses.move new file mode 100644 index 000000000..49b82099a --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/system_addresses.move @@ -0,0 +1,82 @@ +module aptos_framework::system_addresses { + use std::error; + use std::signer; + + /// The address/account did not correspond to the core resource address + const ENOT_CORE_RESOURCE_ADDRESS: u64 = 1; + /// The operation can only be performed by the VM + const EVM: u64 = 2; + /// The address/account did not correspond to the core framework address + const ENOT_APTOS_FRAMEWORK_ADDRESS: u64 = 3; + /// The address is not framework reserved address + const ENOT_FRAMEWORK_RESERVED_ADDRESS: u64 = 4; + + public fun assert_core_resource(account: &signer) { + assert_core_resource_address(signer::address_of(account)) + } + + public fun assert_core_resource_address(addr: address) { + assert!(is_core_resource_address(addr), error::permission_denied(ENOT_CORE_RESOURCE_ADDRESS)) + } + + public fun is_core_resource_address(addr: address): bool { + addr == @core_resources + } + + public fun assert_aptos_framework(account: &signer) { + assert!( + is_aptos_framework_address(signer::address_of(account)), + error::permission_denied(ENOT_APTOS_FRAMEWORK_ADDRESS), + ) + } + + public fun assert_framework_reserved_address(account: &signer) { + assert_framework_reserved(signer::address_of(account)); + } + + public fun assert_framework_reserved(addr: address) { + assert!( + is_framework_reserved_address(addr), + error::permission_denied(ENOT_FRAMEWORK_RESERVED_ADDRESS), + ) + } + + /// Return true if `addr` is 0x0 or under the on chain governance's control. + public fun is_framework_reserved_address(addr: address): bool { + is_aptos_framework_address(addr) || + addr == @0x2 || + addr == @0x3 || + addr == @0x4 || + addr == @0x5 || + addr == @0x6 || + addr == @0x7 || + addr == @0x8 || + addr == @0x9 || + addr == @0xa + } + + /// Return true if `addr` is 0x1. + public fun is_aptos_framework_address(addr: address): bool { + addr == @aptos_framework + } + + /// Assert that the signer has the VM reserved address. + public fun assert_vm(account: &signer) { + assert!(is_vm(account), error::permission_denied(EVM)) + } + + /// Return true if `addr` is a reserved address for the VM to call system modules. + public fun is_vm(account: &signer): bool { + is_vm_address(signer::address_of(account)) + } + + /// Return true if `addr` is a reserved address for the VM to call system modules. + public fun is_vm_address(addr: address): bool { + addr == @vm_reserved + } + + /// Return true if `addr` is either the VM address or an Aptos Framework address. + public fun is_reserved_address(addr: address): bool { + is_aptos_framework_address(addr) || is_vm_address(addr) + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/timestamp.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/timestamp.move new file mode 100644 index 000000000..646ff1a97 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/timestamp.move @@ -0,0 +1,88 @@ +/// This module keeps a global wall clock that stores the current Unix time in microseconds. +/// It interacts with the other modules in the following ways: +/// * genesis: to initialize the timestamp +/// * block: to reach consensus on the global wall clock time +module aptos_framework::timestamp { + use aptos_framework::system_addresses; + use std::error; + + friend aptos_framework::genesis; + + /// A singleton resource holding the current Unix time in microseconds + struct CurrentTimeMicroseconds has key { + microseconds: u64, + } + + /// Conversion factor between seconds and microseconds + const MICRO_CONVERSION_FACTOR: u64 = 1000000; + + /// The blockchain is not in an operating state yet + const ENOT_OPERATING: u64 = 1; + /// An invalid timestamp was provided + const EINVALID_TIMESTAMP: u64 = 2; + + /// Marks that time has started. This can only be called from genesis and with the aptos framework account. + public(friend) fun set_time_has_started(aptos_framework: &signer) { + system_addresses::assert_aptos_framework(aptos_framework); + let timer = CurrentTimeMicroseconds { microseconds: 0 }; + move_to(aptos_framework, timer); + } + + /// Updates the wall clock time by consensus. Requires VM privilege and will be invoked during block prologue. + public fun update_global_time( + account: &signer, + proposer: address, + timestamp: u64 + ) acquires CurrentTimeMicroseconds { + // Can only be invoked by AptosVM signer. + system_addresses::assert_vm(account); + + let global_timer = borrow_global_mut(@aptos_framework); + let now = global_timer.microseconds; + if (proposer == @vm_reserved) { + // NIL block with null address as proposer. Timestamp must be equal. + assert!(now == timestamp, error::invalid_argument(EINVALID_TIMESTAMP)); + } else { + // Normal block. Time must advance + assert!(now < timestamp, error::invalid_argument(EINVALID_TIMESTAMP)); + global_timer.microseconds = timestamp; + }; + } + + #[test_only] + public fun set_time_has_started_for_testing(account: &signer) { + if (!exists(@aptos_framework)) { + set_time_has_started(account); + }; + } + + #[view] + /// Gets the current time in microseconds. + public fun now_microseconds(): u64 acquires CurrentTimeMicroseconds { + borrow_global(@aptos_framework).microseconds + } + + #[view] + /// Gets the current time in seconds. + public fun now_seconds(): u64 acquires CurrentTimeMicroseconds { + now_microseconds() / MICRO_CONVERSION_FACTOR + } + + #[test_only] + public fun update_global_time_for_test(timestamp_microsecs: u64) acquires CurrentTimeMicroseconds { + let global_timer = borrow_global_mut(@aptos_framework); + let now = global_timer.microseconds; + assert!(now < timestamp_microsecs, error::invalid_argument(EINVALID_TIMESTAMP)); + global_timer.microseconds = timestamp_microsecs; + } + + #[test_only] + public fun update_global_time_for_test_secs(timestamp_seconds: u64) acquires CurrentTimeMicroseconds { + update_global_time_for_test(timestamp_seconds * MICRO_CONVERSION_FACTOR); + } + + #[test_only] + public fun fast_forward_seconds(timestamp_seconds: u64) acquires CurrentTimeMicroseconds { + update_global_time_for_test_secs(now_seconds() + timestamp_seconds); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/transaction_context.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/transaction_context.move new file mode 100644 index 000000000..c3bad2537 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/transaction_context.move @@ -0,0 +1,262 @@ +module aptos_framework::transaction_context { + use std::error; + use std::features; + use std::option::Option; + use std::string::String; + + /// Transaction context is only available in the user transaction prologue, execution, or epilogue phases. + const ETRANSACTION_CONTEXT_NOT_AVAILABLE: u64 = 1; + + /// The transaction context extension feature is not enabled. + const ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED: u64 = 2; + + /// A wrapper denoting aptos unique identifer (AUID) + /// for storing an address + struct AUID has drop, store { + unique_address: address + } + + /// Represents the entry function payload. + struct EntryFunctionPayload has copy, drop { + account_address: address, + module_name: String, + function_name: String, + ty_args_names: vector, + args: vector>, + } + + /// Represents the multisig payload. + struct MultisigPayload has copy, drop { + multisig_address: address, + entry_function_payload: Option, + } + + /// Returns the transaction hash of the current transaction. + native fun get_txn_hash(): vector; + + /// Returns the transaction hash of the current transaction. + /// Internally calls the private function `get_txn_hash`. + /// This function is created for to feature gate the `get_txn_hash` function. + public fun get_transaction_hash(): vector { + get_txn_hash() + } + + /// Returns a universally unique identifier (of type address) generated + /// by hashing the transaction hash of this transaction and a sequence number + /// specific to this transaction. This function can be called any + /// number of times inside a single transaction. Each such call increments + /// the sequence number and generates a new unique address. + /// Uses Scheme in types/src/transaction/authenticator.rs for domain separation + /// from other ways of generating unique addresses. + native fun generate_unique_address(): address; + + /// Returns a aptos unique identifier. Internally calls + /// the private function `generate_unique_address`. This function is + /// created for to feature gate the `generate_unique_address` function. + public fun generate_auid_address(): address { + generate_unique_address() + } + + /// Returns the script hash of the current entry function. + public native fun get_script_hash(): vector; + + /// This method runs `generate_unique_address` native function and returns + /// the generated unique address wrapped in the AUID class. + public fun generate_auid(): AUID { + return AUID { + unique_address: generate_unique_address() + } + } + + /// Returns the unique address wrapped in the given AUID struct. + public fun auid_address(auid: &AUID): address { + auid.unique_address + } + + /// Returns the sender's address for the current transaction. + /// This function aborts if called outside of the transaction prologue, execution, or epilogue phases. + public fun sender(): address { + assert!(features::transaction_context_extension_enabled(), error::invalid_state(ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED)); + sender_internal() + } + native fun sender_internal(): address; + + /// Returns the list of the secondary signers for the current transaction. + /// If the current transaction has no secondary signers, this function returns an empty vector. + /// This function aborts if called outside of the transaction prologue, execution, or epilogue phases. + public fun secondary_signers(): vector
{ + assert!(features::transaction_context_extension_enabled(), error::invalid_state(ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED)); + secondary_signers_internal() + } + native fun secondary_signers_internal(): vector
; + + /// Returns the gas payer address for the current transaction. + /// It is either the sender's address if no separate gas fee payer is specified for the current transaction, + /// or the address of the separate gas fee payer if one is specified. + /// This function aborts if called outside of the transaction prologue, execution, or epilogue phases. + public fun gas_payer(): address { + assert!(features::transaction_context_extension_enabled(), error::invalid_state(ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED)); + gas_payer_internal() + } + native fun gas_payer_internal(): address; + + /// Returns the max gas amount in units which is specified for the current transaction. + /// This function aborts if called outside of the transaction prologue, execution, or epilogue phases. + public fun max_gas_amount(): u64 { + assert!(features::transaction_context_extension_enabled(), error::invalid_state(ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED)); + max_gas_amount_internal() + } + native fun max_gas_amount_internal(): u64; + + /// Returns the gas unit price in Octas which is specified for the current transaction. + /// This function aborts if called outside of the transaction prologue, execution, or epilogue phases. + public fun gas_unit_price(): u64 { + assert!(features::transaction_context_extension_enabled(), error::invalid_state(ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED)); + gas_unit_price_internal() + } + native fun gas_unit_price_internal(): u64; + + /// Returns the chain ID specified for the current transaction. + /// This function aborts if called outside of the transaction prologue, execution, or epilogue phases. + public fun chain_id(): u8 { + assert!(features::transaction_context_extension_enabled(), error::invalid_state(ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED)); + chain_id_internal() + } + native fun chain_id_internal(): u8; + + /// Returns the entry function payload if the current transaction has such a payload. Otherwise, return `None`. + /// This function aborts if called outside of the transaction prologue, execution, or epilogue phases. + public fun entry_function_payload(): Option { + assert!(features::transaction_context_extension_enabled(), error::invalid_state(ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED)); + entry_function_payload_internal() + } + native fun entry_function_payload_internal(): Option; + + /// Returns the account address of the entry function payload. + public fun account_address(payload: &EntryFunctionPayload): address { + assert!(features::transaction_context_extension_enabled(), error::invalid_state(ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED)); + payload.account_address + } + + /// Returns the module name of the entry function payload. + public fun module_name(payload: &EntryFunctionPayload): String { + assert!(features::transaction_context_extension_enabled(), error::invalid_state(ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED)); + payload.module_name + } + + /// Returns the function name of the entry function payload. + public fun function_name(payload: &EntryFunctionPayload): String { + assert!(features::transaction_context_extension_enabled(), error::invalid_state(ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED)); + payload.function_name + } + + /// Returns the type arguments names of the entry function payload. + public fun type_arg_names(payload: &EntryFunctionPayload): vector { + assert!(features::transaction_context_extension_enabled(), error::invalid_state(ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED)); + payload.ty_args_names + } + + /// Returns the arguments of the entry function payload. + public fun args(payload: &EntryFunctionPayload): vector> { + assert!(features::transaction_context_extension_enabled(), error::invalid_state(ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED)); + payload.args + } + + /// Returns the multisig payload if the current transaction has such a payload. Otherwise, return `None`. + /// This function aborts if called outside of the transaction prologue, execution, or epilogue phases. + public fun multisig_payload(): Option { + assert!(features::transaction_context_extension_enabled(), error::invalid_state(ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED)); + multisig_payload_internal() + } + native fun multisig_payload_internal(): Option; + + /// Returns the multisig account address of the multisig payload. + public fun multisig_address(payload: &MultisigPayload): address { + assert!(features::transaction_context_extension_enabled(), error::invalid_state(ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED)); + payload.multisig_address + } + + /// Returns the inner entry function payload of the multisig payload. + public fun inner_entry_function_payload(payload: &MultisigPayload): Option { + assert!(features::transaction_context_extension_enabled(), error::invalid_state(ETRANSACTION_CONTEXT_EXTENSION_NOT_ENABLED)); + payload.entry_function_payload + } + + #[test()] + fun test_auid_uniquess() { + use std::vector; + + let auids: vector
= vector
[]; + let i: u64 = 0; + let count: u64 = 50; + while (i < count) { + i = i + 1; + vector::push_back(&mut auids, generate_auid_address()); + }; + i = 0; + while (i < count - 1) { + let j: u64 = i + 1; + while (j < count) { + assert!(*vector::borrow(&auids, i) != *vector::borrow(&auids, j), 0); + j = j + 1; + }; + i = i + 1; + }; + } + + #[test] + #[expected_failure(abort_code=196609, location = Self)] + fun test_call_sender() { + // expected to fail with the error code of `invalid_state(E_TRANSACTION_CONTEXT_NOT_AVAILABLE)` + let _sender = sender(); + } + + #[test] + #[expected_failure(abort_code=196609, location = Self)] + fun test_call_secondary_signers() { + // expected to fail with the error code of `invalid_state(E_TRANSACTION_CONTEXT_NOT_AVAILABLE)` + let _secondary_signers = secondary_signers(); + } + + #[test] + #[expected_failure(abort_code=196609, location = Self)] + fun test_call_gas_payer() { + // expected to fail with the error code of `invalid_state(E_TRANSACTION_CONTEXT_NOT_AVAILABLE)` + let _gas_payer = gas_payer(); + } + + #[test] + #[expected_failure(abort_code=196609, location = Self)] + fun test_call_max_gas_amount() { + // expected to fail with the error code of `invalid_state(E_TRANSACTION_CONTEXT_NOT_AVAILABLE)` + let _max_gas_amount = max_gas_amount(); + } + + #[test] + #[expected_failure(abort_code=196609, location = Self)] + fun test_call_gas_unit_price() { + // expected to fail with the error code of `invalid_state(E_TRANSACTION_CONTEXT_NOT_AVAILABLE)` + let _gas_unit_price = gas_unit_price(); + } + + #[test] + #[expected_failure(abort_code=196609, location = Self)] + fun test_call_chain_id() { + // expected to fail with the error code of `invalid_state(E_TRANSACTION_CONTEXT_NOT_AVAILABLE)` + let _chain_id = chain_id(); + } + + #[test] + #[expected_failure(abort_code=196609, location = Self)] + fun test_call_entry_function_payload() { + // expected to fail with the error code of `invalid_state(E_TRANSACTION_CONTEXT_NOT_AVAILABLE)` + let _entry_fun = entry_function_payload(); + } + + #[test] + #[expected_failure(abort_code=196609, location = Self)] + fun test_call_multisig_payload() { + // expected to fail with the error code of `invalid_state(E_TRANSACTION_CONTEXT_NOT_AVAILABLE)` + let _multisig = multisig_payload(); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/transaction_fee.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/transaction_fee.move new file mode 100644 index 000000000..1a4704e78 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/transaction_fee.move @@ -0,0 +1,575 @@ +/// This module provides an interface to burn or collect and redistribute transaction fees. +module aptos_framework::transaction_fee { + use aptos_framework::coin::{Self, AggregatableCoin, BurnCapability, Coin, MintCapability}; + use aptos_framework::aptos_account; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::stake; + use aptos_framework::fungible_asset::BurnRef; + use aptos_framework::system_addresses; + use std::error; + use std::features; + use std::option::{Self, Option}; + use std::signer; + use aptos_framework::event; + + friend aptos_framework::block; + friend aptos_framework::genesis; + friend aptos_framework::reconfiguration; + friend aptos_framework::transaction_validation; + + /// Gas fees are already being collected and the struct holding + /// information about collected amounts is already published. + const EALREADY_COLLECTING_FEES: u64 = 1; + + /// The burn percentage is out of range [0, 100]. + const EINVALID_BURN_PERCENTAGE: u64 = 3; + + /// No longer supported. + const ENO_LONGER_SUPPORTED: u64 = 4; + + const EFA_GAS_CHARGING_NOT_ENABLED: u64 = 5; + + const EATOMIC_BRIDGE_NOT_ENABLED: u64 = 6; + + const ECOPY_CAPS_SHOT: u64 = 7; + + const ENATIVE_BRIDGE_NOT_ENABLED: u64 = 8; + + /// The one shot copy capabilities call + struct CopyCapabilitiesOneShot has key {} + + /// Stores burn capability to burn the gas fees. + struct AptosCoinCapabilities has key { + burn_cap: BurnCapability, + } + + /// Stores burn capability to burn the gas fees. + struct AptosFABurnCapabilities has key { + burn_ref: BurnRef, + } + + /// Stores mint capability to mint the refunds. + struct AptosCoinMintCapability has key { + mint_cap: MintCapability, + } + + /// Stores information about the block proposer and the amount of fees + /// collected when executing the block. + struct CollectedFeesPerBlock has key { + amount: AggregatableCoin, + proposer: Option
, + burn_percentage: u8, + } + + #[event] + /// Breakdown of fee charge and refund for a transaction. + /// The structure is: + /// + /// - Net charge or refund (not in the statement) + /// - total charge: total_charge_gas_units, matches `gas_used` in the on-chain `TransactionInfo`. + /// This is the sum of the sub-items below. Notice that there's potential precision loss when + /// the conversion between internal and external gas units and between native token and gas + /// units, so it's possible that the numbers don't add up exactly. -- This number is the final + /// charge, while the break down is merely informational. + /// - gas charge for execution (CPU time): `execution_gas_units` + /// - gas charge for IO (storage random access): `io_gas_units` + /// - storage fee charge (storage space): `storage_fee_octas`, to be included in + /// `total_charge_gas_unit`, this number is converted to gas units according to the user + /// specified `gas_unit_price` on the transaction. + /// - storage deletion refund: `storage_fee_refund_octas`, this is not included in `gas_used` or + /// `total_charge_gas_units`, the net charge / refund is calculated by + /// `total_charge_gas_units` * `gas_unit_price` - `storage_fee_refund_octas`. + /// + /// This is meant to emitted as a module event. + struct FeeStatement has drop, store { + /// Total gas charge. + total_charge_gas_units: u64, + /// Execution gas charge. + execution_gas_units: u64, + /// IO gas charge. + io_gas_units: u64, + /// Storage fee charge. + storage_fee_octas: u64, + /// Storage fee refund. + storage_fee_refund_octas: u64, + } + + /// Initializes the resource storing information about gas fees collection and + /// distribution. Should be called by on-chain governance. + public fun initialize_fee_collection_and_distribution(aptos_framework: &signer, burn_percentage: u8) { + system_addresses::assert_aptos_framework(aptos_framework); + assert!( + !exists(@aptos_framework), + error::already_exists(EALREADY_COLLECTING_FEES) + ); + assert!(burn_percentage <= 100, error::out_of_range(EINVALID_BURN_PERCENTAGE)); + + // Make sure stakng module is aware of transaction fees collection. + stake::initialize_validator_fees(aptos_framework); + + // Initially, no fees are collected and the block proposer is not set. + let collected_fees = CollectedFeesPerBlock { + amount: coin::initialize_aggregatable_coin(aptos_framework), + proposer: option::none(), + burn_percentage, + }; + move_to(aptos_framework, collected_fees); + } + + fun is_fees_collection_enabled(): bool { + exists(@aptos_framework) + } + + /// Sets the burn percentage for collected fees to a new value. Should be called by on-chain governance. + public fun upgrade_burn_percentage( + aptos_framework: &signer, + new_burn_percentage: u8 + ) acquires AptosCoinCapabilities, CollectedFeesPerBlock { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(new_burn_percentage <= 100, error::out_of_range(EINVALID_BURN_PERCENTAGE)); + + // Prior to upgrading the burn percentage, make sure to process collected + // fees. Otherwise we would use the new (incorrect) burn_percentage when + // processing fees later! + process_collected_fees(); + + if (is_fees_collection_enabled()) { + // Upgrade has no effect unless fees are being collected. + let burn_percentage = &mut borrow_global_mut(@aptos_framework).burn_percentage; + *burn_percentage = new_burn_percentage + } + } + + /// Registers the proposer of the block for gas fees collection. This function + /// can only be called at the beginning of the block. + public(friend) fun register_proposer_for_fee_collection(proposer_addr: address) acquires CollectedFeesPerBlock { + if (is_fees_collection_enabled()) { + let collected_fees = borrow_global_mut(@aptos_framework); + let _ = option::swap_or_fill(&mut collected_fees.proposer, proposer_addr); + } + } + + /// Burns a specified fraction of the coin. + fun burn_coin_fraction(coin: &mut Coin, burn_percentage: u8) acquires AptosCoinCapabilities { + assert!(burn_percentage <= 100, error::out_of_range(EINVALID_BURN_PERCENTAGE)); + + let collected_amount = coin::value(coin); + spec { + // We assume that `burn_percentage * collected_amount` does not overflow. + assume burn_percentage * collected_amount <= MAX_U64; + }; + let amount_to_burn = (burn_percentage as u64) * collected_amount / 100; + if (amount_to_burn > 0) { + let coin_to_burn = coin::extract(coin, amount_to_burn); + coin::burn( + coin_to_burn, + &borrow_global(@aptos_framework).burn_cap, + ); + } + } + + /// Calculates the fee which should be distributed to the block proposer at the + /// end of an epoch, and records it in the system. This function can only be called + /// at the beginning of the block or during reconfiguration. + public(friend) fun process_collected_fees() acquires AptosCoinCapabilities, CollectedFeesPerBlock { + if (!is_fees_collection_enabled()) { + return + }; + let collected_fees = borrow_global_mut(@aptos_framework); + + // If there are no collected fees, only unset the proposer. See the rationale for + // setting proposer to option::none() below. + if (coin::is_aggregatable_coin_zero(&collected_fees.amount)) { + if (option::is_some(&collected_fees.proposer)) { + let _ = option::extract(&mut collected_fees.proposer); + }; + return + }; + + // Otherwise get the collected fee, and check if it can distributed later. + let coin = coin::drain_aggregatable_coin(&mut collected_fees.amount); + if (option::is_some(&collected_fees.proposer)) { + // Extract the address of proposer here and reset it to option::none(). This + // is particularly useful to avoid any undesired side-effects where coins are + // collected but never distributed or distributed to the wrong account. + // With this design, processing collected fees enforces that all fees will be burnt + // unless the proposer is specified in the block prologue. When we have a governance + // proposal that triggers reconfiguration, we distribute pending fees and burn the + // fee for the proposal. Otherwise, that fee would be leaked to the next block. + let proposer = option::extract(&mut collected_fees.proposer); + + // Since the block can be produced by the VM itself, we have to make sure we catch + // this case. + if (proposer == @vm_reserved) { + burn_coin_fraction(&mut coin, 100); + coin::destroy_zero(coin); + return + }; + + burn_coin_fraction(&mut coin, collected_fees.burn_percentage); + stake::add_transaction_fee(proposer, coin); + return + }; + + // If checks did not pass, simply burn all collected coins and return none. + burn_coin_fraction(&mut coin, 100); + coin::destroy_zero(coin) + } + + /// Burns a specified amount of AptosCoin from an address. + /// + /// @param core_resource The signer representing the core resource account. + /// @param account The address from which to burn AptosCoin. + /// @param fee The amount of AptosCoin to burn. + /// @abort If the burn capability is not available. + public fun burn_from(aptos_framework: &signer, account: address, fee: u64) acquires AptosFABurnCapabilities, AptosCoinCapabilities { + system_addresses::assert_aptos_framework(aptos_framework); + if (exists(@aptos_framework)) { + let burn_ref = &borrow_global(@aptos_framework).burn_ref; + aptos_account::burn_from_fungible_store(burn_ref, account, fee); + } else { + let burn_cap = &borrow_global(@aptos_framework).burn_cap; + if (features::operations_default_to_fa_apt_store_enabled()) { + let (burn_ref, burn_receipt) = coin::get_paired_burn_ref(burn_cap); + aptos_account::burn_from_fungible_store(&burn_ref, account, fee); + coin::return_paired_burn_ref(burn_ref, burn_receipt); + } else { + coin::burn_from( + account, + fee, + burn_cap, + ); + }; + }; + } + + /// Burn transaction fees in epilogue. + public(friend) fun burn_fee(account: address, fee: u64) acquires AptosFABurnCapabilities, AptosCoinCapabilities { + if (exists(@aptos_framework)) { + let burn_ref = &borrow_global(@aptos_framework).burn_ref; + aptos_account::burn_from_fungible_store(burn_ref, account, fee); + } else { + let burn_cap = &borrow_global(@aptos_framework).burn_cap; + if (features::operations_default_to_fa_apt_store_enabled()) { + let (burn_ref, burn_receipt) = coin::get_paired_burn_ref(burn_cap); + aptos_account::burn_from_fungible_store(&burn_ref, account, fee); + coin::return_paired_burn_ref(burn_ref, burn_receipt); + } else { + coin::burn_from( + account, + fee, + burn_cap, + ); + }; + }; + } + + /// Mint refund in epilogue. + public(friend) fun mint_and_refund(account: address, refund: u64) acquires AptosCoinMintCapability { + let mint_cap = &borrow_global(@aptos_framework).mint_cap; + let refund_coin = coin::mint(refund, mint_cap); + coin::force_deposit(account, refund_coin); + } + + /// Collect transaction fees in epilogue. + public(friend) fun collect_fee(account: address, fee: u64) acquires CollectedFeesPerBlock { + let collected_fees = borrow_global_mut(@aptos_framework); + + // Here, we are always optimistic and always collect fees. If the proposer is not set, + // or we cannot redistribute fees later for some reason (e.g. account cannot receive AptoCoin) + // we burn them all at once. This way we avoid having a check for every transaction epilogue. + let collected_amount = &mut collected_fees.amount; + coin::collect_into_aggregatable_coin(account, fee, collected_amount); + } + + /// Only called during genesis. + public(friend) fun store_aptos_coin_burn_cap(aptos_framework: &signer, burn_cap: BurnCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + + if (features::operations_default_to_fa_apt_store_enabled()) { + let burn_ref = coin::convert_and_take_paired_burn_ref(burn_cap); + move_to(aptos_framework, AptosFABurnCapabilities { burn_ref }); + } else { + move_to(aptos_framework, AptosCoinCapabilities { burn_cap }) + } + } + + public entry fun convert_to_aptos_fa_burn_ref(aptos_framework: &signer) acquires AptosCoinCapabilities { + assert!(features::operations_default_to_fa_apt_store_enabled(), EFA_GAS_CHARGING_NOT_ENABLED); + system_addresses::assert_aptos_framework(aptos_framework); + let AptosCoinCapabilities { + burn_cap, + } = move_from(signer::address_of(aptos_framework)); + let burn_ref = coin::convert_and_take_paired_burn_ref(burn_cap); + move_to(aptos_framework, AptosFABurnCapabilities { burn_ref }); + } + + /// Only called during genesis. + public(friend) fun store_aptos_coin_mint_cap(aptos_framework: &signer, mint_cap: MintCapability) { + system_addresses::assert_aptos_framework(aptos_framework); + move_to(aptos_framework, AptosCoinMintCapability { mint_cap }) + } + + /// Copy Mint and Burn capabilities over to bridge + /// Can only be called once after which it will assert + public fun copy_capabilities_for_bridge(aptos_framework: &signer) : (MintCapability, BurnCapability) + acquires AptosCoinCapabilities, AptosCoinMintCapability { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(features::abort_atomic_bridge_enabled(), EATOMIC_BRIDGE_NOT_ENABLED); + assert!(!exists(@aptos_framework), ECOPY_CAPS_SHOT); + move_to(aptos_framework, CopyCapabilitiesOneShot{}); + ( + borrow_global(@aptos_framework).mint_cap, + borrow_global(@aptos_framework).burn_cap + ) + } + + /// Copy Mint and Burn capabilities over to bridge + /// Can only be called once after which it will assert + public fun copy_capabilities_for_native_bridge(aptos_framework: &signer) : (MintCapability, BurnCapability) + acquires AptosCoinCapabilities, AptosCoinMintCapability { + system_addresses::assert_aptos_framework(aptos_framework); + assert!(features::abort_native_bridge_enabled(), ENATIVE_BRIDGE_NOT_ENABLED); + assert!(!exists(@aptos_framework), ECOPY_CAPS_SHOT); + move_to(aptos_framework, CopyCapabilitiesOneShot{}); + ( + borrow_global(@aptos_framework).mint_cap, + borrow_global(@aptos_framework).burn_cap + ) + } + + #[deprecated] + public fun initialize_storage_refund(_: &signer) { + abort error::not_implemented(ENO_LONGER_SUPPORTED) + } + + // Called by the VM after epilogue. + fun emit_fee_statement(fee_statement: FeeStatement) { + event::emit(fee_statement) + } + + #[test_only] + use aptos_framework::aggregator_factory; + #[test_only] + use aptos_framework::object; + + #[test(aptos_framework = @aptos_framework)] + fun test_initialize_fee_collection_and_distribution(aptos_framework: signer) acquires CollectedFeesPerBlock { + aggregator_factory::initialize_aggregator_factory_for_test(&aptos_framework); + initialize_fee_collection_and_distribution(&aptos_framework, 25); + + // Check struct has been published. + assert!(exists(@aptos_framework), 0); + + // Check that initial balance is 0 and there is no proposer set. + let collected_fees = borrow_global(@aptos_framework); + assert!(coin::is_aggregatable_coin_zero(&collected_fees.amount), 0); + assert!(option::is_none(&collected_fees.proposer), 0); + assert!(collected_fees.burn_percentage == 25, 0); + } + + #[test(aptos_framework = @aptos_framework)] + fun test_burn_fraction_calculation(aptos_framework: signer) acquires AptosCoinCapabilities { + use aptos_framework::aptos_coin; + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(&aptos_framework); + store_aptos_coin_burn_cap(&aptos_framework, burn_cap); + + let c1 = coin::mint(100, &mint_cap); + assert!(*option::borrow(&coin::supply()) == 100, 0); + + // Burning 25%. + burn_coin_fraction(&mut c1, 25); + assert!(coin::value(&c1) == 75, 0); + assert!(*option::borrow(&coin::supply()) == 75, 0); + + // Burning 0%. + burn_coin_fraction(&mut c1, 0); + assert!(coin::value(&c1) == 75, 0); + assert!(*option::borrow(&coin::supply()) == 75, 0); + + // Burning remaining 100%. + burn_coin_fraction(&mut c1, 100); + assert!(coin::value(&c1) == 0, 0); + assert!(*option::borrow(&coin::supply()) == 0, 0); + + coin::destroy_zero(c1); + let c2 = coin::mint(10, &mint_cap); + assert!(*option::borrow(&coin::supply()) == 10, 0); + + burn_coin_fraction(&mut c2, 5); + assert!(coin::value(&c2) == 10, 0); + assert!(*option::borrow(&coin::supply()) == 10, 0); + + burn_coin_fraction(&mut c2, 100); + coin::destroy_zero(c2); + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + } + + #[test(aptos_framework = @aptos_framework, alice = @0xa11ce, bob = @0xb0b, carol = @0xca101)] + fun test_fees_distribution( + aptos_framework: signer, + alice: signer, + bob: signer, + carol: signer, + ) acquires AptosCoinCapabilities, CollectedFeesPerBlock { + use std::signer; + use aptos_framework::aptos_account; + use aptos_framework::aptos_coin; + + // Initialization. + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(&aptos_framework); + store_aptos_coin_burn_cap(&aptos_framework, burn_cap); + initialize_fee_collection_and_distribution(&aptos_framework, 10); + + // Create dummy accounts. + let alice_addr = signer::address_of(&alice); + let bob_addr = signer::address_of(&bob); + let carol_addr = signer::address_of(&carol); + aptos_account::create_account(alice_addr); + aptos_account::create_account(bob_addr); + aptos_account::create_account(carol_addr); + assert!(object::object_address(&coin::ensure_paired_metadata()) == @aptos_fungible_asset, 0); + coin::deposit(alice_addr, coin::mint(10000, &mint_cap)); + coin::deposit(bob_addr, coin::mint(10000, &mint_cap)); + coin::deposit(carol_addr, coin::mint(10000, &mint_cap)); + assert!(*option::borrow(&coin::supply()) == 30000, 0); + + // Block 1 starts. + process_collected_fees(); + register_proposer_for_fee_collection(alice_addr); + + // Check that there was no fees distribution in the first block. + let collected_fees = borrow_global(@aptos_framework); + assert!(coin::is_aggregatable_coin_zero(&collected_fees.amount), 0); + assert!(*option::borrow(&collected_fees.proposer) == alice_addr, 0); + assert!(*option::borrow(&coin::supply()) == 30000, 0); + + // Simulate transaction fee collection - here we simply collect some fees from Bob. + collect_fee(bob_addr, 100); + collect_fee(bob_addr, 500); + collect_fee(bob_addr, 400); + + // Now Bob must have 1000 less in his account. Alice and Carol have the same amounts. + assert!(coin::balance(alice_addr) == 10000, 0); + assert!(coin::balance(bob_addr) == 9000, 0); + assert!(coin::balance(carol_addr) == 10000, 0); + + // Block 2 starts. + process_collected_fees(); + register_proposer_for_fee_collection(bob_addr); + + // Collected fees from Bob must have been assigned to Alice. + assert!(stake::get_validator_fee(alice_addr) == 900, 0); + assert!(coin::balance(alice_addr) == 10000, 0); + assert!(coin::balance(bob_addr) == 9000, 0); + assert!(coin::balance(carol_addr) == 10000, 0); + + // Also, aggregator coin is drained and total supply is slightly changed (10% of 1000 is burnt). + let collected_fees = borrow_global(@aptos_framework); + assert!(coin::is_aggregatable_coin_zero(&collected_fees.amount), 0); + assert!(*option::borrow(&collected_fees.proposer) == bob_addr, 0); + assert!(*option::borrow(&coin::supply()) == 29900, 0); + + // Simulate transaction fee collection one more time. + collect_fee(bob_addr, 5000); + collect_fee(bob_addr, 4000); + + assert!(coin::balance(alice_addr) == 10000, 0); + assert!(coin::balance(bob_addr) == 0, 0); + assert!(coin::balance(carol_addr) == 10000, 0); + + // Block 3 starts. + process_collected_fees(); + register_proposer_for_fee_collection(carol_addr); + + // Collected fees should have been assigned to Bob because he was the peoposer. + assert!(stake::get_validator_fee(alice_addr) == 900, 0); + assert!(coin::balance(alice_addr) == 10000, 0); + assert!(stake::get_validator_fee(bob_addr) == 8100, 0); + assert!(coin::balance(bob_addr) == 0, 0); + assert!(coin::balance(carol_addr) == 10000, 0); + + // Again, aggregator coin is drained and total supply is changed by 10% of 9000. + let collected_fees = borrow_global(@aptos_framework); + assert!(coin::is_aggregatable_coin_zero(&collected_fees.amount), 0); + assert!(*option::borrow(&collected_fees.proposer) == carol_addr, 0); + assert!(*option::borrow(&coin::supply()) == 29000, 0); + + // Simulate transaction fee collection one last time. + collect_fee(alice_addr, 1000); + collect_fee(alice_addr, 1000); + + // Block 4 starts. + process_collected_fees(); + register_proposer_for_fee_collection(alice_addr); + + // Check that 2000 was collected from Alice. + assert!(coin::balance(alice_addr) == 8000, 0); + assert!(coin::balance(bob_addr) == 0, 0); + + // Carol must have some fees assigned now. + let collected_fees = borrow_global(@aptos_framework); + assert!(stake::get_validator_fee(carol_addr) == 1800, 0); + assert!(coin::is_aggregatable_coin_zero(&collected_fees.amount), 0); + assert!(*option::borrow(&collected_fees.proposer) == alice_addr, 0); + assert!(*option::borrow(&coin::supply()) == 28800, 0); + + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + } + + #[test_only] + fun setup_coin_caps(aptos_framework: &signer) { + use aptos_framework::aptos_coin; + let (burn_cap, mint_cap) = aptos_coin::initialize_for_test(aptos_framework); + store_aptos_coin_burn_cap(aptos_framework, burn_cap); + store_aptos_coin_mint_cap(aptos_framework, mint_cap); + } + + #[test_only] + fun setup_atomic_bridge(aptos_framework: &signer) { + features::change_feature_flags_for_testing( + aptos_framework, + vector[features::get_atomic_bridge_feature()], + vector[] + ); + } + + #[test(aptos_framework = @aptos_framework)] + fun test_copy_capabilities(aptos_framework: &signer) acquires AptosCoinCapabilities, AptosCoinMintCapability { + setup_coin_caps(aptos_framework); + setup_atomic_bridge(aptos_framework); + + let (mint_cap, burn_cap) = copy_capabilities_for_bridge(aptos_framework); + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = EATOMIC_BRIDGE_NOT_ENABLED, location = Self)] + fun test_copy_capabilities_no_bridge(aptos_framework: &signer) acquires AptosCoinCapabilities, AptosCoinMintCapability { + setup_coin_caps(aptos_framework); + features::change_feature_flags_for_testing( + aptos_framework, + vector[], + vector[features::get_atomic_bridge_feature()], + ); + let (mint_cap, burn_cap) = copy_capabilities_for_bridge(aptos_framework); + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + } + + #[test(aptos_framework = @aptos_framework)] + #[expected_failure(abort_code = ECOPY_CAPS_SHOT, location = Self)] + fun test_copy_capabilities_one_too_many_shots(aptos_framework: &signer) acquires AptosCoinCapabilities, AptosCoinMintCapability { + setup_coin_caps(aptos_framework); + setup_atomic_bridge(aptos_framework); + let (mint_cap, burn_cap) = copy_capabilities_for_bridge(aptos_framework); + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + let (mint_cap, burn_cap) = copy_capabilities_for_bridge(aptos_framework); + coin::destroy_burn_cap(burn_cap); + coin::destroy_mint_cap(mint_cap); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/transaction_validation.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/transaction_validation.move new file mode 100644 index 000000000..3a4d48040 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/transaction_validation.move @@ -0,0 +1,339 @@ +module aptos_framework::transaction_validation { + use std::bcs; + use std::error; + use std::features; + use std::signer; + use std::vector; + + use aptos_framework::account; + use aptos_framework::aptos_account; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::chain_id; + use aptos_framework::coin; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + use aptos_framework::transaction_fee; + use aptos_framework::governed_gas_pool; + + friend aptos_framework::genesis; + + /// This holds information that will be picked up by the VM to call the + /// correct chain-specific prologue and epilogue functions + struct TransactionValidation has key { + module_addr: address, + module_name: vector, + script_prologue_name: vector, + // module_prologue_name is deprecated and not used. + module_prologue_name: vector, + multi_agent_prologue_name: vector, + user_epilogue_name: vector, + } + + /// MSB is used to indicate a gas payer tx + const MAX_U64: u128 = 18446744073709551615; + + /// Transaction exceeded its allocated max gas + const EOUT_OF_GAS: u64 = 6; + + /// Prologue errors. These are separated out from the other errors in this + /// module since they are mapped separately to major VM statuses, and are + /// important to the semantics of the system. + const PROLOGUE_EINVALID_ACCOUNT_AUTH_KEY: u64 = 1001; + const PROLOGUE_ESEQUENCE_NUMBER_TOO_OLD: u64 = 1002; + const PROLOGUE_ESEQUENCE_NUMBER_TOO_NEW: u64 = 1003; + const PROLOGUE_EACCOUNT_DOES_NOT_EXIST: u64 = 1004; + const PROLOGUE_ECANT_PAY_GAS_DEPOSIT: u64 = 1005; + const PROLOGUE_ETRANSACTION_EXPIRED: u64 = 1006; + const PROLOGUE_EBAD_CHAIN_ID: u64 = 1007; + const PROLOGUE_ESEQUENCE_NUMBER_TOO_BIG: u64 = 1008; + const PROLOGUE_ESECONDARY_KEYS_ADDRESSES_COUNT_MISMATCH: u64 = 1009; + const PROLOGUE_EFEE_PAYER_NOT_ENABLED: u64 = 1010; + + /// Only called during genesis to initialize system resources for this module. + public(friend) fun initialize( + aptos_framework: &signer, + script_prologue_name: vector, + // module_prologue_name is deprecated and not used. + module_prologue_name: vector, + multi_agent_prologue_name: vector, + user_epilogue_name: vector, + ) { + system_addresses::assert_aptos_framework(aptos_framework); + + move_to(aptos_framework, TransactionValidation { + module_addr: @aptos_framework, + module_name: b"transaction_validation", + script_prologue_name, + // module_prologue_name is deprecated and not used. + module_prologue_name, + multi_agent_prologue_name, + user_epilogue_name, + }); + } + + fun prologue_common( + sender: signer, + gas_payer: address, + txn_sequence_number: u64, + txn_authentication_key: vector, + txn_gas_price: u64, + txn_max_gas_units: u64, + txn_expiration_time: u64, + chain_id: u8, + ) { + assert!( + timestamp::now_seconds() < txn_expiration_time, + error::invalid_argument(PROLOGUE_ETRANSACTION_EXPIRED), + ); + assert!(chain_id::get() == chain_id, error::invalid_argument(PROLOGUE_EBAD_CHAIN_ID)); + + let transaction_sender = signer::address_of(&sender); + + if ( + transaction_sender == gas_payer + || account::exists_at(transaction_sender) + || !features::sponsored_automatic_account_creation_enabled() + || txn_sequence_number > 0 + ) { + assert!(account::exists_at(transaction_sender), error::invalid_argument(PROLOGUE_EACCOUNT_DOES_NOT_EXIST)); + assert!( + txn_authentication_key == account::get_authentication_key(transaction_sender), + error::invalid_argument(PROLOGUE_EINVALID_ACCOUNT_AUTH_KEY), + ); + + let account_sequence_number = account::get_sequence_number(transaction_sender); + assert!( + txn_sequence_number < (1u64 << 63), + error::out_of_range(PROLOGUE_ESEQUENCE_NUMBER_TOO_BIG) + ); + + assert!( + txn_sequence_number >= account_sequence_number, + error::invalid_argument(PROLOGUE_ESEQUENCE_NUMBER_TOO_OLD) + ); + + assert!( + txn_sequence_number == account_sequence_number, + error::invalid_argument(PROLOGUE_ESEQUENCE_NUMBER_TOO_NEW) + ); + } else { + // In this case, the transaction is sponsored and the account does not exist, so ensure + // the default values match. + assert!( + txn_sequence_number == 0, + error::invalid_argument(PROLOGUE_ESEQUENCE_NUMBER_TOO_NEW) + ); + + assert!( + txn_authentication_key == bcs::to_bytes(&transaction_sender), + error::invalid_argument(PROLOGUE_EINVALID_ACCOUNT_AUTH_KEY), + ); + }; + + let max_transaction_fee = txn_gas_price * txn_max_gas_units; + + if (features::operations_default_to_fa_apt_store_enabled()) { + assert!( + aptos_account::is_fungible_balance_at_least(gas_payer, max_transaction_fee), + error::invalid_argument(PROLOGUE_ECANT_PAY_GAS_DEPOSIT) + ); + } else { + assert!( + coin::is_balance_at_least(gas_payer, max_transaction_fee), + error::invalid_argument(PROLOGUE_ECANT_PAY_GAS_DEPOSIT) + ); + } + } + + fun script_prologue( + sender: signer, + txn_sequence_number: u64, + txn_public_key: vector, + txn_gas_price: u64, + txn_max_gas_units: u64, + txn_expiration_time: u64, + chain_id: u8, + _script_hash: vector, + ) { + let gas_payer = signer::address_of(&sender); + prologue_common( + sender, + gas_payer, + txn_sequence_number, + txn_public_key, + txn_gas_price, + txn_max_gas_units, + txn_expiration_time, + chain_id + ) + } + + fun multi_agent_script_prologue( + sender: signer, + txn_sequence_number: u64, + txn_sender_public_key: vector, + secondary_signer_addresses: vector
, + secondary_signer_public_key_hashes: vector>, + txn_gas_price: u64, + txn_max_gas_units: u64, + txn_expiration_time: u64, + chain_id: u8, + ) { + let sender_addr = signer::address_of(&sender); + prologue_common( + sender, + sender_addr, + txn_sequence_number, + txn_sender_public_key, + txn_gas_price, + txn_max_gas_units, + txn_expiration_time, + chain_id, + ); + multi_agent_common_prologue(secondary_signer_addresses, secondary_signer_public_key_hashes); + } + + fun multi_agent_common_prologue( + secondary_signer_addresses: vector
, + secondary_signer_public_key_hashes: vector>, + ) { + let num_secondary_signers = vector::length(&secondary_signer_addresses); + assert!( + vector::length(&secondary_signer_public_key_hashes) == num_secondary_signers, + error::invalid_argument(PROLOGUE_ESECONDARY_KEYS_ADDRESSES_COUNT_MISMATCH), + ); + + let i = 0; + while ({ + spec { + invariant i <= num_secondary_signers; + invariant forall j in 0..i: + account::exists_at(secondary_signer_addresses[j]) + && secondary_signer_public_key_hashes[j] + == account::get_authentication_key(secondary_signer_addresses[j]); + }; + (i < num_secondary_signers) + }) { + let secondary_address = *vector::borrow(&secondary_signer_addresses, i); + assert!(account::exists_at(secondary_address), error::invalid_argument(PROLOGUE_EACCOUNT_DOES_NOT_EXIST)); + + let signer_public_key_hash = *vector::borrow(&secondary_signer_public_key_hashes, i); + assert!( + signer_public_key_hash == account::get_authentication_key(secondary_address), + error::invalid_argument(PROLOGUE_EINVALID_ACCOUNT_AUTH_KEY), + ); + i = i + 1; + } + } + + fun fee_payer_script_prologue( + sender: signer, + txn_sequence_number: u64, + txn_sender_public_key: vector, + secondary_signer_addresses: vector
, + secondary_signer_public_key_hashes: vector>, + fee_payer_address: address, + fee_payer_public_key_hash: vector, + txn_gas_price: u64, + txn_max_gas_units: u64, + txn_expiration_time: u64, + chain_id: u8, + ) { + assert!(features::fee_payer_enabled(), error::invalid_state(PROLOGUE_EFEE_PAYER_NOT_ENABLED)); + prologue_common( + sender, + fee_payer_address, + txn_sequence_number, + txn_sender_public_key, + txn_gas_price, + txn_max_gas_units, + txn_expiration_time, + chain_id, + ); + multi_agent_common_prologue(secondary_signer_addresses, secondary_signer_public_key_hashes); + assert!( + fee_payer_public_key_hash == account::get_authentication_key(fee_payer_address), + error::invalid_argument(PROLOGUE_EINVALID_ACCOUNT_AUTH_KEY), + ); + } + + /// Epilogue function is run after a transaction is successfully executed. + /// Called by the Adapter + fun epilogue( + account: signer, + storage_fee_refunded: u64, + txn_gas_price: u64, + txn_max_gas_units: u64, + gas_units_remaining: u64 + ) { + let addr = signer::address_of(&account); + epilogue_gas_payer(account, addr, storage_fee_refunded, txn_gas_price, txn_max_gas_units, gas_units_remaining); + } + + /// Epilogue function with explicit gas payer specified, is run after a transaction is successfully executed. + /// Called by the Adapter + fun epilogue_gas_payer( + account: signer, + gas_payer: address, + storage_fee_refunded: u64, + txn_gas_price: u64, + txn_max_gas_units: u64, + gas_units_remaining: u64 + ) { + assert!(txn_max_gas_units >= gas_units_remaining, error::invalid_argument(EOUT_OF_GAS)); + let gas_used = txn_max_gas_units - gas_units_remaining; + + assert!( + (txn_gas_price as u128) * (gas_used as u128) <= MAX_U64, + error::out_of_range(EOUT_OF_GAS) + ); + let transaction_fee_amount = txn_gas_price * gas_used; + + // it's important to maintain the error code consistent with vm + // to do failed transaction cleanup. + if (features::operations_default_to_fa_apt_store_enabled()) { + assert!( + aptos_account::is_fungible_balance_at_least(gas_payer, transaction_fee_amount), + error::out_of_range(PROLOGUE_ECANT_PAY_GAS_DEPOSIT), + ); + } else { + assert!( + coin::is_balance_at_least(gas_payer, transaction_fee_amount), + error::out_of_range(PROLOGUE_ECANT_PAY_GAS_DEPOSIT), + ); + }; + + let amount_to_burn = if (features::collect_and_distribute_gas_fees()) { + // TODO(gas): We might want to distinguish the refundable part of the charge and burn it or track + // it separately, so that we don't increase the total supply by refunding. + + // If transaction fees are redistributed to validators, collect them here for + // later redistribution. + transaction_fee::collect_fee(gas_payer, transaction_fee_amount); + 0 + } else { + // Otherwise, just burn the fee. + // TODO: this branch should be removed completely when transaction fee collection + // is tested and is fully proven to work well. + transaction_fee_amount + }; + + if (amount_to_burn > storage_fee_refunded) { + let burn_amount = amount_to_burn - storage_fee_refunded; + if (features::governed_gas_pool_enabled()) { + governed_gas_pool::deposit_gas_fee_v2(gas_payer, burn_amount); + } else { + transaction_fee::burn_fee(gas_payer, burn_amount); + } + } else if (amount_to_burn < storage_fee_refunded) { + let mint_amount = storage_fee_refunded - amount_to_burn; + if (!features::governed_gas_pool_enabled()) { + transaction_fee::mint_and_refund(gas_payer, mint_amount); + } + }; + + // Increment sequence number + let addr = signer::address_of(&account); + account::increment_sequence_number(addr); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/util.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/util.move new file mode 100644 index 000000000..332afa299 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/util.move @@ -0,0 +1,16 @@ +/// Utility functions used by the framework modules. +module aptos_framework::util { + friend aptos_framework::code; + friend aptos_framework::gas_schedule; + + /// Native function to deserialize a type T. + /// + /// Note that this function does not put any constraint on `T`. If code uses this function to + /// deserialized a linear value, its their responsibility that the data they deserialize is + /// owned. + public(friend) native fun from_bytes(bytes: vector): T; + + public fun address_from_bytes(bytes: vector): address { + from_bytes(bytes) + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/validator_consensus_info.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/validator_consensus_info.move new file mode 100644 index 000000000..3a2abdd0b --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/validator_consensus_info.move @@ -0,0 +1,42 @@ +/// Common type: `ValidatorConsensusInfo`. +module aptos_framework::validator_consensus_info { + /// Information about a validator that participates consensus. + struct ValidatorConsensusInfo has copy, drop, store { + addr: address, + pk_bytes: vector, + voting_power: u64, + } + + /// Create a default `ValidatorConsensusInfo` object. Value may be invalid. Only for place holding prupose. + public fun default(): ValidatorConsensusInfo { + ValidatorConsensusInfo { + addr: @vm, + pk_bytes: vector[], + voting_power: 0, + } + } + + /// Create a `ValidatorConsensusInfo` object. + public fun new(addr: address, pk_bytes: vector, voting_power: u64): ValidatorConsensusInfo { + ValidatorConsensusInfo { + addr, + pk_bytes, + voting_power, + } + } + + /// Get `ValidatorConsensusInfo.addr`. + public fun get_addr(vci: &ValidatorConsensusInfo): address { + vci.addr + } + + /// Get `ValidatorConsensusInfo.pk_bytes`. + public fun get_pk_bytes(vci: &ValidatorConsensusInfo): vector { + vci.pk_bytes + } + + /// Get `ValidatorConsensusInfo.voting_power`. + public fun get_voting_power(vci: &ValidatorConsensusInfo): u64 { + vci.voting_power + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/version.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/version.move new file mode 100644 index 000000000..fa90eb44e --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/version.move @@ -0,0 +1,115 @@ +/// Maintains the version number for the blockchain. +module aptos_framework::version { + use std::error; + use std::signer; + use aptos_framework::chain_status; + use aptos_framework::config_buffer; + + use aptos_framework::reconfiguration; + use aptos_framework::system_addresses; + + friend aptos_framework::genesis; + friend aptos_framework::reconfiguration_with_dkg; + + struct Version has drop, key, store { + major: u64, + } + + struct SetVersionCapability has key {} + + /// Specified major version number must be greater than current version number. + const EINVALID_MAJOR_VERSION_NUMBER: u64 = 1; + /// Account is not authorized to make this change. + const ENOT_AUTHORIZED: u64 = 2; + + /// Only called during genesis. + /// Publishes the Version config. + public(friend) fun initialize(aptos_framework: &signer, initial_version: u64) { + system_addresses::assert_aptos_framework(aptos_framework); + + move_to(aptos_framework, Version { major: initial_version }); + // Give aptos framework account capability to call set version. This allows on chain governance to do it through + // control of the aptos framework account. + move_to(aptos_framework, SetVersionCapability {}); + } + + /// Deprecated by `set_for_next_epoch()`. + /// + /// WARNING: calling this while randomness is enabled will trigger a new epoch without randomness! + /// + /// TODO: update all the tests that reference this function, then disable this function. + public entry fun set_version(account: &signer, major: u64) acquires Version { + assert!(exists(signer::address_of(account)), error::permission_denied(ENOT_AUTHORIZED)); + chain_status::assert_genesis(); + + let old_major = borrow_global(@aptos_framework).major; + assert!(old_major < major, error::invalid_argument(EINVALID_MAJOR_VERSION_NUMBER)); + + let config = borrow_global_mut(@aptos_framework); + config.major = major; + + // Need to trigger reconfiguration so validator nodes can sync on the updated version. + reconfiguration::reconfigure(); + } + + /// Used in on-chain governances to update the major version for the next epoch. + /// Example usage: + /// - `aptos_framework::version::set_for_next_epoch(&framework_signer, new_version);` + /// - `aptos_framework::aptos_governance::reconfigure(&framework_signer);` + public entry fun set_for_next_epoch(account: &signer, major: u64) acquires Version { + assert!(exists(signer::address_of(account)), error::permission_denied(ENOT_AUTHORIZED)); + let old_major = borrow_global(@aptos_framework).major; + assert!(old_major < major, error::invalid_argument(EINVALID_MAJOR_VERSION_NUMBER)); + config_buffer::upsert(Version {major}); + } + + /// Only used in reconfigurations to apply the pending `Version`, if there is any. + public(friend) fun on_new_epoch(framework: &signer) acquires Version { + system_addresses::assert_aptos_framework(framework); + if (config_buffer::does_exist()) { + let new_value = config_buffer::extract(); + if (exists(@aptos_framework)) { + *borrow_global_mut(@aptos_framework) = new_value; + } else { + move_to(framework, new_value); + } + } + } + + /// Only called in tests and testnets. This allows the core resources account, which only exists in tests/testnets, + /// to update the version. + fun initialize_for_test(core_resources: &signer) { + system_addresses::assert_core_resource(core_resources); + move_to(core_resources, SetVersionCapability {}); + } + + #[test(aptos_framework = @aptos_framework)] + public entry fun test_set_version(aptos_framework: signer) acquires Version { + initialize(&aptos_framework, 1); + assert!(borrow_global(@aptos_framework).major == 1, 0); + set_version(&aptos_framework, 2); + assert!(borrow_global(@aptos_framework).major == 2, 1); + } + + #[test(aptos_framework = @aptos_framework, core_resources = @core_resources)] + public entry fun test_set_version_core_resources( + aptos_framework: signer, + core_resources: signer, + ) acquires Version { + initialize(&aptos_framework, 1); + assert!(borrow_global(@aptos_framework).major == 1, 0); + initialize_for_test(&core_resources); + set_version(&core_resources, 2); + assert!(borrow_global(@aptos_framework).major == 2, 1); + } + + #[test(aptos_framework = @aptos_framework, random_account = @0x123)] + #[expected_failure(abort_code = 327682, location = Self)] + public entry fun test_set_version_unauthorized_should_fail( + aptos_framework: signer, + random_account: signer, + ) acquires Version { + initialize(&aptos_framework, 1); + set_version(&random_account, 2); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/vesting.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/vesting.move new file mode 100644 index 000000000..527b4726f --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/vesting.move @@ -0,0 +1,2183 @@ +/// +/// Simple vesting contract that allows specifying how much APT coins should be vesting in each fixed-size period. The +/// vesting contract also comes with staking and allows shareholders to withdraw rewards anytime. +/// +/// Vesting schedule is represented as a vector of distributions. For example, a vesting schedule of +/// [3/48, 3/48, 1/48] means that after the vesting starts: +/// 1. The first and second periods will vest 3/48 of the total original grant. +/// 2. The third period will vest 1/48. +/// 3. All subsequent periods will also vest 1/48 (last distribution in the schedule) until the original grant runs out. +/// +/// Shareholder flow: +/// 1. Admin calls create_vesting_contract with a schedule of [3/48, 3/48, 1/48] with a vesting cliff of 1 year and +/// vesting period of 1 month. +/// 2. After a month, a shareholder calls unlock_rewards to request rewards. They can also call vest() which would also +/// unlocks rewards but since the 1 year cliff has not passed (vesting has not started), vest() would not release any of +/// the original grant. +/// 3. After the unlocked rewards become fully withdrawable (as it's subject to staking lockup), shareholders can call +/// distribute() to send all withdrawable funds to all shareholders based on the original grant's shares structure. +/// 4. After 1 year and 1 month, the vesting schedule now starts. Shareholders call vest() to unlock vested coins. vest() +/// checks the schedule and unlocks 3/48 of the original grant in addition to any accumulated rewards since last +/// unlock_rewards(). Once the unlocked coins become withdrawable, shareholders can call distribute(). +/// 5. Assuming the shareholders forgot to call vest() for 2 months, when they call vest() again, they will unlock vested +/// tokens for the next period since last vest. This would be for the first month they missed. They can call vest() a +/// second time to unlock for the second month they missed. +/// +/// Admin flow: +/// 1. After creating the vesting contract, admin cannot change the vesting schedule. +/// 2. Admin can call update_voter, update_operator, or reset_lockup at any time to update the underlying staking +/// contract. +/// 3. Admin can also call update_beneficiary for any shareholder. This would send all distributions (rewards, vested +/// coins) of that shareholder to the beneficiary account. By defalt, if a beneficiary is not set, the distributions are +/// send directly to the shareholder account. +/// 4. Admin can call terminate_vesting_contract to terminate the vesting. This would first finish any distribution but +/// will prevent any further rewards or vesting distributions from being created. Once the locked up stake becomes +/// withdrawable, admin can call admin_withdraw to withdraw all funds to the vesting contract's withdrawal address. +module aptos_framework::vesting { + use std::bcs; + use std::error; + use std::fixed_point32::{Self, FixedPoint32}; + use std::signer; + use std::string::{utf8, String}; + use std::vector; + + use aptos_std::pool_u64::{Self, Pool}; + use aptos_std::simple_map::{Self, SimpleMap}; + + use aptos_framework::account::{Self, SignerCapability, new_event_handle}; + use aptos_framework::aptos_account::{Self, assert_account_is_registered_for_apt}; + use aptos_framework::aptos_coin::AptosCoin; + use aptos_framework::coin::{Self, Coin}; + use aptos_framework::event::{EventHandle, emit, emit_event}; + use aptos_framework::stake; + use aptos_framework::staking_contract; + use aptos_framework::system_addresses; + use aptos_framework::timestamp; + + friend aptos_framework::genesis; + + const VESTING_POOL_SALT: vector = b"aptos_framework::vesting"; + + /// Withdrawal address is invalid. + const EINVALID_WITHDRAWAL_ADDRESS: u64 = 1; + /// Vesting schedule cannot be empty. + const EEMPTY_VESTING_SCHEDULE: u64 = 2; + /// Vesting period cannot be 0. + const EZERO_VESTING_SCHEDULE_PERIOD: u64 = 3; + /// Shareholders list cannot be empty. + const ENO_SHAREHOLDERS: u64 = 4; + /// The length of shareholders and shares lists don't match. + const ESHARES_LENGTH_MISMATCH: u64 = 5; + /// Vesting cannot start before or at the current block timestamp. Has to be in the future. + const EVESTING_START_TOO_SOON: u64 = 6; + /// The signer is not the admin of the vesting contract. + const ENOT_ADMIN: u64 = 7; + /// Vesting contract needs to be in active state. + const EVESTING_CONTRACT_NOT_ACTIVE: u64 = 8; + /// Admin can only withdraw from an inactive (paused or terminated) vesting contract. + const EVESTING_CONTRACT_STILL_ACTIVE: u64 = 9; + /// No vesting contract found at provided address. + const EVESTING_CONTRACT_NOT_FOUND: u64 = 10; + /// Cannot terminate the vesting contract with pending active stake. Need to wait until next epoch. + const EPENDING_STAKE_FOUND: u64 = 11; + /// Grant amount cannot be 0. + const EZERO_GRANT: u64 = 12; + /// Vesting account has no other management roles beside admin. + const EVESTING_ACCOUNT_HAS_NO_ROLES: u64 = 13; + /// The vesting account has no such management role. + const EROLE_NOT_FOUND: u64 = 14; + /// Account is not admin or does not have the required role to take this action. + const EPERMISSION_DENIED: u64 = 15; + /// Zero items were provided to a *_many function. + const EVEC_EMPTY_FOR_MANY_FUNCTION: u64 = 16; + + /// Maximum number of shareholders a vesting pool can support. + const MAXIMUM_SHAREHOLDERS: u64 = 30; + + /// Vesting contract states. + /// Vesting contract is active and distributions can be made. + const VESTING_POOL_ACTIVE: u64 = 1; + /// Vesting contract has been terminated and all funds have been released back to the withdrawal address. + const VESTING_POOL_TERMINATED: u64 = 2; + + /// Roles that can manage certain aspects of the vesting account beyond the main admin. + const ROLE_BENEFICIARY_RESETTER: vector = b"ROLE_BENEFICIARY_RESETTER"; + + struct VestingSchedule has copy, drop, store { + // The vesting schedule as a list of fractions that vest for each period. The last number is repeated until the + // vesting amount runs out. + // For example [1/24, 1/24, 1/48] with a period of 1 month means that after vesting starts, the first two months + // will vest 1/24 of the original total amount. From the third month only, 1/48 will vest until the vesting fund + // runs out. + // u32/u32 should be sufficient to support vesting schedule fractions. + schedule: vector, + // When the vesting should start. + start_timestamp_secs: u64, + // In seconds. How long each vesting period is. For example 1 month. + period_duration: u64, + // Last vesting period, 1-indexed. For example if 2 months have passed, the last vesting period, if distribution + // was requested, would be 2. Default value is 0 which means there have been no vesting periods yet. + last_vested_period: u64, + } + + struct StakingInfo has store { + // Where the vesting's stake pool is located at. Included for convenience. + pool_address: address, + // The currently assigned operator. + operator: address, + // The currently assigned voter. + voter: address, + // Commission paid to the operator of the stake pool. + commission_percentage: u64, + } + + struct VestingContract has key { + state: u64, + admin: address, + grant_pool: Pool, + beneficiaries: SimpleMap, + vesting_schedule: VestingSchedule, + // Withdrawal address where all funds would be released back to if the admin ends the vesting for a specific + // account or terminates the entire vesting contract. + withdrawal_address: address, + staking: StakingInfo, + // Remaining amount in the grant. For calculating accumulated rewards. + remaining_grant: u64, + // Used to control staking. + signer_cap: SignerCapability, + + // Events. + update_operator_events: EventHandle, + update_voter_events: EventHandle, + reset_lockup_events: EventHandle, + set_beneficiary_events: EventHandle, + unlock_rewards_events: EventHandle, + vest_events: EventHandle, + distribute_events: EventHandle, + terminate_events: EventHandle, + admin_withdraw_events: EventHandle, + } + + struct VestingAccountManagement has key { + roles: SimpleMap, + } + + struct AdminStore has key { + vesting_contracts: vector
, + // Used to create resource accounts for new vesting contracts so there's no address collision. + nonce: u64, + + create_events: EventHandle, + } + + #[event] + struct CreateVestingContract has drop, store { + operator: address, + voter: address, + grant_amount: u64, + withdrawal_address: address, + vesting_contract_address: address, + staking_pool_address: address, + commission_percentage: u64, + } + + #[event] + struct UpdateOperator has drop, store { + admin: address, + vesting_contract_address: address, + staking_pool_address: address, + old_operator: address, + new_operator: address, + commission_percentage: u64, + } + + #[event] + struct UpdateVoter has drop, store { + admin: address, + vesting_contract_address: address, + staking_pool_address: address, + old_voter: address, + new_voter: address, + } + + #[event] + struct ResetLockup has drop, store { + admin: address, + vesting_contract_address: address, + staking_pool_address: address, + new_lockup_expiration_secs: u64, + } + + #[event] + struct SetBeneficiary has drop, store { + admin: address, + vesting_contract_address: address, + shareholder: address, + old_beneficiary: address, + new_beneficiary: address, + } + + #[event] + struct UnlockRewards has drop, store { + admin: address, + vesting_contract_address: address, + staking_pool_address: address, + amount: u64, + } + + #[event] + struct Vest has drop, store { + admin: address, + vesting_contract_address: address, + staking_pool_address: address, + period_vested: u64, + amount: u64, + } + + #[event] + struct Distribute has drop, store { + admin: address, + vesting_contract_address: address, + amount: u64, + } + + #[event] + struct Terminate has drop, store { + admin: address, + vesting_contract_address: address, + } + + #[event] + struct AdminWithdraw has drop, store { + admin: address, + vesting_contract_address: address, + amount: u64, + } + + struct CreateVestingContractEvent has drop, store { + operator: address, + voter: address, + grant_amount: u64, + withdrawal_address: address, + vesting_contract_address: address, + staking_pool_address: address, + commission_percentage: u64, + } + + struct UpdateOperatorEvent has drop, store { + admin: address, + vesting_contract_address: address, + staking_pool_address: address, + old_operator: address, + new_operator: address, + commission_percentage: u64, + } + + struct UpdateVoterEvent has drop, store { + admin: address, + vesting_contract_address: address, + staking_pool_address: address, + old_voter: address, + new_voter: address, + } + + struct ResetLockupEvent has drop, store { + admin: address, + vesting_contract_address: address, + staking_pool_address: address, + new_lockup_expiration_secs: u64, + } + + struct SetBeneficiaryEvent has drop, store { + admin: address, + vesting_contract_address: address, + shareholder: address, + old_beneficiary: address, + new_beneficiary: address, + } + + struct UnlockRewardsEvent has drop, store { + admin: address, + vesting_contract_address: address, + staking_pool_address: address, + amount: u64, + } + + struct VestEvent has drop, store { + admin: address, + vesting_contract_address: address, + staking_pool_address: address, + period_vested: u64, + amount: u64, + } + + struct DistributeEvent has drop, store { + admin: address, + vesting_contract_address: address, + amount: u64, + } + + struct TerminateEvent has drop, store { + admin: address, + vesting_contract_address: address, + } + + struct AdminWithdrawEvent has drop, store { + admin: address, + vesting_contract_address: address, + amount: u64, + } + + #[view] + /// Return the address of the underlying stake pool (separate resource account) of the vesting contract. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun stake_pool_address(vesting_contract_address: address): address acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).staking.pool_address + } + + #[view] + /// Return the vesting start timestamp (in seconds) of the vesting contract. + /// Vesting will start at this time, and once a full period has passed, the first vest will become unlocked. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun vesting_start_secs(vesting_contract_address: address): u64 acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).vesting_schedule.start_timestamp_secs + } + + #[view] + /// Return the duration of one vesting period (in seconds). + /// Each vest is released after one full period has started, starting from the specified start_timestamp_secs. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun period_duration_secs(vesting_contract_address: address): u64 acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).vesting_schedule.period_duration + } + + #[view] + /// Return the remaining grant, consisting of unvested coins that have not been distributed to shareholders. + /// Prior to start_timestamp_secs, the remaining grant will always be equal to the original grant. + /// Once vesting has started, and vested tokens are distributed, the remaining grant will decrease over time, + /// according to the vesting schedule. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun remaining_grant(vesting_contract_address: address): u64 acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).remaining_grant + } + + #[view] + /// Return the beneficiary account of the specified shareholder in a vesting contract. + /// This is the same as the shareholder address by default and only different if it's been explicitly set. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun beneficiary(vesting_contract_address: address, shareholder: address): address acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + get_beneficiary(borrow_global(vesting_contract_address), shareholder) + } + + #[view] + /// Return the percentage of accumulated rewards that is paid to the operator as commission. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun operator_commission_percentage(vesting_contract_address: address): u64 acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).staking.commission_percentage + } + + #[view] + /// Return all the vesting contracts a given address is an admin of. + public fun vesting_contracts(admin: address): vector
acquires AdminStore { + if (!exists(admin)) { + vector::empty
() + } else { + borrow_global(admin).vesting_contracts + } + } + + #[view] + /// Return the operator who runs the validator for the vesting contract. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun operator(vesting_contract_address: address): address acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).staking.operator + } + + #[view] + /// Return the voter who will be voting on on-chain governance proposals on behalf of the vesting contract's stake + /// pool. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun voter(vesting_contract_address: address): address acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).staking.voter + } + + #[view] + /// Return the vesting contract's vesting schedule. The core schedule is represented as a list of u64-based + /// fractions, where the rightmmost 32 bits can be divided by 2^32 to get the fraction, and anything else is the + /// whole number. + /// + /// For example 3/48, or 0.0625, will be represented as 268435456. The fractional portion would be + /// 268435456 / 2^32 = 0.0625. Since there are fewer than 32 bits, the whole number portion is effectively 0. + /// So 268435456 = 0.0625. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun vesting_schedule(vesting_contract_address: address): VestingSchedule acquires VestingContract { + assert_vesting_contract_exists(vesting_contract_address); + borrow_global(vesting_contract_address).vesting_schedule + } + + #[view] + /// Return the total accumulated rewards that have not been distributed to shareholders of the vesting contract. + /// This excludes any unpaid commission that the operator has not collected. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun total_accumulated_rewards(vesting_contract_address: address): u64 acquires VestingContract { + assert_active_vesting_contract(vesting_contract_address); + + let vesting_contract = borrow_global(vesting_contract_address); + let (total_active_stake, _, commission_amount) = + staking_contract::staking_contract_amounts(vesting_contract_address, vesting_contract.staking.operator); + total_active_stake - vesting_contract.remaining_grant - commission_amount + } + + #[view] + /// Return the accumulated rewards that have not been distributed to the provided shareholder. Caller can also pass + /// the beneficiary address instead of shareholder address. + /// + /// This errors out if the vesting contract with the provided address doesn't exist. + public fun accumulated_rewards( + vesting_contract_address: address, shareholder_or_beneficiary: address): u64 acquires VestingContract { + assert_active_vesting_contract(vesting_contract_address); + + let total_accumulated_rewards = total_accumulated_rewards(vesting_contract_address); + let shareholder = shareholder(vesting_contract_address, shareholder_or_beneficiary); + let vesting_contract = borrow_global(vesting_contract_address); + let shares = pool_u64::shares(&vesting_contract.grant_pool, shareholder); + pool_u64::shares_to_amount_with_total_coins(&vesting_contract.grant_pool, shares, total_accumulated_rewards) + } + + #[view] + /// Return the list of all shareholders in the vesting contract. + public fun shareholders(vesting_contract_address: address): vector
acquires VestingContract { + assert_active_vesting_contract(vesting_contract_address); + + let vesting_contract = borrow_global(vesting_contract_address); + pool_u64::shareholders(&vesting_contract.grant_pool) + } + + #[view] + /// Return the shareholder address given the beneficiary address in a given vesting contract. If there are multiple + /// shareholders with the same beneficiary address, only the first shareholder is returned. If the given beneficiary + /// address is actually a shareholder address, just return the address back. + /// + /// This returns 0x0 if no shareholder is found for the given beneficiary / the address is not a shareholder itself. + public fun shareholder( + vesting_contract_address: address, + shareholder_or_beneficiary: address + ): address acquires VestingContract { + assert_active_vesting_contract(vesting_contract_address); + + let shareholders = &shareholders(vesting_contract_address); + if (vector::contains(shareholders, &shareholder_or_beneficiary)) { + return shareholder_or_beneficiary + }; + let vesting_contract = borrow_global(vesting_contract_address); + let result = @0x0; + vector::any(shareholders, |shareholder| { + if (shareholder_or_beneficiary == get_beneficiary(vesting_contract, *shareholder)) { + result = *shareholder; + true + } else { + false + } + }); + + result + } + + /// Create a vesting schedule with the given schedule of distributions, a vesting start time and period duration. + public fun create_vesting_schedule( + schedule: vector, + start_timestamp_secs: u64, + period_duration: u64, + ): VestingSchedule { + assert!(vector::length(&schedule) > 0, error::invalid_argument(EEMPTY_VESTING_SCHEDULE)); + assert!(period_duration > 0, error::invalid_argument(EZERO_VESTING_SCHEDULE_PERIOD)); + assert!( + start_timestamp_secs >= timestamp::now_seconds(), + error::invalid_argument(EVESTING_START_TOO_SOON), + ); + + VestingSchedule { + schedule, + start_timestamp_secs, + period_duration, + last_vested_period: 0, + } + } + + /// Create a vesting contract with a given configurations. + public fun create_vesting_contract( + admin: &signer, + shareholders: &vector
, + buy_ins: SimpleMap>, + vesting_schedule: VestingSchedule, + withdrawal_address: address, + operator: address, + voter: address, + commission_percentage: u64, + // Optional seed used when creating the staking contract account. + contract_creation_seed: vector, + ): address acquires AdminStore { + assert!( + !system_addresses::is_reserved_address(withdrawal_address), + error::invalid_argument(EINVALID_WITHDRAWAL_ADDRESS), + ); + assert_account_is_registered_for_apt(withdrawal_address); + assert!(vector::length(shareholders) > 0, error::invalid_argument(ENO_SHAREHOLDERS)); + assert!( + simple_map::length(&buy_ins) == vector::length(shareholders), + error::invalid_argument(ESHARES_LENGTH_MISMATCH), + ); + + // Create a coins pool to track shareholders and shares of the grant. + let grant = coin::zero(); + let grant_amount = 0; + let grant_pool = pool_u64::create(MAXIMUM_SHAREHOLDERS); + vector::for_each_ref(shareholders, |shareholder| { + let shareholder: address = *shareholder; + let (_, buy_in) = simple_map::remove(&mut buy_ins, &shareholder); + let buy_in_amount = coin::value(&buy_in); + coin::merge(&mut grant, buy_in); + pool_u64::buy_in( + &mut grant_pool, + shareholder, + buy_in_amount, + ); + grant_amount = grant_amount + buy_in_amount; + }); + assert!(grant_amount > 0, error::invalid_argument(EZERO_GRANT)); + + // If this is the first time this admin account has created a vesting contract, initialize the admin store. + let admin_address = signer::address_of(admin); + if (!exists(admin_address)) { + move_to(admin, AdminStore { + vesting_contracts: vector::empty
(), + nonce: 0, + create_events: new_event_handle(admin), + }); + }; + + // Initialize the vesting contract in a new resource account. This allows the same admin to create multiple + // pools. + let (contract_signer, contract_signer_cap) = create_vesting_contract_account(admin, contract_creation_seed); + let pool_address = staking_contract::create_staking_contract_with_coins( + &contract_signer, operator, voter, grant, commission_percentage, contract_creation_seed); + + // Add the newly created vesting contract's address to the admin store. + let contract_address = signer::address_of(&contract_signer); + let admin_store = borrow_global_mut(admin_address); + vector::push_back(&mut admin_store.vesting_contracts, contract_address); + if (std::features::module_event_migration_enabled()) { + emit( + CreateVestingContract { + operator, + voter, + withdrawal_address, + grant_amount, + vesting_contract_address: contract_address, + staking_pool_address: pool_address, + commission_percentage, + }, + ); + }; + emit_event( + &mut admin_store.create_events, + CreateVestingContractEvent { + operator, + voter, + withdrawal_address, + grant_amount, + vesting_contract_address: contract_address, + staking_pool_address: pool_address, + commission_percentage, + }, + ); + + move_to(&contract_signer, VestingContract { + state: VESTING_POOL_ACTIVE, + admin: admin_address, + grant_pool, + beneficiaries: simple_map::create(), + vesting_schedule, + withdrawal_address, + staking: StakingInfo { pool_address, operator, voter, commission_percentage }, + remaining_grant: grant_amount, + signer_cap: contract_signer_cap, + update_operator_events: new_event_handle(&contract_signer), + update_voter_events: new_event_handle(&contract_signer), + reset_lockup_events: new_event_handle(&contract_signer), + set_beneficiary_events: new_event_handle(&contract_signer), + unlock_rewards_events: new_event_handle(&contract_signer), + vest_events: new_event_handle(&contract_signer), + distribute_events: new_event_handle(&contract_signer), + terminate_events: new_event_handle(&contract_signer), + admin_withdraw_events: new_event_handle(&contract_signer), + }); + + simple_map::destroy_empty(buy_ins); + contract_address + } + + /// Unlock any accumulated rewards. + public entry fun unlock_rewards(contract_address: address) acquires VestingContract { + let accumulated_rewards = total_accumulated_rewards(contract_address); + let vesting_contract = borrow_global(contract_address); + unlock_stake(vesting_contract, accumulated_rewards); + } + + /// Call `unlock_rewards` for many vesting contracts. + public entry fun unlock_rewards_many(contract_addresses: vector
) acquires VestingContract { + let len = vector::length(&contract_addresses); + + assert!(len != 0, error::invalid_argument(EVEC_EMPTY_FOR_MANY_FUNCTION)); + + vector::for_each_ref(&contract_addresses, |contract_address| { + let contract_address: address = *contract_address; + unlock_rewards(contract_address); + }); + } + + /// Unlock any vested portion of the grant. + public entry fun vest(contract_address: address) acquires VestingContract { + // Unlock all rewards first, if any. + unlock_rewards(contract_address); + + // Unlock the vested amount. This amount will become withdrawable when the underlying stake pool's lockup + // expires. + let vesting_contract = borrow_global_mut(contract_address); + // Short-circuit if vesting hasn't started yet. + if (vesting_contract.vesting_schedule.start_timestamp_secs > timestamp::now_seconds()) { + return + }; + + // Check if the next vested period has already passed. If not, short-circuit since there's nothing to vest. + let vesting_schedule = &mut vesting_contract.vesting_schedule; + let last_vested_period = vesting_schedule.last_vested_period; + let next_period_to_vest = last_vested_period + 1; + let last_completed_period = + (timestamp::now_seconds() - vesting_schedule.start_timestamp_secs) / vesting_schedule.period_duration; + if (last_completed_period < next_period_to_vest) { + return + }; + + // Calculate how much has vested, excluding rewards. + // Index is 0-based while period is 1-based so we need to subtract 1. + let schedule = &vesting_schedule.schedule; + let schedule_index = next_period_to_vest - 1; + let vesting_fraction = if (schedule_index < vector::length(schedule)) { + *vector::borrow(schedule, schedule_index) + } else { + // Last vesting schedule fraction will repeat until the grant runs out. + *vector::borrow(schedule, vector::length(schedule) - 1) + }; + let total_grant = pool_u64::total_coins(&vesting_contract.grant_pool); + let vested_amount = fixed_point32::multiply_u64(total_grant, vesting_fraction); + // Cap vested amount by the remaining grant amount so we don't try to distribute more than what's remaining. + vested_amount = min(vested_amount, vesting_contract.remaining_grant); + vesting_contract.remaining_grant = vesting_contract.remaining_grant - vested_amount; + vesting_schedule.last_vested_period = next_period_to_vest; + unlock_stake(vesting_contract, vested_amount); + + if (std::features::module_event_migration_enabled()) { + emit( + Vest { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + staking_pool_address: vesting_contract.staking.pool_address, + period_vested: next_period_to_vest, + amount: vested_amount, + }, + ); + }; + emit_event( + &mut vesting_contract.vest_events, + VestEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + staking_pool_address: vesting_contract.staking.pool_address, + period_vested: next_period_to_vest, + amount: vested_amount, + }, + ); + } + + /// Call `vest` for many vesting contracts. + public entry fun vest_many(contract_addresses: vector
) acquires VestingContract { + let len = vector::length(&contract_addresses); + + assert!(len != 0, error::invalid_argument(EVEC_EMPTY_FOR_MANY_FUNCTION)); + + vector::for_each_ref(&contract_addresses, |contract_address| { + let contract_address = *contract_address; + vest(contract_address); + }); + } + + /// Distribute any withdrawable stake from the stake pool. + public entry fun distribute(contract_address: address) acquires VestingContract { + assert_active_vesting_contract(contract_address); + + let vesting_contract = borrow_global_mut(contract_address); + let coins = withdraw_stake(vesting_contract, contract_address); + let total_distribution_amount = coin::value(&coins); + if (total_distribution_amount == 0) { + coin::destroy_zero(coins); + return + }; + + // Distribute coins to all shareholders in the vesting contract. + let grant_pool = &vesting_contract.grant_pool; + let shareholders = &pool_u64::shareholders(grant_pool); + vector::for_each_ref(shareholders, |shareholder| { + let shareholder = *shareholder; + let shares = pool_u64::shares(grant_pool, shareholder); + let amount = pool_u64::shares_to_amount_with_total_coins(grant_pool, shares, total_distribution_amount); + let share_of_coins = coin::extract(&mut coins, amount); + let recipient_address = get_beneficiary(vesting_contract, shareholder); + aptos_account::deposit_coins(recipient_address, share_of_coins); + }); + + // Send any remaining "dust" (leftover due to rounding error) to the withdrawal address. + if (coin::value(&coins) > 0) { + aptos_account::deposit_coins(vesting_contract.withdrawal_address, coins); + } else { + coin::destroy_zero(coins); + }; + + if (std::features::module_event_migration_enabled()) { + emit( + Distribute { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + amount: total_distribution_amount, + }, + ); + }; + emit_event( + &mut vesting_contract.distribute_events, + DistributeEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + amount: total_distribution_amount, + }, + ); + } + + /// Call `distribute` for many vesting contracts. + public entry fun distribute_many(contract_addresses: vector
) acquires VestingContract { + let len = vector::length(&contract_addresses); + + assert!(len != 0, error::invalid_argument(EVEC_EMPTY_FOR_MANY_FUNCTION)); + + vector::for_each_ref(&contract_addresses, |contract_address| { + let contract_address = *contract_address; + distribute(contract_address); + }); + } + + /// Terminate the vesting contract and send all funds back to the withdrawal address. + public entry fun terminate_vesting_contract(admin: &signer, contract_address: address) acquires VestingContract { + assert_active_vesting_contract(contract_address); + + // Distribute all withdrawable coins, which should have been from previous rewards withdrawal or vest. + distribute(contract_address); + + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + let (active_stake, _, pending_active_stake, _) = stake::get_stake(vesting_contract.staking.pool_address); + assert!(pending_active_stake == 0, error::invalid_state(EPENDING_STAKE_FOUND)); + + // Unlock all remaining active stake. + vesting_contract.state = VESTING_POOL_TERMINATED; + vesting_contract.remaining_grant = 0; + unlock_stake(vesting_contract, active_stake); + + if (std::features::module_event_migration_enabled()) { + emit( + Terminate { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + }, + ); + }; + emit_event( + &mut vesting_contract.terminate_events, + TerminateEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + }, + ); + } + + /// Withdraw all funds to the preset vesting contract's withdrawal address. This can only be called if the contract + /// has already been terminated. + public entry fun admin_withdraw(admin: &signer, contract_address: address) acquires VestingContract { + let vesting_contract = borrow_global(contract_address); + assert!( + vesting_contract.state == VESTING_POOL_TERMINATED, + error::invalid_state(EVESTING_CONTRACT_STILL_ACTIVE) + ); + + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + let coins = withdraw_stake(vesting_contract, contract_address); + let amount = coin::value(&coins); + if (amount == 0) { + coin::destroy_zero(coins); + return + }; + aptos_account::deposit_coins(vesting_contract.withdrawal_address, coins); + + if (std::features::module_event_migration_enabled()) { + emit( + AdminWithdraw { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + amount, + }, + ); + }; + emit_event( + &mut vesting_contract.admin_withdraw_events, + AdminWithdrawEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + amount, + }, + ); + } + + public entry fun update_operator( + admin: &signer, + contract_address: address, + new_operator: address, + commission_percentage: u64, + ) acquires VestingContract { + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + let contract_signer = &get_vesting_account_signer_internal(vesting_contract); + let old_operator = vesting_contract.staking.operator; + staking_contract::switch_operator(contract_signer, old_operator, new_operator, commission_percentage); + vesting_contract.staking.operator = new_operator; + vesting_contract.staking.commission_percentage = commission_percentage; + + if (std::features::module_event_migration_enabled()) { + emit( + UpdateOperator { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + staking_pool_address: vesting_contract.staking.pool_address, + old_operator, + new_operator, + commission_percentage, + }, + ); + }; + emit_event( + &mut vesting_contract.update_operator_events, + UpdateOperatorEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + staking_pool_address: vesting_contract.staking.pool_address, + old_operator, + new_operator, + commission_percentage, + }, + ); + } + + public entry fun update_operator_with_same_commission( + admin: &signer, + contract_address: address, + new_operator: address, + ) acquires VestingContract { + let commission_percentage = operator_commission_percentage(contract_address); + update_operator(admin, contract_address, new_operator, commission_percentage); + } + + public entry fun update_commission_percentage( + admin: &signer, + contract_address: address, + new_commission_percentage: u64, + ) acquires VestingContract { + let operator = operator(contract_address); + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + let contract_signer = &get_vesting_account_signer_internal(vesting_contract); + staking_contract::update_commision(contract_signer, operator, new_commission_percentage); + vesting_contract.staking.commission_percentage = new_commission_percentage; + // This function does not emit an event. Instead, `staking_contract::update_commission_percentage` + // emits the event for this commission percentage update. + } + + public entry fun update_voter( + admin: &signer, + contract_address: address, + new_voter: address, + ) acquires VestingContract { + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + let contract_signer = &get_vesting_account_signer_internal(vesting_contract); + let old_voter = vesting_contract.staking.voter; + staking_contract::update_voter(contract_signer, vesting_contract.staking.operator, new_voter); + vesting_contract.staking.voter = new_voter; + + if (std::features::module_event_migration_enabled()) { + emit( + UpdateVoter { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + staking_pool_address: vesting_contract.staking.pool_address, + old_voter, + new_voter, + }, + ); + }; + emit_event( + &mut vesting_contract.update_voter_events, + UpdateVoterEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + staking_pool_address: vesting_contract.staking.pool_address, + old_voter, + new_voter, + }, + ); + } + + public entry fun reset_lockup( + admin: &signer, + contract_address: address, + ) acquires VestingContract { + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + let contract_signer = &get_vesting_account_signer_internal(vesting_contract); + staking_contract::reset_lockup(contract_signer, vesting_contract.staking.operator); + + if (std::features::module_event_migration_enabled()) { + emit( + ResetLockup { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + staking_pool_address: vesting_contract.staking.pool_address, + new_lockup_expiration_secs: stake::get_lockup_secs(vesting_contract.staking.pool_address), + }, + ); + }; + emit_event( + &mut vesting_contract.reset_lockup_events, + ResetLockupEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + staking_pool_address: vesting_contract.staking.pool_address, + new_lockup_expiration_secs: stake::get_lockup_secs(vesting_contract.staking.pool_address), + }, + ); + } + + public entry fun set_beneficiary( + admin: &signer, + contract_address: address, + shareholder: address, + new_beneficiary: address, + ) acquires VestingContract { + // Verify that the beneficiary account is set up to receive APT. This is a requirement so distribute() wouldn't + // fail and block all other accounts from receiving APT if one beneficiary is not registered. + assert_account_is_registered_for_apt(new_beneficiary); + + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + + let old_beneficiary = get_beneficiary(vesting_contract, shareholder); + let beneficiaries = &mut vesting_contract.beneficiaries; + if (simple_map::contains_key(beneficiaries, &shareholder)) { + let beneficiary = simple_map::borrow_mut(beneficiaries, &shareholder); + *beneficiary = new_beneficiary; + } else { + simple_map::add(beneficiaries, shareholder, new_beneficiary); + }; + + if (std::features::module_event_migration_enabled()) { + emit( + SetBeneficiary { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + shareholder, + old_beneficiary, + new_beneficiary, + }, + ); + }; + emit_event( + &mut vesting_contract.set_beneficiary_events, + SetBeneficiaryEvent { + admin: vesting_contract.admin, + vesting_contract_address: contract_address, + shareholder, + old_beneficiary, + new_beneficiary, + }, + ); + } + + /// Remove the beneficiary for the given shareholder. All distributions will sent directly to the shareholder + /// account. + public entry fun reset_beneficiary( + account: &signer, + contract_address: address, + shareholder: address, + ) acquires VestingAccountManagement, VestingContract { + let vesting_contract = borrow_global_mut(contract_address); + let addr = signer::address_of(account); + assert!( + addr == vesting_contract.admin || + addr == get_role_holder(contract_address, utf8(ROLE_BENEFICIARY_RESETTER)), + error::permission_denied(EPERMISSION_DENIED), + ); + + let beneficiaries = &mut vesting_contract.beneficiaries; + if (simple_map::contains_key(beneficiaries, &shareholder)) { + simple_map::remove(beneficiaries, &shareholder); + }; + } + + public entry fun set_management_role( + admin: &signer, + contract_address: address, + role: String, + role_holder: address, + ) acquires VestingAccountManagement, VestingContract { + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + + if (!exists(contract_address)) { + let contract_signer = &get_vesting_account_signer_internal(vesting_contract); + move_to(contract_signer, VestingAccountManagement { + roles: simple_map::create(), + }) + }; + let roles = &mut borrow_global_mut(contract_address).roles; + if (simple_map::contains_key(roles, &role)) { + *simple_map::borrow_mut(roles, &role) = role_holder; + } else { + simple_map::add(roles, role, role_holder); + }; + } + + public entry fun set_beneficiary_resetter( + admin: &signer, + contract_address: address, + beneficiary_resetter: address, + ) acquires VestingAccountManagement, VestingContract { + set_management_role(admin, contract_address, utf8(ROLE_BENEFICIARY_RESETTER), beneficiary_resetter); + } + + /// Set the beneficiary for the operator. + public entry fun set_beneficiary_for_operator( + operator: &signer, + new_beneficiary: address, + ) { + staking_contract::set_beneficiary_for_operator(operator, new_beneficiary); + } + + public fun get_role_holder(contract_address: address, role: String): address acquires VestingAccountManagement { + assert!(exists(contract_address), error::not_found(EVESTING_ACCOUNT_HAS_NO_ROLES)); + let roles = &borrow_global(contract_address).roles; + assert!(simple_map::contains_key(roles, &role), error::not_found(EROLE_NOT_FOUND)); + *simple_map::borrow(roles, &role) + } + + /// For emergency use in case the admin needs emergency control of vesting contract account. + /// This doesn't give the admin total power as the admin would still need to follow the rules set by + /// staking_contract and stake modules. + public fun get_vesting_account_signer(admin: &signer, contract_address: address): signer acquires VestingContract { + let vesting_contract = borrow_global_mut(contract_address); + verify_admin(admin, vesting_contract); + get_vesting_account_signer_internal(vesting_contract) + } + + fun get_vesting_account_signer_internal(vesting_contract: &VestingContract): signer { + account::create_signer_with_capability(&vesting_contract.signer_cap) + } + + /// Create a salt for generating the resource accounts that will be holding the VestingContract. + /// This address should be deterministic for the same admin and vesting contract creation nonce. + fun create_vesting_contract_account( + admin: &signer, + contract_creation_seed: vector, + ): (signer, SignerCapability) acquires AdminStore { + let admin_store = borrow_global_mut(signer::address_of(admin)); + let seed = bcs::to_bytes(&signer::address_of(admin)); + vector::append(&mut seed, bcs::to_bytes(&admin_store.nonce)); + admin_store.nonce = admin_store.nonce + 1; + + // Include a salt to avoid conflicts with any other modules out there that might also generate + // deterministic resource accounts for the same admin address + nonce. + vector::append(&mut seed, VESTING_POOL_SALT); + vector::append(&mut seed, contract_creation_seed); + + let (account_signer, signer_cap) = account::create_resource_account(admin, seed); + // Register the vesting contract account to receive APT as it'll be sent to it when claiming unlocked stake from + // the underlying staking contract. + coin::register(&account_signer); + + (account_signer, signer_cap) + } + + fun verify_admin(admin: &signer, vesting_contract: &VestingContract) { + assert!(signer::address_of(admin) == vesting_contract.admin, error::unauthenticated(ENOT_ADMIN)); + } + + fun assert_vesting_contract_exists(contract_address: address) { + assert!(exists(contract_address), error::not_found(EVESTING_CONTRACT_NOT_FOUND)); + } + + fun assert_active_vesting_contract(contract_address: address) acquires VestingContract { + assert_vesting_contract_exists(contract_address); + let vesting_contract = borrow_global(contract_address); + assert!(vesting_contract.state == VESTING_POOL_ACTIVE, error::invalid_state(EVESTING_CONTRACT_NOT_ACTIVE)); + } + + fun unlock_stake(vesting_contract: &VestingContract, amount: u64) { + let contract_signer = &get_vesting_account_signer_internal(vesting_contract); + staking_contract::unlock_stake(contract_signer, vesting_contract.staking.operator, amount); + } + + fun withdraw_stake(vesting_contract: &VestingContract, contract_address: address): Coin { + // Claim any withdrawable distribution from the staking contract. The withdrawn coins will be sent directly to + // the vesting contract's account. + staking_contract::distribute(contract_address, vesting_contract.staking.operator); + let withdrawn_coins = coin::balance(contract_address); + let contract_signer = &get_vesting_account_signer_internal(vesting_contract); + coin::withdraw(contract_signer, withdrawn_coins) + } + + fun get_beneficiary(contract: &VestingContract, shareholder: address): address { + if (simple_map::contains_key(&contract.beneficiaries, &shareholder)) { + *simple_map::borrow(&contract.beneficiaries, &shareholder) + } else { + shareholder + } + } + + #[test_only] + use aptos_framework::stake::with_rewards; + + #[test_only] + use aptos_framework::account::create_account_for_test; + use aptos_std::math64::min; + + #[test_only] + const MIN_STAKE: u64 = 100000000000000; // 1M APT coins with 8 decimals. + + #[test_only] + const GRANT_AMOUNT: u64 = 20000000000000000; // 200M APT coins with 8 decimals. + + #[test_only] + const VESTING_SCHEDULE_CLIFF: u64 = 31536000; // 1 year + + #[test_only] + const VESTING_PERIOD: u64 = 2592000; // 30 days + + #[test_only] + const VALIDATOR_STATUS_PENDING_ACTIVE: u64 = 1; + #[test_only] + const VALIDATOR_STATUS_ACTIVE: u64 = 2; + #[test_only] + const VALIDATOR_STATUS_INACTIVE: u64 = 4; + + #[test_only] + const MODULE_EVENT: u64 = 26; + + #[test_only] + const OPERATOR_BENEFICIARY_CHANGE: u64 = 39; + + #[test_only] + public fun setup(aptos_framework: &signer, accounts: &vector
) { + use aptos_framework::aptos_account::create_account; + + stake::initialize_for_test_custom( + aptos_framework, + MIN_STAKE, + GRANT_AMOUNT * 10, + 3600, + true, + 10, + 10000, + 1000000 + ); + + vector::for_each_ref(accounts, |addr| { + let addr: address = *addr; + if (!account::exists_at(addr)) { + create_account(addr); + }; + }); + + std::features::change_feature_flags_for_testing(aptos_framework, vector[MODULE_EVENT, OPERATOR_BENEFICIARY_CHANGE], vector[]); + } + + #[test_only] + public fun setup_vesting_contract( + admin: &signer, + shareholders: &vector
, + shares: &vector, + withdrawal_address: address, + commission_percentage: u64, + ): address acquires AdminStore { + setup_vesting_contract_with_schedule( + admin, + shareholders, + shares, + withdrawal_address, + commission_percentage, + &vector[3, 2, 1], + 48, + ) + } + + #[test_only] + public fun setup_vesting_contract_with_schedule( + admin: &signer, + shareholders: &vector
, + shares: &vector, + withdrawal_address: address, + commission_percentage: u64, + vesting_numerators: &vector, + vesting_denominator: u64, + ): address acquires AdminStore { + let schedule = vector::empty(); + vector::for_each_ref(vesting_numerators, |num| { + vector::push_back(&mut schedule, fixed_point32::create_from_rational(*num, vesting_denominator)); + }); + let vesting_schedule = create_vesting_schedule( + schedule, + timestamp::now_seconds() + VESTING_SCHEDULE_CLIFF, + VESTING_PERIOD, + ); + + let admin_address = signer::address_of(admin); + let buy_ins = simple_map::create>(); + vector::enumerate_ref(shares, |i, share| { + let shareholder = *vector::borrow(shareholders, i); + simple_map::add(&mut buy_ins, shareholder, stake::mint_coins(*share)); + }); + + create_vesting_contract( + admin, + shareholders, + buy_ins, + vesting_schedule, + withdrawal_address, + admin_address, + admin_address, + commission_percentage, + vector[], + ) + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder_1 = @0x234, shareholder_2 = @0x345, withdrawal = @111)] + public entry fun test_end_to_end( + aptos_framework: &signer, + admin: &signer, + shareholder_1: &signer, + shareholder_2: &signer, + withdrawal: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let withdrawal_address = signer::address_of(withdrawal); + let shareholder_1_address = signer::address_of(shareholder_1); + let shareholder_2_address = signer::address_of(shareholder_2); + let shareholders = &vector[shareholder_1_address, shareholder_2_address]; + let shareholder_1_share = GRANT_AMOUNT / 4; + let shareholder_2_share = GRANT_AMOUNT * 3 / 4; + let shares = &vector[shareholder_1_share, shareholder_2_share]; + + // Create the vesting contract. + setup( + aptos_framework, &vector[admin_address, withdrawal_address, shareholder_1_address, shareholder_2_address]); + let contract_address = setup_vesting_contract(admin, shareholders, shares, withdrawal_address, 0); + assert!(vector::length(&borrow_global(admin_address).vesting_contracts) == 1, 0); + let stake_pool_address = stake_pool_address(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, 0); + + // The stake pool is still in pending active stake, so unlock_rewards and vest shouldn't do anything. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, admin, stake_pool_address, false); + assert!(stake::get_validator_state(stake_pool_address) == VALIDATOR_STATUS_PENDING_ACTIVE, 1); + unlock_rewards(contract_address); + vest(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, 0); + + // Wait for the validator to join the validator set. No rewards are earnt yet so unlock_rewards and vest should + // still do nothing. + stake::end_epoch(); + assert!(stake::get_validator_state(stake_pool_address) == VALIDATOR_STATUS_ACTIVE, 2); + unlock_rewards(contract_address); + vest(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, 0); + + // Stake pool earns some rewards. unlock_rewards should unlock the right amount. + stake::end_epoch(); + let rewards = get_accumulated_rewards(contract_address); + unlock_rewards(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, rewards); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Stake pool earns more rewards. vest should unlock the rewards but no vested tokens as vesting hasn't started. + stake::end_epoch(); + rewards = with_rewards(rewards); // Pending inactive stake still earns rewards. + rewards = rewards + get_accumulated_rewards(contract_address); + vest(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, rewards); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Fast forward to stake lockup expiration so rewards are fully unlocked. + // In the mean time, rewards still earn rewards. + // Calling distribute() should send rewards to the shareholders. + stake::fast_forward_to_unlock(stake_pool_address); + rewards = with_rewards(rewards); + distribute(contract_address); + let shareholder_1_bal = coin::balance(shareholder_1_address); + let shareholder_2_bal = coin::balance(shareholder_2_address); + // Distribution goes by the shares of the vesting contract. + assert!(shareholder_1_bal == rewards / 4, shareholder_1_bal); + assert!(shareholder_2_bal == rewards * 3 / 4, shareholder_2_bal); + + // Fast forward time to the vesting start. + timestamp::update_global_time_for_test_secs(vesting_start_secs(contract_address)); + // Calling vest only unlocks rewards but not any vested token as the first vesting period hasn't passed yet. + rewards = get_accumulated_rewards(contract_address); + vest(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, rewards); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Fast forward to the end of the first period. vest() should now unlock 3/48 of the tokens. + timestamp::fast_forward_seconds(VESTING_PERIOD); + vest(contract_address); + let vested_amount = fraction(GRANT_AMOUNT, 3, 48); + let remaining_grant = GRANT_AMOUNT - vested_amount; + let pending_distribution = rewards + vested_amount; + assert!(remaining_grant(contract_address) == remaining_grant, remaining_grant(contract_address)); + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, pending_distribution); + + // Fast forward to the end of the fourth period. We can call vest() 3 times to vest the last 3 periods. + timestamp::fast_forward_seconds(VESTING_PERIOD * 3); + vest(contract_address); + vested_amount = fraction(GRANT_AMOUNT, 2, 48); + remaining_grant = remaining_grant - vested_amount; + pending_distribution = pending_distribution + vested_amount; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, pending_distribution); + vest(contract_address); + vested_amount = fraction(GRANT_AMOUNT, 1, 48); + remaining_grant = remaining_grant - vested_amount; + pending_distribution = pending_distribution + vested_amount; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, pending_distribution); + // The last vesting fraction (1/48) is repeated beyond the first 3 periods. + vest(contract_address); + remaining_grant = remaining_grant - vested_amount; + pending_distribution = pending_distribution + vested_amount; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, pending_distribution); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + + stake::end_epoch(); + let total_active = with_rewards(remaining_grant); + pending_distribution = with_rewards(pending_distribution); + distribute(contract_address); + stake::assert_stake_pool(stake_pool_address, total_active, 0, 0, 0); + assert!(coin::balance(shareholder_1_address) == shareholder_1_bal + pending_distribution / 4, 0); + assert!(coin::balance(shareholder_2_address) == shareholder_2_bal + pending_distribution * 3 / 4, 1); + // Withdrawal address receives the left-over dust of 1 coin due to rounding error. + assert!(coin::balance(withdrawal_address) == 1, 0); + + // Admin terminates the vesting contract. + terminate_vesting_contract(admin, contract_address); + stake::assert_stake_pool(stake_pool_address, 0, 0, 0, total_active); + assert!(remaining_grant(contract_address) == 0, 0); + stake::fast_forward_to_unlock(stake_pool_address); + let withdrawn_amount = with_rewards(total_active); + stake::assert_stake_pool(stake_pool_address, 0, withdrawn_amount, 0, 0); + let previous_bal = coin::balance(withdrawal_address); + admin_withdraw(admin, contract_address); + assert!(coin::balance(withdrawal_address) == previous_bal + withdrawn_amount, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x1000C, location = Self)] + public entry fun test_create_vesting_contract_with_zero_grant_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + setup_vesting_contract(admin, &vector[@1], &vector[0], admin_address, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x10004, location = Self)] + public entry fun test_create_vesting_contract_with_no_shareholders_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + setup_vesting_contract(admin, &vector[], &vector[], admin_address, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x10005, location = Self)] + public entry fun test_create_vesting_contract_with_mistmaching_shareholders_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + setup_vesting_contract(admin, &vector[@1, @2], &vector[1], admin_address, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x60001, location = aptos_framework::aptos_account)] + public entry fun test_create_vesting_contract_with_invalid_withdrawal_address_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + setup_vesting_contract(admin, &vector[@1, @2], &vector[1], @5, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x60001, location = aptos_framework::aptos_account)] + public entry fun test_create_vesting_contract_with_missing_withdrawal_account_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + setup_vesting_contract(admin, &vector[@1, @2], &vector[1], @11, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x60002, location = aptos_framework::aptos_account)] + public entry fun test_create_vesting_contract_with_unregistered_withdrawal_account_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + create_account_for_test(@11); + setup_vesting_contract(admin, &vector[@1, @2], &vector[1], @11, 0); + } + + #[test(aptos_framework = @0x1)] + #[expected_failure(abort_code = 0x10002, location = Self)] + public entry fun test_create_empty_vesting_schedule_should_fail(aptos_framework: &signer) { + setup(aptos_framework, &vector[]); + create_vesting_schedule(vector[], 1, 1); + } + + #[test(aptos_framework = @0x1)] + #[expected_failure(abort_code = 0x10003, location = Self)] + public entry fun test_create_vesting_schedule_with_zero_period_duration_should_fail(aptos_framework: &signer) { + setup(aptos_framework, &vector[]); + create_vesting_schedule(vector[fixed_point32::create_from_rational(1, 1)], 1, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x10006, location = Self)] + public entry fun test_create_vesting_schedule_with_invalid_vesting_start_should_fail(aptos_framework: &signer) { + setup(aptos_framework, &vector[]); + timestamp::update_global_time_for_test_secs(1000); + create_vesting_schedule( + vector[fixed_point32::create_from_rational(1, 1)], + 900, + 1); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + public entry fun test_vest_twice_should_not_double_count( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + + // Operator needs to join the validator set for the stake pool to earn rewards. + let stake_pool_address = stake_pool_address(contract_address); + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, admin, stake_pool_address, true); + + // Fast forward to the end of the first period. vest() should now unlock 3/48 of the tokens. + timestamp::update_global_time_for_test_secs(vesting_start_secs(contract_address) + VESTING_PERIOD); + vest(contract_address); + let vested_amount = fraction(GRANT_AMOUNT, 3, 48); + let remaining_grant = GRANT_AMOUNT - vested_amount; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, vested_amount); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + + // Calling vest() a second time shouldn't change anything. + vest(contract_address); + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, vested_amount); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + public entry fun test_unlock_rewards_twice_should_not_double_count( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + + // Operator needs to join the validator set for the stake pool to earn rewards. + let stake_pool_address = stake_pool_address(contract_address); + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, admin, stake_pool_address, true); + + // Stake pool earns some rewards. unlock_rewards should unlock the right amount. + stake::end_epoch(); + let rewards = get_accumulated_rewards(contract_address); + unlock_rewards(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, rewards); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Calling unlock_rewards a second time shouldn't change anything as no new rewards has accumulated. + unlock_rewards(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, rewards); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234, operator = @0x345)] + public entry fun test_unlock_rewards_should_pay_commission_first( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + operator: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let operator_address = signer::address_of(operator); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address, operator_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + assert!(operator_commission_percentage(contract_address) == 0, 0); + + // 10% commission will be paid to the operator. + update_operator(admin, contract_address, operator_address, 10); + assert!(operator_commission_percentage(contract_address) == 10, 0); + + // Operator needs to join the validator set for the stake pool to earn rewards. + let stake_pool_address = stake_pool_address(contract_address); + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, stake_pool_address, true); + + // Stake pool earns some rewards. unlock_rewards should unlock the right amount. + stake::end_epoch(); + let accumulated_rewards = get_accumulated_rewards(contract_address); + let commission = accumulated_rewards / 10; // 10%. + let staker_rewards = accumulated_rewards - commission; + unlock_rewards(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, accumulated_rewards); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Distribution should pay commission to operator first and remaining amount to shareholders. + stake::fast_forward_to_unlock(stake_pool_address); + stake::assert_stake_pool( + stake_pool_address, + with_rewards(GRANT_AMOUNT), + with_rewards(accumulated_rewards), + 0, + 0 + ); + // Operator also earns more commission from the rewards earnt on the withdrawn rewards. + let commission_on_staker_rewards = (with_rewards(staker_rewards) - staker_rewards) / 10; + staker_rewards = with_rewards(staker_rewards) - commission_on_staker_rewards; + commission = with_rewards(commission) + commission_on_staker_rewards; + distribute(contract_address); + // Rounding error leads to a dust amount of 1 transferred to the staker. + assert!(coin::balance(shareholder_address) == staker_rewards + 1, 0); + assert!(coin::balance(operator_address) == commission - 1, 1); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234, operator = @0x345)] + public entry fun test_request_commission_should_not_lock_rewards_for_shareholders( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + operator: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let operator_address = signer::address_of(operator); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address, operator_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + assert!(operator_commission_percentage(contract_address) == 0, 0); + + // 10% commission will be paid to the operator. + update_operator(admin, contract_address, operator_address, 10); + assert!(operator_commission_percentage(contract_address) == 10, 0); + + // Operator needs to join the validator set for the stake pool to earn rewards. + let stake_pool_address = stake_pool_address(contract_address); + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, stake_pool_address, true); + + // Stake pool earns some rewards. + stake::end_epoch(); + + // Operator requests commission directly with staking_contract first. + let accumulated_rewards = get_accumulated_rewards(contract_address); + let commission = accumulated_rewards / 10; // 10%. + let staker_rewards = accumulated_rewards - commission; + staking_contract::request_commission(operator, contract_address, operator_address); + + // Unlock vesting rewards. This should still pay out the accumulated rewards to shareholders. + unlock_rewards(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, accumulated_rewards); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Distribution should pay commission to operator first and remaining amount to shareholders. + stake::fast_forward_to_unlock(stake_pool_address); + stake::assert_stake_pool( + stake_pool_address, + with_rewards(GRANT_AMOUNT), + with_rewards(accumulated_rewards), + 0, + 0 + ); + // Operator also earns more commission from the rewards earnt on the withdrawn rewards. + let commission_on_staker_rewards = (with_rewards(staker_rewards) - staker_rewards) / 10; + staker_rewards = with_rewards(staker_rewards) - commission_on_staker_rewards; + commission = with_rewards(commission) + commission_on_staker_rewards; + distribute(contract_address); + // Rounding error leads to a dust amount of 1 transferred to the staker. + assert!(coin::balance(shareholder_address) == staker_rewards + 1, 0); + assert!(coin::balance(operator_address) == commission - 1, 1); + } + + #[test(aptos_framework = @0x1, admin = @0x123, operator = @0x345)] + public entry fun test_update_operator_with_same_commission( + aptos_framework: &signer, + admin: &signer, + operator: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let operator_address = signer::address_of(operator); + setup(aptos_framework, &vector[admin_address, @11, operator_address]); + let contract_address = setup_vesting_contract( + admin, &vector[@11], &vector[GRANT_AMOUNT], admin_address, 10); + + update_operator_with_same_commission(admin, contract_address, operator_address); + assert!(operator_commission_percentage(contract_address) == 10, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234, operator = @0x345)] + public entry fun test_commission_percentage_change( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + operator: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let operator_address = signer::address_of(operator); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address, operator_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + assert!(operator_commission_percentage(contract_address) == 0, 0); + let stake_pool_address = stake_pool_address(contract_address); + + // 10% commission will be paid to the operator. + update_operator(admin, contract_address, operator_address, 10); + + // Operator needs to join the validator set for the stake pool to earn rewards. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator, stake_pool_address, true); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, 0); + assert!(get_accumulated_rewards(contract_address) == 0, 0); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Stake pool earns some rewards. + stake::end_epoch(); + let (_, accumulated_rewards, _) = staking_contract::staking_contract_amounts( + contract_address, + operator_address + ); + + // Update commission percentage to 20%. This also immediately requests commission. + update_commission_percentage(admin, contract_address, 20); + // Assert that the operator is still the same, and the commission percentage is updated to 20%. + assert!(operator(contract_address) == operator_address, 0); + assert!(operator_commission_percentage(contract_address) == 20, 0); + + // Commission is calculated using the previous commission percentage which is 10%. + let expected_commission = accumulated_rewards / 10; + + // Stake pool earns some more rewards. + stake::end_epoch(); + let (_, accumulated_rewards, _) = staking_contract::staking_contract_amounts( + contract_address, + operator_address + ); + + // Request commission again. + staking_contract::request_commission(operator, contract_address, operator_address); + // The commission is calculated using the current commission percentage which is 20%. + expected_commission = with_rewards(expected_commission) + (accumulated_rewards / 5); + + // Unlocks the commission. + stake::fast_forward_to_unlock(stake_pool_address); + expected_commission = with_rewards(expected_commission); + + // Distribute the commission to the operator. + distribute(contract_address); + + // Assert that the operator receives the expected commission. + assert!(coin::balance(operator_address) == expected_commission, 1); + } + + #[test( + aptos_framework = @0x1, + admin = @0x123, + shareholder = @0x234, + operator1 = @0x345, + beneficiary = @0x456, + operator2 = @0x567 + )] + public entry fun test_set_beneficiary_for_operator( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + operator1: &signer, + beneficiary: &signer, + operator2: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let operator_address1 = signer::address_of(operator1); + let operator_address2 = signer::address_of(operator2); + let shareholder_address = signer::address_of(shareholder); + let beneficiary_address = signer::address_of(beneficiary); + setup(aptos_framework, &vector[admin_address, shareholder_address, operator_address1, beneficiary_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + assert!(operator_commission_percentage(contract_address) == 0, 0); + let stake_pool_address = stake_pool_address(contract_address); + // 10% commission will be paid to the operator. + update_operator(admin, contract_address, operator_address1, 10); + assert!(staking_contract::beneficiary_for_operator(operator_address1) == operator_address1, 0); + set_beneficiary_for_operator(operator1, beneficiary_address); + assert!(staking_contract::beneficiary_for_operator(operator_address1) == beneficiary_address, 0); + + // Operator needs to join the validator set for the stake pool to earn rewards. + let (_sk, pk, pop) = stake::generate_identity(); + stake::join_validator_set_for_test(&pk, &pop, operator1, stake_pool_address, true); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, 0); + assert!(get_accumulated_rewards(contract_address) == 0, 0); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Stake pool earns some rewards. + stake::end_epoch(); + let (_, accumulated_rewards, _) = staking_contract::staking_contract_amounts(contract_address, + operator_address1 + ); + // Commission is calculated using the previous commission percentage which is 10%. + let expected_commission = accumulated_rewards / 10; + + // Request commission. + staking_contract::request_commission(operator1, contract_address, operator_address1); + // Unlocks the commission. + stake::fast_forward_to_unlock(stake_pool_address); + expected_commission = with_rewards(expected_commission); + + // Distribute the commission to the operator. + distribute(contract_address); + + // Assert that the beneficiary receives the expected commission. + assert!(coin::balance(operator_address1) == 0, 1); + assert!(coin::balance(beneficiary_address) == expected_commission, 1); + let old_beneficiay_balance = coin::balance(beneficiary_address); + + // switch operator to operator2. The rewards should go to operator2 not to the beneficiay of operator1. + update_operator(admin, contract_address, operator_address2, 10); + + stake::end_epoch(); + let (_, accumulated_rewards, _) = staking_contract::staking_contract_amounts(contract_address, + operator_address2 + ); + + let expected_commission = accumulated_rewards / 10; + + // Request commission. + staking_contract::request_commission(operator2, contract_address, operator_address2); + // Unlocks the commission. + stake::fast_forward_to_unlock(stake_pool_address); + expected_commission = with_rewards(expected_commission); + + // Distribute the commission to the operator. + distribute(contract_address); + + // Assert that the rewards go to operator2, and the balance of the operator1's beneficiay remains the same. + assert!(coin::balance(operator_address2) >= expected_commission, 1); + assert!(coin::balance(beneficiary_address) == old_beneficiay_balance, 1); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + #[expected_failure(abort_code = 0x30008, location = Self)] + public entry fun test_cannot_unlock_rewards_after_contract_is_terminated( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + + // Immediately terminate. Calling unlock_rewards should now fail. + terminate_vesting_contract(admin, contract_address); + unlock_rewards(contract_address); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + public entry fun test_vesting_contract_with_zero_vestings( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract_with_schedule( + admin, + &vector[shareholder_address], + &vector[GRANT_AMOUNT], + admin_address, + 0, + &vector[0, 3, 0, 2], + 48, + ); + let stake_pool_address = stake_pool_address(contract_address); + + // First vest() should unlock 0 according to schedule. + timestamp::update_global_time_for_test_secs(vesting_start_secs(contract_address) + VESTING_PERIOD); + vest(contract_address); + stake::assert_stake_pool(stake_pool_address, GRANT_AMOUNT, 0, 0, 0); + assert!(remaining_grant(contract_address) == GRANT_AMOUNT, 0); + + // Next period should vest 3/48. + timestamp::fast_forward_seconds(VESTING_PERIOD); + vest(contract_address); + let vested_amount = fraction(GRANT_AMOUNT, 3, 48); + let remaining_grant = GRANT_AMOUNT - vested_amount; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, vested_amount); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + + timestamp::fast_forward_seconds(VESTING_PERIOD); + // Distribute the previous vested amount. + distribute(contract_address); + // Next period should vest 0 again. + vest(contract_address); + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, 0); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + + // Next period should vest 2/48. + timestamp::fast_forward_seconds(VESTING_PERIOD); + vest(contract_address); + let vested_amount = fraction(GRANT_AMOUNT, 2, 48); + remaining_grant = remaining_grant - vested_amount; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, vested_amount); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + public entry fun test_last_vest_should_distribute_remaining_amount( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract_with_schedule( + admin, + &vector[shareholder_address], + &vector[GRANT_AMOUNT], + admin_address, + 0, + // First vest = 3/4 but last vest should only be for the remaining 1/4. + &vector[3], + 4, + ); + let stake_pool_address = stake_pool_address(contract_address); + + // First vest is 3/48 + timestamp::update_global_time_for_test_secs(vesting_start_secs(contract_address) + VESTING_PERIOD); + vest(contract_address); + let vested_amount = fraction(GRANT_AMOUNT, 3, 4); + let remaining_grant = GRANT_AMOUNT - vested_amount; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, vested_amount); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + + timestamp::fast_forward_seconds(VESTING_PERIOD); + // Distribute the previous vested amount. + distribute(contract_address); + // Last vest should be the remaining amount (1/4). + vest(contract_address); + let vested_amount = remaining_grant; + remaining_grant = 0; + stake::assert_stake_pool(stake_pool_address, remaining_grant, 0, 0, vested_amount); + assert!(remaining_grant(contract_address) == remaining_grant, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + #[expected_failure(abort_code = 0x30008, location = Self)] + public entry fun test_cannot_vest_after_contract_is_terminated( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + + // Immediately terminate. Calling vest should now fail. + terminate_vesting_contract(admin, contract_address); + vest(contract_address); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + #[expected_failure(abort_code = 0x30008, location = Self)] + public entry fun test_cannot_terminate_twice( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + + // Call terminate_vesting_contract twice should fail. + terminate_vesting_contract(admin, contract_address); + terminate_vesting_contract(admin, contract_address); + } + + #[test(aptos_framework = @0x1, admin = @0x123, shareholder = @0x234)] + #[expected_failure(abort_code = 0x30009, location = Self)] + public entry fun test_cannot_call_admin_withdraw_if_contract_is_not_terminated( + aptos_framework: &signer, + admin: &signer, + shareholder: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + let shareholder_address = signer::address_of(shareholder); + setup(aptos_framework, &vector[admin_address, shareholder_address]); + let contract_address = setup_vesting_contract( + admin, &vector[shareholder_address], &vector[GRANT_AMOUNT], admin_address, 0); + + // Calling admin_withdraw should fail as contract has not been terminated. + admin_withdraw(admin, contract_address); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x60001, location = aptos_framework::aptos_account)] + public entry fun test_set_beneficiary_with_missing_account_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + let contract_address = setup_vesting_contract( + admin, &vector[@1, @2], &vector[GRANT_AMOUNT, GRANT_AMOUNT], admin_address, 0); + set_beneficiary(admin, contract_address, @1, @11); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + #[expected_failure(abort_code = 0x60002, location = aptos_framework::aptos_account)] + public entry fun test_set_beneficiary_with_unregistered_account_should_fail( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + let contract_address = setup_vesting_contract( + admin, &vector[@1, @2], &vector[GRANT_AMOUNT, GRANT_AMOUNT], admin_address, 0); + create_account_for_test(@11); + set_beneficiary(admin, contract_address, @1, @11); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + public entry fun test_set_beneficiary_should_send_distribution( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address, @11]); + let contract_address = setup_vesting_contract( + admin, &vector[@1], &vector[GRANT_AMOUNT], admin_address, 0); + set_beneficiary(admin, contract_address, @1, @11); + assert!(beneficiary(contract_address, @1) == @11, 0); + + // Fast forward to the end of the first period. vest() should now unlock 3/48 of the tokens. + timestamp::update_global_time_for_test_secs(vesting_start_secs(contract_address) + VESTING_PERIOD); + vest(contract_address); + + // Distribution should go to the beneficiary account. + stake::end_epoch(); + // No rewards as validator never joined the validator set. + let vested_amount = fraction(GRANT_AMOUNT, 3, 48); + distribute(contract_address); + let balance = coin::balance(@11); + assert!(balance == vested_amount, balance); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + public entry fun test_set_management_role( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore, VestingAccountManagement, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address]); + let contract_address = setup_vesting_contract( + admin, &vector[@11], &vector[GRANT_AMOUNT], admin_address, 0); + let role = utf8(b"RANDOM"); + set_management_role(admin, contract_address, role, @12); + assert!(get_role_holder(contract_address, role) == @12, 0); + set_management_role(admin, contract_address, role, @13); + assert!(get_role_holder(contract_address, role) == @13, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123)] + public entry fun test_reset_beneficiary( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore, VestingAccountManagement, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address, @11, @12]); + let contract_address = setup_vesting_contract( + admin, &vector[@11], &vector[GRANT_AMOUNT], admin_address, 0); + set_beneficiary(admin, contract_address, @11, @12); + assert!(beneficiary(contract_address, @11) == @12, 0); + + // Fast forward to the end of the first period. vest() should now unlock 3/48 of the tokens. + timestamp::update_global_time_for_test_secs(vesting_start_secs(contract_address) + VESTING_PERIOD); + vest(contract_address); + + // Reset the beneficiary. + reset_beneficiary(admin, contract_address, @11); + + // Distribution should go to the original account. + stake::end_epoch(); + // No rewards as validator never joined the validator set. + let vested_amount = fraction(GRANT_AMOUNT, 3, 48); + distribute(contract_address); + assert!(coin::balance(@11) == vested_amount, 0); + assert!(coin::balance(@12) == 0, 1); + } + + #[test(aptos_framework = @0x1, admin = @0x123, resetter = @0x234)] + public entry fun test_reset_beneficiary_with_resetter_role( + aptos_framework: &signer, + admin: &signer, + resetter: &signer, + ) acquires AdminStore, VestingAccountManagement, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address, @11, @12]); + let contract_address = setup_vesting_contract( + admin, &vector[@11], &vector[GRANT_AMOUNT], admin_address, 0); + set_beneficiary(admin, contract_address, @11, @12); + assert!(beneficiary(contract_address, @11) == @12, 0); + + // Reset the beneficiary with the resetter role. + let resetter_address = signer::address_of(resetter); + set_beneficiary_resetter(admin, contract_address, resetter_address); + assert!(simple_map::length(&borrow_global(contract_address).roles) == 1, 0); + reset_beneficiary(resetter, contract_address, @11); + assert!(beneficiary(contract_address, @11) == @11, 0); + } + + #[test(aptos_framework = @0x1, admin = @0x123, resetter = @0x234, random = @0x345)] + #[expected_failure(abort_code = 0x5000F, location = Self)] + public entry fun test_reset_beneficiary_with_unauthorized( + aptos_framework: &signer, + admin: &signer, + resetter: &signer, + random: &signer, + ) acquires AdminStore, VestingAccountManagement, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address, @11]); + let contract_address = setup_vesting_contract( + admin, &vector[@11], &vector[GRANT_AMOUNT], admin_address, 0); + + // Reset the beneficiary with a random account. This should failed. + set_beneficiary_resetter(admin, contract_address, signer::address_of(resetter)); + reset_beneficiary(random, contract_address, @11); + } + + #[test(aptos_framework = @0x1, admin = @0x123, resetter = @0x234, random = @0x345)] + public entry fun test_shareholder( + aptos_framework: &signer, + admin: &signer, + ) acquires AdminStore, VestingContract { + let admin_address = signer::address_of(admin); + setup(aptos_framework, &vector[admin_address, @11, @12]); + let contract_address = setup_vesting_contract( + admin, &vector[@11], &vector[GRANT_AMOUNT], admin_address, 0); + + // Confirm that the lookup returns the same address when a shareholder is + // passed for which there is no beneficiary. + assert!(shareholder(contract_address, @11) == @11, 0); + + // Set a beneficiary for @11. + set_beneficiary(admin, contract_address, @11, @12); + assert!(beneficiary(contract_address, @11) == @12, 0); + + // Confirm that lookup from beneficiary to shareholder works when a beneficiary + // is set. + assert!(shareholder(contract_address, @12) == @11, 0); + + // Confirm that it returns 0x0 when the address is not in the map. + assert!(shareholder(contract_address, @33) == @0x0, 0); + } + + #[test_only] + fun get_accumulated_rewards(contract_address: address): u64 acquires VestingContract { + let vesting_contract = borrow_global(contract_address); + let (active_stake, _, _, _) = stake::get_stake(vesting_contract.staking.pool_address); + active_stake - vesting_contract.remaining_grant + } + + #[test_only] + fun fraction(total: u64, numerator: u64, denominator: u64): u64 { + fixed_point32::multiply_u64(total, fixed_point32::create_from_rational(numerator, denominator)) + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/voting.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/voting.move new file mode 100644 index 000000000..3bc26528b --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosFramework/voting.move @@ -0,0 +1,1279 @@ +/// +/// This is the general Voting module that can be used as part of a DAO Governance. Voting is designed to be used by +/// standalone governance modules, who has full control over the voting flow and is responsible for voting power +/// calculation and including proper capabilities when creating the proposal so resolution can go through. +/// On-chain governance of the Aptos network also uses Voting. +/// +/// The voting flow: +/// 1. The Voting module can be deployed at a known address (e.g. 0x1 for Aptos on-chain governance) +/// 2. The governance module, e.g. AptosGovernance, can be deployed later and define a GovernanceProposal resource type +/// that can also contain other information such as Capability resource for authorization. +/// 3. The governance module's owner can then register the ProposalType with Voting. This also hosts the proposal list +/// (forum) on the calling account. +/// 4. A proposer, through the governance module, can call Voting::create_proposal to create a proposal. create_proposal +/// cannot be called directly not through the governance module. A script hash of the resolution script that can later +/// be called to execute the proposal is required. +/// 5. A voter, through the governance module, can call Voting::vote on a proposal. vote requires passing a &ProposalType +/// and thus only the governance module that registers ProposalType can call vote. +/// 6. Once the proposal's expiration time has passed and more than the defined threshold has voted yes on the proposal, +/// anyone can call resolve which returns the content of the proposal (of type ProposalType) that can be used to execute. +/// 7. Only the resolution script with the same script hash specified in the proposal can call Voting::resolve as part of +/// the resolution process. +module aptos_framework::voting { + use std::bcs::to_bytes; + use std::error; + use std::option::{Self, Option}; + use std::signer; + use std::string::{String, utf8}; + use std::vector; + + use aptos_std::from_bcs::to_u64; + use aptos_std::simple_map::{Self, SimpleMap}; + use aptos_std::table::{Self, Table}; + use aptos_std::type_info::{Self, TypeInfo}; + + use aptos_framework::account; + use aptos_framework::event::{Self, EventHandle}; + use aptos_framework::timestamp; + use aptos_framework::transaction_context; + use aptos_std::from_bcs; + + /// Current script's execution hash does not match the specified proposal's + const EPROPOSAL_EXECUTION_HASH_NOT_MATCHING: u64 = 1; + /// Proposal cannot be resolved. Either voting duration has not passed, not enough votes, or fewer yes than no votes + const EPROPOSAL_CANNOT_BE_RESOLVED: u64 = 2; + /// Proposal cannot be resolved more than once + const EPROPOSAL_ALREADY_RESOLVED: u64 = 3; + /// Proposal cannot contain an empty execution script hash + const EPROPOSAL_EMPTY_EXECUTION_HASH: u64 = 4; + /// Proposal's voting period has already ended. + const EPROPOSAL_VOTING_ALREADY_ENDED: u64 = 5; + /// Voting forum has already been registered. + const EVOTING_FORUM_ALREADY_REGISTERED: u64 = 6; + /// Minimum vote threshold cannot be higher than early resolution threshold. + const EINVALID_MIN_VOTE_THRESHOLD: u64 = 7; + /// Resolution of a proposal cannot happen atomically in the same transaction as the last vote. + const ERESOLUTION_CANNOT_BE_ATOMIC: u64 = 8; + /// Cannot vote if the specified multi-step proposal is in execution. + const EMULTI_STEP_PROPOSAL_IN_EXECUTION: u64 = 9; + /// If a proposal is multi-step, we need to use `resolve_proposal_v2()` to resolve it. + /// If we use `resolve()` to resolve a multi-step proposal, it will fail with EMULTI_STEP_PROPOSAL_CANNOT_USE_SINGLE_STEP_RESOLVE_FUNCTION. + const EMULTI_STEP_PROPOSAL_CANNOT_USE_SINGLE_STEP_RESOLVE_FUNCTION: u64 = 10; + /// If we call `resolve_proposal_v2()` to resolve a single-step proposal, the `next_execution_hash` parameter should be an empty vector. + const ESINGLE_STEP_PROPOSAL_CANNOT_HAVE_NEXT_EXECUTION_HASH: u64 = 11; + /// Cannot call `is_multi_step_proposal_in_execution()` on single-step proposals. + const EPROPOSAL_IS_SINGLE_STEP: u64 = 12; + + /// ProposalStateEnum representing proposal state. + const PROPOSAL_STATE_PENDING: u64 = 0; + const PROPOSAL_STATE_SUCCEEDED: u64 = 1; + /// Proposal has failed because either the min vote threshold is not met or majority voted no. + const PROPOSAL_STATE_FAILED: u64 = 3; + + /// Key used to track the resolvable time in the proposal's metadata. + const RESOLVABLE_TIME_METADATA_KEY: vector = b"RESOLVABLE_TIME_METADATA_KEY"; + /// Key used to track if the proposal is multi-step + const IS_MULTI_STEP_PROPOSAL_KEY: vector = b"IS_MULTI_STEP_PROPOSAL_KEY"; + /// Key used to track if the multi-step proposal is in execution / resolving in progress. + const IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY: vector = b"IS_MULTI_STEP_PROPOSAL_IN_EXECUTION"; + + /// Extra metadata (e.g. description, code url) can be part of the ProposalType struct. + struct Proposal has store { + /// Required. The address of the proposer. + proposer: address, + + /// Required. Should contain enough information to execute later, for example the required capability. + /// This is stored as an option so we can return it to governance when the proposal is resolved. + execution_content: Option, + + /// Optional. Value is serialized value of an attribute. + /// Currently, we have three attributes that are used by the voting flow. + /// 1. RESOLVABLE_TIME_METADATA_KEY: this is uesed to record the resolvable time to ensure that resolution has to be done non-atomically. + /// 2. IS_MULTI_STEP_PROPOSAL_KEY: this is used to track if a proposal is single-step or multi-step. + /// 3. IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY: this attribute only applies to multi-step proposals. A single-step proposal will not have + /// this field in its metadata map. The value is used to indicate if a multi-step proposal is in execution. If yes, we will disable further + /// voting for this multi-step proposal. + metadata: SimpleMap>, + + /// Timestamp when the proposal was created. + creation_time_secs: u64, + + /// Required. The hash for the execution script module. Only the same exact script module can resolve this + /// proposal. + execution_hash: vector, + + /// A proposal is only resolved if expiration has passed and the number of votes is above threshold. + min_vote_threshold: u128, + expiration_secs: u64, + + /// Optional. Early resolution threshold. If specified, the proposal can be resolved early if the total + /// number of yes or no votes passes this threshold. + /// For example, this can be set to 50% of the total supply of the voting token, so if > 50% vote yes or no, + /// the proposal can be resolved before expiration. + early_resolution_vote_threshold: Option, + + /// Number of votes for each outcome. + /// u128 since the voting power is already u64 and can add up to more than u64 can hold. + yes_votes: u128, + no_votes: u128, + + /// Whether the proposal has been resolved. + is_resolved: bool, + /// Resolution timestamp if the proposal has been resolved. 0 otherwise. + resolution_time_secs: u64, + } + + struct VotingForum has key { + /// Use Table for execution optimization instead of Vector for gas cost since Vector is read entirely into memory + /// during execution while only relevant Table entries are. + proposals: Table>, + events: VotingEvents, + /// Unique identifier for a proposal. This allows for 2 * 10**19 proposals. + next_proposal_id: u64, + } + + struct VotingEvents has store { + create_proposal_events: EventHandle, + register_forum_events: EventHandle, + resolve_proposal_events: EventHandle, + vote_events: EventHandle, + } + + #[event] + struct CreateProposal has drop, store { + proposal_id: u64, + early_resolution_vote_threshold: Option, + execution_hash: vector, + expiration_secs: u64, + metadata: SimpleMap>, + min_vote_threshold: u128, + } + + #[event] + struct RegisterForum has drop, store { + hosting_account: address, + proposal_type_info: TypeInfo, + } + + #[event] + struct Vote has drop, store { + proposal_id: u64, + num_votes: u64, + } + + #[event] + struct ResolveProposal has drop, store { + proposal_id: u64, + yes_votes: u128, + no_votes: u128, + resolved_early: bool + } + + struct CreateProposalEvent has drop, store { + proposal_id: u64, + early_resolution_vote_threshold: Option, + execution_hash: vector, + expiration_secs: u64, + metadata: SimpleMap>, + min_vote_threshold: u128, + } + + struct RegisterForumEvent has drop, store { + hosting_account: address, + proposal_type_info: TypeInfo, + } + + struct VoteEvent has drop, store { + proposal_id: u64, + num_votes: u64, + } + + public fun register(account: &signer) { + let addr = signer::address_of(account); + assert!(!exists>(addr), error::already_exists(EVOTING_FORUM_ALREADY_REGISTERED)); + + let voting_forum = VotingForum { + next_proposal_id: 0, + proposals: table::new>(), + events: VotingEvents { + create_proposal_events: account::new_event_handle(account), + register_forum_events: account::new_event_handle(account), + resolve_proposal_events: account::new_event_handle(account), + vote_events: account::new_event_handle(account), + } + }; + + if (std::features::module_event_migration_enabled()) { + event::emit( + RegisterForum { + hosting_account: addr, + proposal_type_info: type_info::type_of(), + }, + ); + }; + event::emit_event( + &mut voting_forum.events.register_forum_events, + RegisterForumEvent { + hosting_account: addr, + proposal_type_info: type_info::type_of(), + }, + ); + + move_to(account, voting_forum); + } + + /// Create a single-step proposal with the given parameters + /// + /// @param voting_forum_address The forum's address where the proposal will be stored. + /// @param execution_content The execution content that will be given back at resolution time. This can contain + /// data such as a capability resource used to scope the execution. + /// @param execution_hash The hash for the execution script module. Only the same exact script module can resolve + /// this proposal. + /// @param min_vote_threshold The minimum number of votes needed to consider this proposal successful. + /// @param expiration_secs The time in seconds at which the proposal expires and can potentially be resolved. + /// @param early_resolution_vote_threshold The vote threshold for early resolution of this proposal. + /// @param metadata A simple_map that stores information about this proposal. + /// @return The proposal id. + public fun create_proposal( + proposer: address, + voting_forum_address: address, + execution_content: ProposalType, + execution_hash: vector, + min_vote_threshold: u128, + expiration_secs: u64, + early_resolution_vote_threshold: Option, + metadata: SimpleMap>, + ): u64 acquires VotingForum { + create_proposal_v2( + proposer, + voting_forum_address, + execution_content, + execution_hash, + min_vote_threshold, + expiration_secs, + early_resolution_vote_threshold, + metadata, + false + ) + } + + /// Create a single-step or a multi-step proposal with the given parameters + /// + /// @param voting_forum_address The forum's address where the proposal will be stored. + /// @param execution_content The execution content that will be given back at resolution time. This can contain + /// data such as a capability resource used to scope the execution. + /// @param execution_hash The sha-256 hash for the execution script module. Only the same exact script module can + /// resolve this proposal. + /// @param min_vote_threshold The minimum number of votes needed to consider this proposal successful. + /// @param expiration_secs The time in seconds at which the proposal expires and can potentially be resolved. + /// @param early_resolution_vote_threshold The vote threshold for early resolution of this proposal. + /// @param metadata A simple_map that stores information about this proposal. + /// @param is_multi_step_proposal A bool value that indicates if the proposal is single-step or multi-step. + /// @return The proposal id. + public fun create_proposal_v2( + proposer: address, + voting_forum_address: address, + execution_content: ProposalType, + execution_hash: vector, + min_vote_threshold: u128, + expiration_secs: u64, + early_resolution_vote_threshold: Option, + metadata: SimpleMap>, + is_multi_step_proposal: bool, + ): u64 acquires VotingForum { + if (option::is_some(&early_resolution_vote_threshold)) { + assert!( + min_vote_threshold <= *option::borrow(&early_resolution_vote_threshold), + error::invalid_argument(EINVALID_MIN_VOTE_THRESHOLD), + ); + }; + // Make sure the execution script's hash is not empty. + assert!(vector::length(&execution_hash) > 0, error::invalid_argument(EPROPOSAL_EMPTY_EXECUTION_HASH)); + + let voting_forum = borrow_global_mut>(voting_forum_address); + let proposal_id = voting_forum.next_proposal_id; + voting_forum.next_proposal_id = voting_forum.next_proposal_id + 1; + + // Add a flag to indicate if this proposal is single-step or multi-step. + simple_map::add(&mut metadata, utf8(IS_MULTI_STEP_PROPOSAL_KEY), to_bytes(&is_multi_step_proposal)); + + let is_multi_step_in_execution_key = utf8(IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY); + if (is_multi_step_proposal) { + // If the given proposal is a multi-step proposal, we will add a flag to indicate if this multi-step proposal is in execution. + // This value is by default false. We turn this value to true when we start executing the multi-step proposal. This value + // will be used to disable further voting after we started executing the multi-step proposal. + simple_map::add(&mut metadata, is_multi_step_in_execution_key, to_bytes(&false)); + // If the proposal is a single-step proposal, we check if the metadata passed by the client has the IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY key. + // If they have the key, we will remove it, because a single-step proposal that doesn't need this key. + } else if (simple_map::contains_key(&mut metadata, &is_multi_step_in_execution_key)) { + simple_map::remove(&mut metadata, &is_multi_step_in_execution_key); + }; + + table::add(&mut voting_forum.proposals, proposal_id, Proposal { + proposer, + creation_time_secs: timestamp::now_seconds(), + execution_content: option::some(execution_content), + execution_hash, + metadata, + min_vote_threshold, + expiration_secs, + early_resolution_vote_threshold, + yes_votes: 0, + no_votes: 0, + is_resolved: false, + resolution_time_secs: 0, + }); + + if (std::features::module_event_migration_enabled()) { + event::emit( + CreateProposal { + proposal_id, + early_resolution_vote_threshold, + execution_hash, + expiration_secs, + metadata, + min_vote_threshold, + }, + ); + }; + event::emit_event( + &mut voting_forum.events.create_proposal_events, + CreateProposalEvent { + proposal_id, + early_resolution_vote_threshold, + execution_hash, + expiration_secs, + metadata, + min_vote_threshold, + }, + ); + + proposal_id + } + + /// Vote on the given proposal. + /// + /// @param _proof Required so only the governance module that defines ProposalType can initiate voting. + /// This guarantees that voting eligibility and voting power are controlled by the right governance. + /// @param voting_forum_address The address of the forum where the proposals are stored. + /// @param proposal_id The proposal id. + /// @param num_votes Number of votes. Voting power should be calculated by governance. + /// @param should_pass Whether the votes are for yes or no. + public fun vote( + _proof: &ProposalType, + voting_forum_address: address, + proposal_id: u64, + num_votes: u64, + should_pass: bool, + ) acquires VotingForum { + let voting_forum = borrow_global_mut>(voting_forum_address); + let proposal = table::borrow_mut(&mut voting_forum.proposals, proposal_id); + // Voting might still be possible after the proposal has enough yes votes to be resolved early. This would only + // lead to possible proposal resolution failure if the resolve early threshold is not definitive (e.g. < 50% + 1 + // of the total voting token's supply). In this case, more voting might actually still be desirable. + // Governance mechanisms built on this voting module can apply additional rules on when voting is closed as + // appropriate. + assert!(!is_voting_period_over(proposal), error::invalid_state(EPROPOSAL_VOTING_ALREADY_ENDED)); + assert!(!proposal.is_resolved, error::invalid_state(EPROPOSAL_ALREADY_RESOLVED)); + // Assert this proposal is single-step, or if the proposal is multi-step, it is not in execution yet. + assert!(!simple_map::contains_key(&proposal.metadata, &utf8(IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY)) + || *simple_map::borrow(&proposal.metadata, &utf8(IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY)) == to_bytes( + &false + ), + error::invalid_state(EMULTI_STEP_PROPOSAL_IN_EXECUTION)); + + if (should_pass) { + proposal.yes_votes = proposal.yes_votes + (num_votes as u128); + } else { + proposal.no_votes = proposal.no_votes + (num_votes as u128); + }; + + // Record the resolvable time to ensure that resolution has to be done non-atomically. + let timestamp_secs_bytes = to_bytes(×tamp::now_seconds()); + let key = utf8(RESOLVABLE_TIME_METADATA_KEY); + if (simple_map::contains_key(&proposal.metadata, &key)) { + *simple_map::borrow_mut(&mut proposal.metadata, &key) = timestamp_secs_bytes; + } else { + simple_map::add(&mut proposal.metadata, key, timestamp_secs_bytes); + }; + + if (std::features::module_event_migration_enabled()) { + event::emit(Vote { proposal_id, num_votes }); + }; + event::emit_event( + &mut voting_forum.events.vote_events, + VoteEvent { proposal_id, num_votes }, + ); + } + + /// Common checks on if a proposal is resolvable, regardless if the proposal is single-step or multi-step. + fun is_proposal_resolvable( + voting_forum_address: address, + proposal_id: u64, + ) acquires VotingForum { + let proposal_state = get_proposal_state(voting_forum_address, proposal_id); + assert!(proposal_state == PROPOSAL_STATE_SUCCEEDED, error::invalid_state(EPROPOSAL_CANNOT_BE_RESOLVED)); + + let voting_forum = borrow_global_mut>(voting_forum_address); + let proposal = table::borrow_mut(&mut voting_forum.proposals, proposal_id); + assert!(!proposal.is_resolved, error::invalid_state(EPROPOSAL_ALREADY_RESOLVED)); + + // We need to make sure that the resolution is happening in + // a separate transaction from the last vote to guard against any potential flashloan attacks. + let resolvable_time = to_u64(*simple_map::borrow(&proposal.metadata, &utf8(RESOLVABLE_TIME_METADATA_KEY))); + assert!(timestamp::now_seconds() > resolvable_time, error::invalid_state(ERESOLUTION_CANNOT_BE_ATOMIC)); + + assert!( + transaction_context::get_script_hash() == proposal.execution_hash, + error::invalid_argument(EPROPOSAL_EXECUTION_HASH_NOT_MATCHING), + ); + } + + /// Resolve a single-step proposal with given id. Can only be done if there are at least as many votes as min required and + /// there are more yes votes than no. If either of these conditions is not met, this will revert. + /// + /// @param voting_forum_address The address of the forum where the proposals are stored. + /// @param proposal_id The proposal id. + public fun resolve( + voting_forum_address: address, + proposal_id: u64, + ): ProposalType acquires VotingForum { + is_proposal_resolvable(voting_forum_address, proposal_id); + + let voting_forum = borrow_global_mut>(voting_forum_address); + let proposal = table::borrow_mut(&mut voting_forum.proposals, proposal_id); + + // Assert that the specified proposal is not a multi-step proposal. + let multi_step_key = utf8(IS_MULTI_STEP_PROPOSAL_KEY); + let has_multi_step_key = simple_map::contains_key(&proposal.metadata, &multi_step_key); + if (has_multi_step_key) { + let is_multi_step_proposal = from_bcs::to_bool(*simple_map::borrow(&proposal.metadata, &multi_step_key)); + assert!( + !is_multi_step_proposal, + error::permission_denied(EMULTI_STEP_PROPOSAL_CANNOT_USE_SINGLE_STEP_RESOLVE_FUNCTION) + ); + }; + + let resolved_early = can_be_resolved_early(proposal); + proposal.is_resolved = true; + proposal.resolution_time_secs = timestamp::now_seconds(); + + if (std::features::module_event_migration_enabled()) { + event::emit( + ResolveProposal { + proposal_id, + yes_votes: proposal.yes_votes, + no_votes: proposal.no_votes, + resolved_early, + }, + ); + }; + event::emit_event( + &mut voting_forum.events.resolve_proposal_events, + ResolveProposal { + proposal_id, + yes_votes: proposal.yes_votes, + no_votes: proposal.no_votes, + resolved_early, + }, + ); + + option::extract(&mut proposal.execution_content) + } + + /// Resolve a single-step or a multi-step proposal with the given id. + /// Can only be done if there are at least as many votes as min required and + /// there are more yes votes than no. If either of these conditions is not met, this will revert. + /// + /// + /// @param voting_forum_address The address of the forum where the proposals are stored. + /// @param proposal_id The proposal id. + /// @param next_execution_hash The next execution hash if the given proposal is multi-step. + public fun resolve_proposal_v2( + voting_forum_address: address, + proposal_id: u64, + next_execution_hash: vector, + ) acquires VotingForum { + is_proposal_resolvable(voting_forum_address, proposal_id); + + let voting_forum = borrow_global_mut>(voting_forum_address); + let proposal = table::borrow_mut(&mut voting_forum.proposals, proposal_id); + + // Update the IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY key to indicate that the multi-step proposal is in execution. + let multi_step_in_execution_key = utf8(IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY); + if (simple_map::contains_key(&proposal.metadata, &multi_step_in_execution_key)) { + let is_multi_step_proposal_in_execution_value = simple_map::borrow_mut( + &mut proposal.metadata, + &multi_step_in_execution_key + ); + *is_multi_step_proposal_in_execution_value = to_bytes(&true); + }; + + let multi_step_key = utf8(IS_MULTI_STEP_PROPOSAL_KEY); + let is_multi_step = simple_map::contains_key(&proposal.metadata, &multi_step_key) && from_bcs::to_bool( + *simple_map::borrow(&proposal.metadata, &multi_step_key) + ); + let next_execution_hash_is_empty = vector::length(&next_execution_hash) == 0; + + // Assert that if this proposal is single-step, the `next_execution_hash` parameter is empty. + assert!( + is_multi_step || next_execution_hash_is_empty, + error::invalid_argument(ESINGLE_STEP_PROPOSAL_CANNOT_HAVE_NEXT_EXECUTION_HASH) + ); + + // If the `next_execution_hash` parameter is empty, it means that either + // - this proposal is a single-step proposal, or + // - this proposal is multi-step and we're currently resolving the last step in the multi-step proposal. + // We can mark that this proposal is resolved. + if (next_execution_hash_is_empty) { + proposal.is_resolved = true; + proposal.resolution_time_secs = timestamp::now_seconds(); + + // Set the `IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY` value to false upon successful resolution of the last step of a multi-step proposal. + if (is_multi_step) { + let is_multi_step_proposal_in_execution_value = simple_map::borrow_mut( + &mut proposal.metadata, + &multi_step_in_execution_key + ); + *is_multi_step_proposal_in_execution_value = to_bytes(&false); + }; + } else { + // If the current step is not the last step, + // update the proposal's execution hash on-chain to the execution hash of the next step. + proposal.execution_hash = next_execution_hash; + }; + + // For single-step proposals, we emit one `ResolveProposal` event per proposal. + // For multi-step proposals, we emit one `ResolveProposal` event per step in the multi-step proposal. This means + // that we emit multiple `ResolveProposal` events for the same multi-step proposal. + let resolved_early = can_be_resolved_early(proposal); + if (std::features::module_event_migration_enabled()) { + event::emit( + ResolveProposal { + proposal_id, + yes_votes: proposal.yes_votes, + no_votes: proposal.no_votes, + resolved_early, + }, + ); + }; + event::emit_event( + &mut voting_forum.events.resolve_proposal_events, + ResolveProposal { + proposal_id, + yes_votes: proposal.yes_votes, + no_votes: proposal.no_votes, + resolved_early, + }, + ); + + } + + #[view] + /// Return the next unassigned proposal id + public fun next_proposal_id(voting_forum_address: address, ): u64 acquires VotingForum { + let voting_forum = borrow_global>(voting_forum_address); + voting_forum.next_proposal_id + } + + #[view] + public fun get_proposer( + voting_forum_address: address, + proposal_id: u64 + ): address acquires VotingForum { + let proposal = get_proposal(voting_forum_address, proposal_id); + proposal.proposer + } + + #[view] + public fun is_voting_closed( + voting_forum_address: address, + proposal_id: u64 + ): bool acquires VotingForum { + let proposal = get_proposal(voting_forum_address, proposal_id); + can_be_resolved_early(proposal) || is_voting_period_over(proposal) + } + + /// Return true if the proposal has reached early resolution threshold (if specified). + public fun can_be_resolved_early(proposal: &Proposal): bool { + if (option::is_some(&proposal.early_resolution_vote_threshold)) { + let early_resolution_threshold = *option::borrow(&proposal.early_resolution_vote_threshold); + if (proposal.yes_votes >= early_resolution_threshold || proposal.no_votes >= early_resolution_threshold) { + return true + }; + }; + false + } + + #[view] + public fun get_proposal_metadata( + voting_forum_address: address, + proposal_id: u64, + ): SimpleMap> acquires VotingForum { + let proposal = get_proposal(voting_forum_address, proposal_id); + proposal.metadata + } + + #[view] + public fun get_proposal_metadata_value( + voting_forum_address: address, + proposal_id: u64, + metadata_key: String, + ): vector acquires VotingForum { + let proposal = get_proposal(voting_forum_address, proposal_id); + *simple_map::borrow(&proposal.metadata, &metadata_key) + } + + #[view] + /// Return the state of the proposal with given id. + /// + /// @param voting_forum_address The address of the forum where the proposals are stored. + /// @param proposal_id The proposal id. + /// @return Proposal state as an enum value. + public fun get_proposal_state( + voting_forum_address: address, + proposal_id: u64, + ): u64 acquires VotingForum { + if (is_voting_closed(voting_forum_address, proposal_id)) { + let proposal = get_proposal(voting_forum_address, proposal_id); + let yes_votes = proposal.yes_votes; + let no_votes = proposal.no_votes; + + if (yes_votes > no_votes && yes_votes + no_votes >= proposal.min_vote_threshold) { + PROPOSAL_STATE_SUCCEEDED + } else { + PROPOSAL_STATE_FAILED + } + } else { + PROPOSAL_STATE_PENDING + } + } + + #[view] + /// Return the proposal's creation time. + public fun get_proposal_creation_secs( + voting_forum_address: address, + proposal_id: u64, + ): u64 acquires VotingForum { + let proposal = get_proposal(voting_forum_address, proposal_id); + proposal.creation_time_secs + } + + #[view] + /// Return the proposal's expiration time. + public fun get_proposal_expiration_secs( + voting_forum_address: address, + proposal_id: u64, + ): u64 acquires VotingForum { + let proposal = get_proposal(voting_forum_address, proposal_id); + proposal.expiration_secs + } + + #[view] + /// Return the proposal's execution hash. + public fun get_execution_hash( + voting_forum_address: address, + proposal_id: u64, + ): vector acquires VotingForum { + let proposal = get_proposal(voting_forum_address, proposal_id); + proposal.execution_hash + } + + #[view] + /// Return the proposal's minimum vote threshold + public fun get_min_vote_threshold( + voting_forum_address: address, + proposal_id: u64, + ): u128 acquires VotingForum { + let proposal = get_proposal(voting_forum_address, proposal_id); + proposal.min_vote_threshold + } + + #[view] + /// Return the proposal's early resolution minimum vote threshold (optionally set) + public fun get_early_resolution_vote_threshold( + voting_forum_address: address, + proposal_id: u64, + ): Option acquires VotingForum { + let proposal = get_proposal(voting_forum_address, proposal_id); + proposal.early_resolution_vote_threshold + } + + #[view] + /// Return the proposal's current vote count (yes_votes, no_votes) + public fun get_votes( + voting_forum_address: address, + proposal_id: u64, + ): (u128, u128) acquires VotingForum { + let proposal = get_proposal(voting_forum_address, proposal_id); + (proposal.yes_votes, proposal.no_votes) + } + + #[view] + /// Return true if the governance proposal has already been resolved. + public fun is_resolved( + voting_forum_address: address, + proposal_id: u64, + ): bool acquires VotingForum { + let proposal = get_proposal(voting_forum_address, proposal_id); + proposal.is_resolved + } + + #[view] + public fun get_resolution_time_secs( + voting_forum_address: address, + proposal_id: u64, + ): u64 acquires VotingForum { + let proposal = get_proposal(voting_forum_address, proposal_id); + proposal.resolution_time_secs + } + + #[view] + /// Return true if the multi-step governance proposal is in execution. + public fun is_multi_step_proposal_in_execution( + voting_forum_address: address, + proposal_id: u64, + ): bool acquires VotingForum { + let voting_forum = borrow_global>(voting_forum_address); + let proposal = table::borrow(&voting_forum.proposals, proposal_id); + let is_multi_step_in_execution_key = utf8(IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY); + assert!( + simple_map::contains_key(&proposal.metadata, &is_multi_step_in_execution_key), + error::invalid_argument(EPROPOSAL_IS_SINGLE_STEP) + ); + from_bcs::to_bool(*simple_map::borrow(&proposal.metadata, &is_multi_step_in_execution_key)) + } + + /// Return true if the voting period of the given proposal has already ended. + fun is_voting_period_over(proposal: &Proposal): bool { + timestamp::now_seconds() > proposal.expiration_secs + } + + inline fun get_proposal( + voting_forum_address: address, + proposal_id: u64, + ): &Proposal acquires VotingForum { + let voting_forum = borrow_global>(voting_forum_address); + table::borrow(&voting_forum.proposals, proposal_id) + } + + #[test_only] + struct TestProposal has store {} + + #[test_only] + const VOTING_DURATION_SECS: u64 = 100000; + + #[test_only] + public fun create_test_proposal_generic( + governance: &signer, + early_resolution_threshold: Option, + use_generic_create_proposal_function: bool, + ): u64 acquires VotingForum { + // Register voting forum and create a proposal. + register(governance); + let governance_address = signer::address_of(governance); + let proposal = TestProposal {}; + + // This works because our Move unit test extensions mock out the execution hash to be [1]. + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + let metadata = simple_map::create>(); + + if (use_generic_create_proposal_function) { + create_proposal_v2( + governance_address, + governance_address, + proposal, + execution_hash, + 10, + timestamp::now_seconds() + VOTING_DURATION_SECS, + early_resolution_threshold, + metadata, + use_generic_create_proposal_function + ) + } else { + create_proposal( + governance_address, + governance_address, + proposal, + execution_hash, + 10, + timestamp::now_seconds() + VOTING_DURATION_SECS, + early_resolution_threshold, + metadata, + ) + } + } + + #[test_only] + public fun resolve_proposal_for_test( + voting_forum_address: address, + proposal_id: u64, + is_multi_step: bool, + finish_multi_step_execution: bool + ) acquires VotingForum { + if (is_multi_step) { + let execution_hash = vector::empty(); + vector::push_back(&mut execution_hash, 1); + resolve_proposal_v2(voting_forum_address, proposal_id, execution_hash); + + if (finish_multi_step_execution) { + resolve_proposal_v2(voting_forum_address, proposal_id, vector::empty()); + }; + } else { + let proposal = resolve(voting_forum_address, proposal_id); + let TestProposal {} = proposal; + }; + } + + #[test_only] + public fun create_test_proposal( + governance: &signer, + early_resolution_threshold: Option, + ): u64 acquires VotingForum { + create_test_proposal_generic(governance, early_resolution_threshold, false) + } + + #[test_only] + public fun create_proposal_with_empty_execution_hash_should_fail_generic( + governance: &signer, + is_multi_step: bool + ) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + register(governance); + let proposal = TestProposal {}; + + // This should fail because execution hash is empty. + if (is_multi_step) { + create_proposal_v2( + governance_address, + governance_address, + proposal, + b"", + 10, + 100000, + option::none(), + simple_map::create>(), + is_multi_step + ); + } else { + create_proposal( + governance_address, + governance_address, + proposal, + b"", + 10, + 100000, + option::none(), + simple_map::create>(), + ); + }; + } + + #[test(governance = @0x123)] + #[expected_failure(abort_code = 0x10004, location = Self)] + public fun create_proposal_with_empty_execution_hash_should_fail(governance: &signer) acquires VotingForum { + create_proposal_with_empty_execution_hash_should_fail_generic(governance, false); + } + + #[test(governance = @0x123)] + #[expected_failure(abort_code = 0x10004, location = Self)] + public fun create_proposal_with_empty_execution_hash_should_fail_multi_step( + governance: &signer + ) acquires VotingForum { + create_proposal_with_empty_execution_hash_should_fail_generic(governance, true); + } + + #[test_only] + public entry fun test_voting_passed_generic( + aptos_framework: &signer, + governance: &signer, + use_create_multi_step: bool, + use_resolve_multi_step: bool + ) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + + // Register voting forum and create a proposal. + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(governance, option::none(), use_create_multi_step); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_PENDING, 0); + + // Vote. + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 10, true); + let TestProposal {} = proof; + + // Resolve. + timestamp::fast_forward_seconds(VOTING_DURATION_SECS + 1); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_SUCCEEDED, 1); + + // This if statement is specifically for the test `test_voting_passed_single_step_can_use_generic_function()`. + // It's testing when we have a single-step proposal that was created by the single-step `create_proposal()`, + // we should be able to successfully resolve it using the generic `resolve_proposal_v2` function. + if (!use_create_multi_step && use_resolve_multi_step) { + resolve_proposal_v2(governance_address, proposal_id, vector::empty()); + } else { + resolve_proposal_for_test(governance_address, proposal_id, use_resolve_multi_step, true); + }; + let voting_forum = borrow_global>(governance_address); + assert!(table::borrow(&voting_forum.proposals, proposal_id).is_resolved, 2); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + public entry fun test_voting_passed(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_passed_generic(aptos_framework, governance, false, false); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + public entry fun test_voting_passed_multi_step(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_passed_generic(aptos_framework, governance, true, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x5000a, location = Self)] + public entry fun test_voting_passed_multi_step_cannot_use_single_step_resolve_function( + aptos_framework: &signer, + governance: &signer + ) acquires VotingForum { + test_voting_passed_generic(aptos_framework, governance, true, false); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + public entry fun test_voting_passed_single_step_can_use_generic_function( + aptos_framework: &signer, + governance: &signer + ) acquires VotingForum { + test_voting_passed_generic(aptos_framework, governance, false, true); + } + + #[test_only] + public entry fun test_cannot_resolve_twice_generic( + aptos_framework: &signer, + governance: &signer, + is_multi_step: bool + ) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + + // Register voting forum and create a proposal. + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(governance, option::none(), is_multi_step); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_PENDING, 0); + + // Vote. + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 10, true); + let TestProposal {} = proof; + + // Resolve. + timestamp::fast_forward_seconds(VOTING_DURATION_SECS + 1); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_SUCCEEDED, 1); + resolve_proposal_for_test(governance_address, proposal_id, is_multi_step, true); + resolve_proposal_for_test(governance_address, proposal_id, is_multi_step, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30003, location = Self)] + public entry fun test_cannot_resolve_twice(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_cannot_resolve_twice_generic(aptos_framework, governance, false); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30003, location = Self)] + public entry fun test_cannot_resolve_twice_multi_step( + aptos_framework: &signer, + governance: &signer + ) acquires VotingForum { + test_cannot_resolve_twice_generic(aptos_framework, governance, true); + } + + #[test_only] + public entry fun test_voting_passed_early_generic( + aptos_framework: &signer, + governance: &signer, + is_multi_step: bool + ) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + + // Register voting forum and create a proposal. + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(governance, option::some(100), is_multi_step); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_PENDING, 0); + + // Assert that IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY has value `false` in proposal.metadata. + if (is_multi_step) { + assert!(!is_multi_step_proposal_in_execution(governance_address, 0), 1); + }; + + // Vote. + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 100, true); + vote(&proof, governance_address, proposal_id, 10, false); + let TestProposal {} = proof; + + // Resolve early. Need to increase timestamp as resolution cannot happen in the same tx. + timestamp::fast_forward_seconds(1); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_SUCCEEDED, 2); + + if (is_multi_step) { + // Assert that IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY still has value `false` in proposal.metadata before execution. + assert!(!is_multi_step_proposal_in_execution(governance_address, 0), 3); + resolve_proposal_for_test(governance_address, proposal_id, is_multi_step, false); + + // Assert that the multi-step proposal is in execution but not resolved yet. + assert!(is_multi_step_proposal_in_execution(governance_address, 0), 4); + let voting_forum = borrow_global_mut>(governance_address); + let proposal = table::borrow_mut(&mut voting_forum.proposals, proposal_id); + assert!(!proposal.is_resolved, 5); + }; + + resolve_proposal_for_test(governance_address, proposal_id, is_multi_step, true); + let voting_forum = borrow_global_mut>(governance_address); + assert!(table::borrow(&voting_forum.proposals, proposal_id).is_resolved, 6); + + // Assert that the IS_MULTI_STEP_PROPOSAL_IN_EXECUTION_KEY value is set back to `false` upon successful resolution of this multi-step proposal. + if (is_multi_step) { + assert!(!is_multi_step_proposal_in_execution(governance_address, 0), 7); + }; + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + public entry fun test_voting_passed_early(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_passed_early_generic(aptos_framework, governance, false); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + public entry fun test_voting_passed_early_multi_step( + aptos_framework: &signer, + governance: &signer + ) acquires VotingForum { + test_voting_passed_early_generic(aptos_framework, governance, true); + } + + #[test_only] + public entry fun test_voting_passed_early_in_same_tx_should_fail_generic( + aptos_framework: &signer, + governance: &signer, + is_multi_step: bool + ) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(governance, option::some(100), is_multi_step); + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 40, true); + vote(&proof, governance_address, proposal_id, 60, true); + let TestProposal {} = proof; + + // Resolving early should fail since timestamp hasn't changed since the last vote. + resolve_proposal_for_test(governance_address, proposal_id, is_multi_step, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30008, location = Self)] + public entry fun test_voting_passed_early_in_same_tx_should_fail( + aptos_framework: &signer, + governance: &signer + ) acquires VotingForum { + test_voting_passed_early_in_same_tx_should_fail_generic(aptos_framework, governance, false); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30008, location = Self)] + public entry fun test_voting_passed_early_in_same_tx_should_fail_multi_step( + aptos_framework: &signer, + governance: &signer + ) acquires VotingForum { + test_voting_passed_early_in_same_tx_should_fail_generic(aptos_framework, governance, true); + } + + #[test_only] + public entry fun test_voting_failed_generic( + aptos_framework: &signer, + governance: &signer, + is_multi_step: bool + ) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + + // Register voting forum and create a proposal. + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(governance, option::none(), is_multi_step); + + // Vote. + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 10, true); + vote(&proof, governance_address, proposal_id, 100, false); + let TestProposal {} = proof; + + // Resolve. + timestamp::fast_forward_seconds(VOTING_DURATION_SECS + 1); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_FAILED, 1); + resolve_proposal_for_test(governance_address, proposal_id, is_multi_step, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30002, location = Self)] + public entry fun test_voting_failed(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_failed_generic(aptos_framework, governance, false); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30002, location = Self)] + public entry fun test_voting_failed_multi_step(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_failed_generic(aptos_framework, governance, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30005, location = Self)] + public entry fun test_cannot_vote_after_voting_period_is_over( + aptos_framework: signer, + governance: signer + ) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(&aptos_framework); + let governance_address = signer::address_of(&governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal(&governance, option::none()); + // Voting period is over. Voting should now fail. + timestamp::fast_forward_seconds(VOTING_DURATION_SECS + 1); + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 10, true); + let TestProposal {} = proof; + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30009, location = Self)] + public entry fun test_cannot_vote_after_multi_step_proposal_starts_executing( + aptos_framework: signer, + governance: signer + ) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(&aptos_framework); + + // Register voting forum and create a proposal. + let governance_address = signer::address_of(&governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(&governance, option::some(100), true); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_PENDING, 0); + + // Vote. + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 100, true); + + // Resolve early. + timestamp::fast_forward_seconds(1); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_SUCCEEDED, 1); + resolve_proposal_for_test(governance_address, proposal_id, true, false); + vote(&proof, governance_address, proposal_id, 100, false); + let TestProposal {} = proof; + } + + #[test_only] + public entry fun test_voting_failed_early_generic( + aptos_framework: &signer, + governance: &signer, + is_multi_step: bool + ) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + + // Register voting forum and create a proposal. + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(governance, option::some(100), is_multi_step); + + // Vote. + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 100, true); + vote(&proof, governance_address, proposal_id, 100, false); + let TestProposal {} = proof; + + // Resolve. + timestamp::fast_forward_seconds(VOTING_DURATION_SECS + 1); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_FAILED, 1); + resolve_proposal_for_test(governance_address, proposal_id, is_multi_step, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30002, location = Self)] + public entry fun test_voting_failed_early(aptos_framework: &signer, governance: &signer) acquires VotingForum { + test_voting_failed_early_generic(aptos_framework, governance, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x30002, location = Self)] + public entry fun test_voting_failed_early_multi_step( + aptos_framework: &signer, + governance: &signer + ) acquires VotingForum { + test_voting_failed_early_generic(aptos_framework, governance, false); + } + + #[test_only] + public entry fun test_cannot_set_min_threshold_higher_than_early_resolution_generic( + aptos_framework: &signer, + governance: &signer, + is_multi_step: bool, + ) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + account::create_account_for_test(signer::address_of(governance)); + // This should fail. + create_test_proposal_generic(governance, option::some(5), is_multi_step); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_cannot_set_min_threshold_higher_than_early_resolution( + aptos_framework: &signer, + governance: &signer, + ) acquires VotingForum { + test_cannot_set_min_threshold_higher_than_early_resolution_generic(aptos_framework, governance, false); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + #[expected_failure(abort_code = 0x10007, location = Self)] + public entry fun test_cannot_set_min_threshold_higher_than_early_resolution_multi_step( + aptos_framework: &signer, + governance: &signer, + ) acquires VotingForum { + test_cannot_set_min_threshold_higher_than_early_resolution_generic(aptos_framework, governance, true); + } + + #[test(aptos_framework = @aptos_framework, governance = @0x123)] + public entry fun test_replace_execution_hash(aptos_framework: &signer, governance: &signer) acquires VotingForum { + account::create_account_for_test(@aptos_framework); + timestamp::set_time_has_started_for_testing(aptos_framework); + + // Register voting forum and create a proposal. + let governance_address = signer::address_of(governance); + account::create_account_for_test(governance_address); + let proposal_id = create_test_proposal_generic(governance, option::none(), true); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_PENDING, 0); + + // Vote. + let proof = TestProposal {}; + vote(&proof, governance_address, proposal_id, 10, true); + let TestProposal {} = proof; + + // Resolve. + timestamp::fast_forward_seconds(VOTING_DURATION_SECS + 1); + assert!(get_proposal_state(governance_address, proposal_id) == PROPOSAL_STATE_SUCCEEDED, 1); + + resolve_proposal_v2(governance_address, proposal_id, vector[10u8]); + let voting_forum = borrow_global>(governance_address); + let proposal = table::borrow(&voting_forum.proposals, 0); + assert!(proposal.execution_hash == vector[10u8], 2); + assert!(!table::borrow(&voting_forum.proposals, proposal_id).is_resolved, 3); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/any.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/any.move new file mode 100644 index 000000000..d2851b77f --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/any.move @@ -0,0 +1,57 @@ +module aptos_std::any { + use aptos_std::type_info; + use aptos_std::from_bcs::from_bytes; + use std::bcs::to_bytes; + use std::error; + use std::string::String; + + friend aptos_std::copyable_any; + + /// The type provided for `unpack` is not the same as was given for `pack`. + const ETYPE_MISMATCH: u64 = 1; + + /// A type which can represent a value of any type. This allows for representation of 'unknown' future + /// values. For example, to define a resource such that it can be later be extended without breaking + /// changes one can do + /// + /// ```move + /// struct Resource { + /// field: Type, + /// ... + /// extension: Option + /// } + /// ``` + struct Any has drop, store { + type_name: String, + data: vector + } + + /// Pack a value into the `Any` representation. Because Any can be stored and dropped, this is + /// also required from `T`. + public fun pack(x: T): Any { + Any { + type_name: type_info::type_name(), + data: to_bytes(&x) + } + } + + /// Unpack a value from the `Any` representation. This aborts if the value has not the expected type `T`. + public fun unpack(x: Any): T { + assert!(type_info::type_name() == x.type_name, error::invalid_argument(ETYPE_MISMATCH)); + from_bytes(x.data) + } + + /// Returns the type name of this Any + public fun type_name(x: &Any): &String { + &x.type_name + } + + #[test_only] + struct S has store, drop { x: u64 } + + #[test] + fun test_any() { + assert!(unpack(pack(22)) == 22, 1); + assert!(unpack(pack(S { x: 22 })) == S { x: 22 }, 2); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/aptos_hash.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/aptos_hash.move new file mode 100644 index 000000000..532fa736e --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/aptos_hash.move @@ -0,0 +1,253 @@ +/// Cryptographic hashes: +/// - Keccak-256: see https://keccak.team/keccak.html +/// +/// In addition, SHA2-256 and SHA3-256 are available in `std::hash`. Note that SHA3-256 is a variant of Keccak: it is +/// NOT the same as Keccak-256. +/// +/// Non-cryptograhic hashes: +/// - SipHash: an add-rotate-xor (ARX) based family of pseudorandom functions created by Jean-Philippe Aumasson and Daniel J. Bernstein in 2012 +module aptos_std::aptos_hash { + use std::bcs; + use std::features; + + // + // Constants + // + + /// A newly-added native function is not yet enabled. + const E_NATIVE_FUN_NOT_AVAILABLE: u64 = 1; + + // + // Functions + // + + /// Returns the (non-cryptographic) SipHash of `bytes`. See https://en.wikipedia.org/wiki/SipHash + native public fun sip_hash(bytes: vector): u64; + + /// Returns the (non-cryptographic) SipHash of the BCS serialization of `v`. See https://en.wikipedia.org/wiki/SipHash + public fun sip_hash_from_value(v: &MoveValue): u64 { + let bytes = bcs::to_bytes(v); + + sip_hash(bytes) + } + + /// Returns the Keccak-256 hash of `bytes`. + native public fun keccak256(bytes: vector): vector; + + /// Returns the SHA2-512 hash of `bytes`. + public fun sha2_512(bytes: vector): vector { + if(!features::sha_512_and_ripemd_160_enabled()) { + abort(std::error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + sha2_512_internal(bytes) + } + + /// Returns the SHA3-512 hash of `bytes`. + public fun sha3_512(bytes: vector): vector { + if(!features::sha_512_and_ripemd_160_enabled()) { + abort(std::error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + sha3_512_internal(bytes) + } + + + /// Returns the RIPEMD-160 hash of `bytes`. + /// + /// WARNING: Only 80-bit security is provided by this function. This means an adversary who can compute roughly 2^80 + /// hashes will, with high probability, find a collision x_1 != x_2 such that RIPEMD-160(x_1) = RIPEMD-160(x_2). + public fun ripemd160(bytes: vector): vector { + if(!features::sha_512_and_ripemd_160_enabled()) { + abort(std::error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + ripemd160_internal(bytes) + } + + /// Returns the BLAKE2B-256 hash of `bytes`. + public fun blake2b_256(bytes: vector): vector { + if(!features::blake2b_256_enabled()) { + abort(std::error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + blake2b_256_internal(bytes) + } + + // + // Private native functions + // + + /// Returns the SHA2-512 hash of `bytes`. + native fun sha2_512_internal(bytes: vector): vector; + + + /// Returns the SHA3-512 hash of `bytes`. + native fun sha3_512_internal(bytes: vector): vector; + + /// Returns the RIPEMD-160 hash of `bytes`. + /// + /// WARNING: Only 80-bit security is provided by this function. This means an adversary who can compute roughly 2^80 + /// hashes will, with high probability, find a collision x_1 != x_2 such that RIPEMD-160(x_1) = RIPEMD-160(x_2). + native fun ripemd160_internal(bytes: vector): vector; + + /// Returns the BLAKE2B-256 hash of `bytes`. + native fun blake2b_256_internal(bytes: vector): vector; + + // + // Testing + // + + #[test] + fun keccak256_test() { + let inputs = vector[ + b"testing", + b"", + ]; + + let outputs = vector[ + x"5f16f4c7f149ac4f9510d9cf8cf384038ad348b3bcdc01915f95de12df9d1b02", + x"c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470", + ]; + + let i = 0; + while (i < std::vector::length(&inputs)) { + let input = *std::vector::borrow(&inputs, i); + let hash_expected = *std::vector::borrow(&outputs, i); + let hash = keccak256(input); + + assert!(hash_expected == hash, 1); + + i = i + 1; + }; + } + + #[test(fx = @aptos_std)] + fun sha2_512_test(fx: signer) { + // We need to enable the feature in order for the native call to be allowed. + features::change_feature_flags_for_testing(&fx, vector[features::get_sha_512_and_ripemd_160_feature()], vector[]); + + let inputs = vector[ + b"testing", + b"", + ]; + + // From https://emn178.github.io/online-tools/sha512.html + let outputs = vector[ + x"521b9ccefbcd14d179e7a1bb877752870a6d620938b28a66a107eac6e6805b9d0989f45b5730508041aa5e710847d439ea74cd312c9355f1f2dae08d40e41d50", + x"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", + ]; + + let i = 0; + while (i < std::vector::length(&inputs)) { + let input = *std::vector::borrow(&inputs, i); + let hash_expected = *std::vector::borrow(&outputs, i); + let hash = sha2_512(input); + + assert!(hash_expected == hash, 1); + + i = i + 1; + }; + } + + #[test(fx = @aptos_std)] + fun sha3_512_test(fx: signer) { + // We need to enable the feature in order for the native call to be allowed. + features::change_feature_flags_for_testing(&fx, vector[features::get_sha_512_and_ripemd_160_feature()], vector[]); + let inputs = vector[ + b"testing", + b"", + ]; + + // From https://emn178.github.io/online-tools/sha3_512.html + let outputs = vector[ + x"881c7d6ba98678bcd96e253086c4048c3ea15306d0d13ff48341c6285ee71102a47b6f16e20e4d65c0c3d677be689dfda6d326695609cbadfafa1800e9eb7fc1", + x"a69f73cca23a9ac5c8b567dc185a756e97c982164fe25859e0d1dcc1475c80a615b2123af1f5f94c11e3e9402c3ac558f500199d95b6d3e301758586281dcd26", + ]; + + let i = 0; + while (i < std::vector::length(&inputs)) { + let input = *std::vector::borrow(&inputs, i); + let hash_expected = *std::vector::borrow(&outputs, i); + let hash = sha3_512(input); + + assert!(hash_expected == hash, 1); + + i = i + 1; + }; + } + + #[test(fx = @aptos_std)] + fun ripemd160_test(fx: signer) { + // We need to enable the feature in order for the native call to be allowed. + features::change_feature_flags_for_testing(&fx, vector[features::get_sha_512_and_ripemd_160_feature()], vector[]); + let inputs = vector[ + b"testing", + b"", + ]; + + // From https://www.browserling.com/tools/ripemd160-hash + let outputs = vector[ + x"b89ba156b40bed29a5965684b7d244c49a3a769b", + x"9c1185a5c5e9fc54612808977ee8f548b2258d31", + ]; + + let i = 0; + while (i < std::vector::length(&inputs)) { + let input = *std::vector::borrow(&inputs, i); + let hash_expected = *std::vector::borrow(&outputs, i); + let hash = ripemd160(input); + + assert!(hash_expected == hash, 1); + + i = i + 1; + }; + } + + #[test(fx = @aptos_std)] + #[expected_failure(abort_code = 196609, location = Self)] + fun blake2b_256_aborts(fx: signer) { + // We disable the feature to make sure the `blake2b_256` call aborts + features::change_feature_flags_for_testing(&fx, vector[], vector[features::get_blake2b_256_feature()]); + + blake2b_256(b"This will abort"); + } + + #[test(fx = @aptos_std)] + fun blake2b_256_test(fx: signer) { + // We need to enable the feature in order for the native call to be allowed. + features::change_feature_flags_for_testing(&fx, vector[features::get_blake2b_256_feature()], vector[]); + let inputs = vector[ + b"", + b"testing", + b"testing again", // empty message doesn't yield an output on the online generator + ]; + + // From https://www.toolkitbay.com/tkb/tool/BLAKE2b_256 + // + // For computing the hash of an empty string, we use the following Python3 script: + // ``` + // #!/usr/bin/python3 + // + // import hashlib + // + // print(hashlib.blake2b(b'', digest_size=32).hexdigest()); + // ``` + let outputs = vector[ + x"0e5751c026e543b2e8ab2eb06099daa1d1e5df47778f7787faab45cdf12fe3a8", + x"99397ff32ae348b8b6536d5c213f343d7e9fdeaa10e8a23a9f90ab21a1658565", + x"1deab5a4eb7481453ca9b29e1f7c4be8ba44de4faeeafdf173b310cbaecfc84c", + ]; + + let i = 0; + while (i < std::vector::length(&inputs)) { + let input = *std::vector::borrow(&inputs, i); + let hash_expected = *std::vector::borrow(&outputs, i); + let hash = blake2b_256(input); + + assert!(hash_expected == hash, 1); + + i = i + 1; + }; + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/big_vector.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/big_vector.move new file mode 100644 index 000000000..a7eca3973 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/big_vector.move @@ -0,0 +1,469 @@ +module aptos_std::big_vector { + use std::error; + use std::vector; + use aptos_std::table_with_length::{Self, TableWithLength}; + friend aptos_std::smart_vector; + + /// Vector index is out of bounds + const EINDEX_OUT_OF_BOUNDS: u64 = 1; + /// Cannot destroy a non-empty vector + const EVECTOR_NOT_EMPTY: u64 = 2; + /// Cannot pop back from an empty vector + const EVECTOR_EMPTY: u64 = 3; + /// bucket_size cannot be 0 + const EZERO_BUCKET_SIZE: u64 = 4; + + /// A scalable vector implementation based on tables where elements are grouped into buckets. + /// Each bucket has a capacity of `bucket_size` elements. + struct BigVector has store { + buckets: TableWithLength>, + end_index: u64, + bucket_size: u64 + } + + /// Regular Vector API + + /// Create an empty vector. + public(friend) fun empty(bucket_size: u64): BigVector { + assert!(bucket_size > 0, error::invalid_argument(EZERO_BUCKET_SIZE)); + BigVector { + buckets: table_with_length::new(), + end_index: 0, + bucket_size, + } + } + + /// Create a vector of length 1 containing the passed in element. + public(friend) fun singleton(element: T, bucket_size: u64): BigVector { + let v = empty(bucket_size); + push_back(&mut v, element); + v + } + + /// Destroy the vector `v`. + /// Aborts if `v` is not empty. + public fun destroy_empty(v: BigVector) { + assert!(is_empty(&v), error::invalid_argument(EVECTOR_NOT_EMPTY)); + let BigVector { buckets, end_index: _, bucket_size: _ } = v; + table_with_length::destroy_empty(buckets); + } + + /// Destroy the vector `v` if T has `drop` + public fun destroy(v: BigVector) { + let BigVector { buckets, end_index, bucket_size: _ } = v; + let i = 0; + while (end_index > 0) { + let num_elements = vector::length(&table_with_length::remove(&mut buckets, i)); + end_index = end_index - num_elements; + i = i + 1; + }; + table_with_length::destroy_empty(buckets); + } + + /// Acquire an immutable reference to the `i`th element of the vector `v`. + /// Aborts if `i` is out of bounds. + public fun borrow(v: &BigVector, i: u64): &T { + assert!(i < length(v), error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + vector::borrow(table_with_length::borrow(&v.buckets, i / v.bucket_size), i % v.bucket_size) + } + + /// Return a mutable reference to the `i`th element in the vector `v`. + /// Aborts if `i` is out of bounds. + public fun borrow_mut(v: &mut BigVector, i: u64): &mut T { + assert!(i < length(v), error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + vector::borrow_mut(table_with_length::borrow_mut(&mut v.buckets, i / v.bucket_size), i % v.bucket_size) + } + + /// Empty and destroy the other vector, and push each of the elements in the other vector onto the lhs vector in the + /// same order as they occurred in other. + /// Disclaimer: This function is costly. Use it at your own discretion. + public fun append(lhs: &mut BigVector, other: BigVector) { + let other_len = length(&other); + let half_other_len = other_len / 2; + let i = 0; + while (i < half_other_len) { + push_back(lhs, swap_remove(&mut other, i)); + i = i + 1; + }; + while (i < other_len) { + push_back(lhs, pop_back(&mut other)); + i = i + 1; + }; + destroy_empty(other); + } + + /// Add element `val` to the end of the vector `v`. It grows the buckets when the current buckets are full. + /// This operation will cost more gas when it adds new bucket. + public fun push_back(v: &mut BigVector, val: T) { + let num_buckets = table_with_length::length(&v.buckets); + if (v.end_index == num_buckets * v.bucket_size) { + table_with_length::add(&mut v.buckets, num_buckets, vector::empty()); + vector::push_back(table_with_length::borrow_mut(&mut v.buckets, num_buckets), val); + } else { + vector::push_back(table_with_length::borrow_mut(&mut v.buckets, num_buckets - 1), val); + }; + v.end_index = v.end_index + 1; + } + + /// Pop an element from the end of vector `v`. It doesn't shrink the buckets even if they're empty. + /// Call `shrink_to_fit` explicity to deallocate empty buckets. + /// Aborts if `v` is empty. + public fun pop_back(v: &mut BigVector): T { + assert!(!is_empty(v), error::invalid_state(EVECTOR_EMPTY)); + let num_buckets = table_with_length::length(&v.buckets); + let last_bucket = table_with_length::borrow_mut(&mut v.buckets, num_buckets - 1); + let val = vector::pop_back(last_bucket); + // Shrink the table if the last vector is empty. + if (vector::is_empty(last_bucket)) { + move last_bucket; + vector::destroy_empty(table_with_length::remove(&mut v.buckets, num_buckets - 1)); + }; + v.end_index = v.end_index - 1; + val + } + + /// Remove the element at index i in the vector v and return the owned value that was previously stored at i in v. + /// All elements occurring at indices greater than i will be shifted down by 1. Will abort if i is out of bounds. + /// Disclaimer: This function is costly. Use it at your own discretion. + public fun remove(v: &mut BigVector, i: u64): T { + let len = length(v); + assert!(i < len, error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let num_buckets = table_with_length::length(&v.buckets); + let cur_bucket_index = i / v.bucket_size + 1; + let cur_bucket = table_with_length::borrow_mut(&mut v.buckets, cur_bucket_index - 1); + let res = vector::remove(cur_bucket, i % v.bucket_size); + v.end_index = v.end_index - 1; + move cur_bucket; + while ({ + spec { + invariant cur_bucket_index <= num_buckets; + invariant table_with_length::spec_len(v.buckets) == num_buckets; + }; + (cur_bucket_index < num_buckets) + }) { + // remove one element from the start of current vector + let cur_bucket = table_with_length::borrow_mut(&mut v.buckets, cur_bucket_index); + let t = vector::remove(cur_bucket, 0); + move cur_bucket; + // and put it at the end of the last one + let prev_bucket = table_with_length::borrow_mut(&mut v.buckets, cur_bucket_index - 1); + vector::push_back(prev_bucket, t); + cur_bucket_index = cur_bucket_index + 1; + }; + spec { + assert cur_bucket_index == num_buckets; + }; + + // Shrink the table if the last vector is empty. + let last_bucket = table_with_length::borrow_mut(&mut v.buckets, num_buckets - 1); + if (vector::is_empty(last_bucket)) { + move last_bucket; + vector::destroy_empty(table_with_length::remove(&mut v.buckets, num_buckets - 1)); + }; + + res + } + + /// Swap the `i`th element of the vector `v` with the last element and then pop the vector. + /// This is O(1), but does not preserve ordering of elements in the vector. + /// Aborts if `i` is out of bounds. + public fun swap_remove(v: &mut BigVector, i: u64): T { + assert!(i < length(v), error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let last_val = pop_back(v); + // if the requested value is the last one, return it + if (v.end_index == i) { + return last_val + }; + // because the lack of mem::swap, here we swap remove the requested value from the bucket + // and append the last_val to the bucket then swap the last bucket val back + let bucket = table_with_length::borrow_mut(&mut v.buckets, i / v.bucket_size); + let bucket_len = vector::length(bucket); + let val = vector::swap_remove(bucket, i % v.bucket_size); + vector::push_back(bucket, last_val); + vector::swap(bucket, i % v.bucket_size, bucket_len - 1); + val + } + + /// Swap the elements at the i'th and j'th indices in the vector v. Will abort if either of i or j are out of bounds + /// for v. + public fun swap(v: &mut BigVector, i: u64, j: u64) { + assert!(i < length(v) && j < length(v), error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let i_bucket_index = i / v.bucket_size; + let j_bucket_index = j / v.bucket_size; + let i_vector_index = i % v.bucket_size; + let j_vector_index = j % v.bucket_size; + if (i_bucket_index == j_bucket_index) { + vector::swap(table_with_length::borrow_mut(&mut v.buckets, i_bucket_index), i_vector_index, j_vector_index); + return + }; + // If i and j are in different buckets, take the buckets out first for easy mutation. + let bucket_i = table_with_length::remove(&mut v.buckets, i_bucket_index); + let bucket_j = table_with_length::remove(&mut v.buckets, j_bucket_index); + // Get the elements from buckets by calling `swap_remove`. + let element_i = vector::swap_remove(&mut bucket_i, i_vector_index); + let element_j = vector::swap_remove(&mut bucket_j, j_vector_index); + // Swap the elements and push back to the other bucket. + vector::push_back(&mut bucket_i, element_j); + vector::push_back(&mut bucket_j, element_i); + let last_index_in_bucket_i = vector::length(&bucket_i) - 1; + let last_index_in_bucket_j = vector::length(&bucket_j) - 1; + // Re-position the swapped elements to the right index. + vector::swap(&mut bucket_i, i_vector_index, last_index_in_bucket_i); + vector::swap(&mut bucket_j, j_vector_index, last_index_in_bucket_j); + // Add back the buckets. + table_with_length::add(&mut v.buckets, i_bucket_index, bucket_i); + table_with_length::add(&mut v.buckets, j_bucket_index, bucket_j); + } + + /// Reverse the order of the elements in the vector v in-place. + /// Disclaimer: This function is costly. Use it at your own discretion. + public fun reverse(v: &mut BigVector) { + let new_buckets = vector[]; + let push_bucket = vector[]; + let num_buckets = table_with_length::length(&v.buckets); + let num_buckets_left = num_buckets; + + while (num_buckets_left > 0) { + let pop_bucket = table_with_length::remove(&mut v.buckets, num_buckets_left - 1); + vector::for_each_reverse(pop_bucket, |val| { + vector::push_back(&mut push_bucket, val); + if (vector::length(&push_bucket) == v.bucket_size) { + vector::push_back(&mut new_buckets, push_bucket); + push_bucket = vector[]; + }; + }); + num_buckets_left = num_buckets_left - 1; + }; + + if (vector::length(&push_bucket) > 0) { + vector::push_back(&mut new_buckets, push_bucket); + } else { + vector::destroy_empty(push_bucket); + }; + + vector::reverse(&mut new_buckets); + let i = 0; + assert!(table_with_length::length(&v.buckets) == 0, 0); + while (i < num_buckets) { + table_with_length::add(&mut v.buckets, i, vector::pop_back(&mut new_buckets)); + i = i + 1; + }; + vector::destroy_empty(new_buckets); + } + + /// Return the index of the first occurrence of an element in v that is equal to e. Returns (true, index) if such an + /// element was found, and (false, 0) otherwise. + /// Disclaimer: This function is costly. Use it at your own discretion. + public fun index_of(v: &BigVector, val: &T): (bool, u64) { + let num_buckets = table_with_length::length(&v.buckets); + let bucket_index = 0; + while (bucket_index < num_buckets) { + let cur = table_with_length::borrow(&v.buckets, bucket_index); + let (found, i) = vector::index_of(cur, val); + if (found) { + return (true, bucket_index * v.bucket_size + i) + }; + bucket_index = bucket_index + 1; + }; + (false, 0) + } + + /// Return if an element equal to e exists in the vector v. + /// Disclaimer: This function is costly. Use it at your own discretion. + public fun contains(v: &BigVector, val: &T): bool { + if (is_empty(v)) return false; + let (exist, _) = index_of(v, val); + exist + } + + /// Convert a big vector to a native vector, which is supposed to be called mostly by view functions to get an + /// atomic view of the whole vector. + /// Disclaimer: This function may be costly as the big vector may be huge in size. Use it at your own discretion. + public fun to_vector(v: &BigVector): vector { + let res = vector[]; + let num_buckets = table_with_length::length(&v.buckets); + let i = 0; + while (i < num_buckets) { + vector::append(&mut res, *table_with_length::borrow(&v.buckets, i)); + i = i + 1; + }; + res + } + + /// Return the length of the vector. + public fun length(v: &BigVector): u64 { + v.end_index + } + + /// Return `true` if the vector `v` has no elements and `false` otherwise. + public fun is_empty(v: &BigVector): bool { + length(v) == 0 + } + + #[test] + fun big_vector_test() { + let v = empty(5); + let i = 0; + while (i < 100) { + push_back(&mut v, i); + i = i + 1; + }; + let j = 0; + while (j < 100) { + let val = borrow(&v, j); + assert!(*val == j, 0); + j = j + 1; + }; + while (i > 0) { + i = i - 1; + let (exist, index) = index_of(&v, &i); + let j = pop_back(&mut v); + assert!(exist, 0); + assert!(index == i, 0); + assert!(j == i, 0); + }; + while (i < 100) { + push_back(&mut v, i); + i = i + 1; + }; + let last_index = length(&v) - 1; + assert!(swap_remove(&mut v, last_index) == 99, 0); + assert!(swap_remove(&mut v, 0) == 0, 0); + while (length(&v) > 0) { + // the vector is always [N, 1, 2, ... N-1] with repetitive swap_remove(&mut v, 0) + let expected = length(&v); + let val = swap_remove(&mut v, 0); + assert!(val == expected, 0); + }; + destroy_empty(v); + } + + #[test] + fun big_vector_append_edge_case_test() { + let v1 = empty(5); + let v2 = singleton(1u64, 7); + let v3 = empty(6); + let v4 = empty(8); + append(&mut v3, v4); + assert!(length(&v3) == 0, 0); + append(&mut v2, v3); + assert!(length(&v2) == 1, 0); + append(&mut v1, v2); + assert!(length(&v1) == 1, 0); + destroy(v1); + } + + #[test] + fun big_vector_append_test() { + let v1 = empty(5); + let v2 = empty(7); + let i = 0; + while (i < 7) { + push_back(&mut v1, i); + i = i + 1; + }; + while (i < 25) { + push_back(&mut v2, i); + i = i + 1; + }; + append(&mut v1, v2); + assert!(length(&v1) == 25, 0); + i = 0; + while (i < 25) { + assert!(*borrow(&v1, i) == i, 0); + i = i + 1; + }; + destroy(v1); + } + + #[test] + fun big_vector_to_vector_test() { + let v1 = empty(7); + let i = 0; + while (i < 100) { + push_back(&mut v1, i); + i = i + 1; + }; + let v2 = to_vector(&v1); + let j = 0; + while (j < 100) { + assert!(*vector::borrow(&v2, j) == j, 0); + j = j + 1; + }; + destroy(v1); + } + + #[test] + fun big_vector_remove_and_reverse_test() { + let v = empty(11); + let i = 0; + while (i < 101) { + push_back(&mut v, i); + i = i + 1; + }; + remove(&mut v, 100); + remove(&mut v, 90); + remove(&mut v, 80); + remove(&mut v, 70); + remove(&mut v, 60); + remove(&mut v, 50); + remove(&mut v, 40); + remove(&mut v, 30); + remove(&mut v, 20); + remove(&mut v, 10); + remove(&mut v, 0); + assert!(length(&v) == 90, 0); + + let index = 0; + i = 0; + while (i < 101) { + if (i % 10 != 0) { + assert!(*borrow(&v, index) == i, 0); + index = index + 1; + }; + i = i + 1; + }; + destroy(v); + } + + #[test] + fun big_vector_swap_test() { + let v = empty(11); + let i = 0; + while (i < 101) { + push_back(&mut v, i); + i = i + 1; + }; + i = 0; + while (i < 51) { + swap(&mut v, i, 100 - i); + i = i + 1; + }; + i = 0; + while (i < 101) { + assert!(*borrow(&v, i) == 100 - i, 0); + i = i + 1; + }; + destroy(v); + } + + #[test] + fun big_vector_index_of_test() { + let v = empty(11); + let i = 0; + while (i < 100) { + push_back(&mut v, i); + let (found, idx) = index_of(&mut v, &i); + assert!(found && idx == i, 0); + i = i + 1; + }; + destroy(v); + } + + #[test] + fun big_vector_empty_contains() { + let v = empty(10); + assert!(!contains(&v, &(1 as u64)), 0); + destroy_empty(v); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/bls12381.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/bls12381.move new file mode 100644 index 000000000..de7d05ad8 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/bls12381.move @@ -0,0 +1,985 @@ +/// Contains functions for: +/// +/// The minimum-pubkey-size variant of [Boneh-Lynn-Shacham (BLS) signatures](https://en.wikipedia.org/wiki/BLS_digital_signature), +/// where public keys are BLS12-381 elliptic-curve points in $\mathbb{G}_1$ and signatures are in $\mathbb{G}_2$, +/// as per the [IETF BLS draft standard](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-bls-signature#section-2.1). + +module aptos_std::bls12381 { + use std::option::{Self, Option}; + #[test_only] + use std::error::invalid_argument; + + /// The signature size, in bytes + const SIGNATURE_SIZE: u64 = 96; + + /// The public key size, in bytes + const PUBLIC_KEY_NUM_BYTES: u64 = 48; + + /// The caller was supposed to input one or more public keys. + const EZERO_PUBKEYS: u64 = 1; + + /// One of the given inputs has the wrong size.s + const EWRONG_SIZE: u64 = 2; + + /// The number of signers does not match the number of messages to be signed. + const E_NUM_SIGNERS_MUST_EQ_NUM_MESSAGES: u64 = 3; + + // TODO: Performance would increase if structs in this module are implemented natively via handles (similar to Table and + // RistrettoPoint). This will avoid unnecessary (de)serialization. We would need to allow storage of these structs too. + + #[test_only] + struct SecretKey has copy, drop { + bytes: vector, + } + + /// A *validated* public key that: + /// (1) is a point in the prime-order subgroup of the BLS12-381 elliptic curve, and + /// (2) is not the identity point + /// + /// This struct can be used to verify a normal (non-aggregated) signature. + /// + /// This struct can be combined with a ProofOfPossession struct in order to create a PublicKeyWithPop struct, which + /// can be used to verify a multisignature. + struct PublicKey has copy, drop, store { + bytes: vector + } + + /// A proof-of-possession (PoP). + /// Given such a struct and a PublicKey struct, one can construct a PublicKeyWithPoP (see below). + struct ProofOfPossession has copy, drop, store { + bytes: vector + } + + /// A *validated* public key that had a successfully-verified proof-of-possession (PoP). + /// + /// A vector of these structs can be either: + /// (1) used to verify an aggregate signature + /// (2) aggregated with other PublicKeyWithPoP structs into an AggrPublicKeysWithPoP, which in turn can be used + /// to verify a multisignature + struct PublicKeyWithPoP has copy, drop, store { + bytes: vector + } + + /// An aggregation of public keys with verified PoPs, which can be used to verify multisignatures. + struct AggrPublicKeysWithPoP has copy, drop, store { + bytes: vector + } + + /// A BLS signature. This can be either a: + /// (1) normal (non-aggregated) signature + /// (2) signature share (for a multisignature or aggregate signature) + struct Signature has copy, drop, store { + bytes: vector + } + + /// An aggregation of BLS signatures. This can be either a: + /// (4) aggregated signature (i.e., an aggregation of signatures s_i, each on a message m_i) + /// (3) multisignature (i.e., an aggregation of signatures s_i, each on the same message m) + /// + /// We distinguish between a Signature type and a AggrOrMultiSignature type to prevent developers from interchangeably + /// calling `verify_multisignature` and `verify_signature_share` to verify both multisignatures and signature shares, + /// which could create problems down the line. + struct AggrOrMultiSignature has copy, drop, store { + bytes: vector + } + + /// Creates a new public key from a sequence of bytes. + public fun public_key_from_bytes(bytes: vector): Option { + if (validate_pubkey_internal(bytes)) { + option::some(PublicKey { + bytes + }) + } else { + option::none() + } + } + + /// Serializes a public key into 48 bytes. + public fun public_key_to_bytes(pk: &PublicKey): vector { + pk.bytes + } + + /// Creates a new proof-of-possession (PoP) which can be later used to create a PublicKeyWithPoP struct, + public fun proof_of_possession_from_bytes(bytes: vector): ProofOfPossession { + ProofOfPossession { + bytes + } + } + + /// Serializes the signature into 96 bytes. + public fun proof_of_possession_to_bytes(pop: &ProofOfPossession): vector { + pop.bytes + } + + /// Creates a PoP'd public key from a normal public key and a corresponding proof-of-possession. + public fun public_key_from_bytes_with_pop(pk_bytes: vector, pop: &ProofOfPossession): Option { + if (verify_proof_of_possession_internal(pk_bytes, pop.bytes)) { + option::some(PublicKeyWithPoP { + bytes: pk_bytes + }) + } else { + option::none() + } + } + + /// Creates a normal public key from a PoP'd public key. + public fun public_key_with_pop_to_normal(pkpop: &PublicKeyWithPoP): PublicKey { + PublicKey { + bytes: pkpop.bytes + } + } + + /// Serializes a PoP'd public key into 48 bytes. + public fun public_key_with_pop_to_bytes(pk: &PublicKeyWithPoP): vector { + pk.bytes + } + + /// Creates a new signature from a sequence of bytes. Does not check the signature for prime-order subgroup + /// membership since that is done implicitly during verification. + public fun signature_from_bytes(bytes: vector): Signature { + Signature { + bytes + } + } + + /// Serializes the signature into 96 bytes. + public fun signature_to_bytes(sig: &Signature): vector { + sig.bytes + } + + /// Checks that the group element that defines a signature is in the prime-order subgroup. + /// This check is implicitly performed when verifying any signature via this module, but we expose this functionality + /// in case it might be useful for applications to easily dismiss invalid signatures early on. + public fun signature_subgroup_check(signature: &Signature): bool { + signature_subgroup_check_internal(signature.bytes) + } + + /// Given a vector of public keys with verified PoPs, combines them into an *aggregated* public key which can be used + /// to verify multisignatures using `verify_multisignature` and aggregate signatures using `verify_aggregate_signature`. + /// Aborts if no public keys are given as input. + public fun aggregate_pubkeys(public_keys: vector): AggrPublicKeysWithPoP { + let (bytes, success) = aggregate_pubkeys_internal(public_keys); + assert!(success, std::error::invalid_argument(EZERO_PUBKEYS)); + + AggrPublicKeysWithPoP { + bytes + } + } + + /// Serializes an aggregate public key into 48 bytes. + public fun aggregate_pubkey_to_bytes(apk: &AggrPublicKeysWithPoP): vector { + apk.bytes + } + + /// Aggregates the input signatures into an aggregate-or-multi-signature structure, which can be later verified via + /// `verify_aggregate_signature` or `verify_multisignature`. Returns `None` if zero signatures are given as input + /// or if some of the signatures are not valid group elements. + public fun aggregate_signatures(signatures: vector): Option { + let (bytes, success) = aggregate_signatures_internal(signatures); + if (success) { + option::some( + AggrOrMultiSignature { + bytes + } + ) + } else { + option::none() + } + } + + /// Serializes an aggregate-or-multi-signature into 96 bytes. + public fun aggr_or_multi_signature_to_bytes(sig: &AggrOrMultiSignature): vector { + sig.bytes + } + + /// Deserializes an aggregate-or-multi-signature from 96 bytes. + public fun aggr_or_multi_signature_from_bytes(bytes: vector): AggrOrMultiSignature { + assert!(std::vector::length(&bytes) == SIGNATURE_SIZE, std::error::invalid_argument(EWRONG_SIZE)); + + AggrOrMultiSignature { + bytes + } + } + + + /// Checks that the group element that defines an aggregate-or-multi-signature is in the prime-order subgroup. + public fun aggr_or_multi_signature_subgroup_check(signature: &AggrOrMultiSignature): bool { + signature_subgroup_check_internal(signature.bytes) + } + + /// Verifies an aggregate signature, an aggregation of many signatures `s_i`, each on a different message `m_i`. + public fun verify_aggregate_signature( + aggr_sig: &AggrOrMultiSignature, + public_keys: vector, + messages: vector>, + ): bool { + verify_aggregate_signature_internal(aggr_sig.bytes, public_keys, messages) + } + + /// Verifies a multisignature: an aggregation of many signatures, each on the same message `m`. + public fun verify_multisignature( + multisig: &AggrOrMultiSignature, + aggr_public_key: &AggrPublicKeysWithPoP, + message: vector + ): bool { + verify_multisignature_internal(multisig.bytes, aggr_public_key.bytes, message) + } + + /// Verifies a normal, non-aggregated signature. + public fun verify_normal_signature( + signature: &Signature, + public_key: &PublicKey, + message: vector + ): bool { + verify_normal_signature_internal(signature.bytes, public_key.bytes, message) + } + + /// Verifies a signature share in the multisignature share or an aggregate signature share. + public fun verify_signature_share( + signature_share: &Signature, + public_key: &PublicKeyWithPoP, + message: vector + ): bool { + verify_signature_share_internal(signature_share.bytes, public_key.bytes, message) + } + + #[test_only] + /// Generates a BLS key-pair: a secret key with its corresponding public key. + public fun generate_keys(): (SecretKey, PublicKeyWithPoP) { + let (sk_bytes, pk_bytes) = generate_keys_internal(); + let sk = SecretKey { + bytes: sk_bytes + }; + let pkpop = PublicKeyWithPoP { + bytes: pk_bytes + }; + (sk, pkpop) + } + + #[test_only] + /// Generates a BLS signature for a message with a signing key. + public fun sign_arbitrary_bytes(signing_key: &SecretKey, message: vector): Signature { + Signature { + bytes: sign_internal(signing_key.bytes, message) + } + } + + #[test_only] + /// Generates a multi-signature for a message with multiple signing keys. + public fun multi_sign_arbitrary_bytes(signing_keys: &vector, message: vector): AggrOrMultiSignature { + let n = std::vector::length(signing_keys); + let sigs = vector[]; + let i: u64 = 0; + while (i < n) { + let sig = sign_arbitrary_bytes(std::vector::borrow(signing_keys, i), message); + std::vector::push_back(&mut sigs, sig); + i = i + 1; + }; + let multisig = aggregate_signatures(sigs); + option::extract(&mut multisig) + } + + #[test_only] + /// Generates an aggregated signature over all messages in messages, where signing_keys[i] signs messages[i]. + public fun aggr_sign_arbitrary_bytes(signing_keys: &vector, messages: &vector>): AggrOrMultiSignature { + let signing_key_count = std::vector::length(signing_keys); + let message_count = std::vector::length(messages); + assert!(signing_key_count == message_count, invalid_argument(E_NUM_SIGNERS_MUST_EQ_NUM_MESSAGES)); + let sigs = vector[]; + let i: u64 = 0; + while (i < signing_key_count) { + let sig = sign_arbitrary_bytes(std::vector::borrow(signing_keys, i), *std::vector::borrow(messages, i)); + std::vector::push_back(&mut sigs, sig); + i = i + 1; + }; + let aggr_sig = aggregate_signatures(sigs); + option::extract(&mut aggr_sig) + } + + #[test_only] + /// Returns a mauled copy of a byte array. + public fun maul_bytes(bytes: &vector): vector { + let new_bytes = *bytes; + let first_byte = std::vector::borrow_mut(&mut new_bytes, 0); + *first_byte = *first_byte ^ 0xff; + new_bytes + } + + #[test_only] + /// Returns a mauled copy of a normal signature. + public fun maul_signature(sig: &Signature): Signature { + Signature { + bytes: maul_bytes(&signature_to_bytes(sig)) + } + } + + #[test_only] + /// Returns a mauled copy of an aggregated signature or a multi-signature. + public fun maul_aggr_or_multi_signature(sig: &AggrOrMultiSignature): AggrOrMultiSignature { + AggrOrMultiSignature { + bytes: maul_bytes(&aggr_or_multi_signature_to_bytes(sig)) + } + } + + #[test_only] + /// Returns a mauled copy of a normal public key. + public fun maul_public_key(pk: &PublicKey): PublicKey { + PublicKey { + bytes: maul_bytes(&public_key_to_bytes(pk)) + } + } + + #[test_only] + /// Returns a mauled copy of a PoP'd public key. + public fun maul_public_key_with_pop(pk: &PublicKeyWithPoP): PublicKeyWithPoP { + PublicKeyWithPoP { + bytes: maul_bytes(&public_key_with_pop_to_bytes(pk)) + } + } + + #[test_only] + /// Returns a mauled copy of an aggregated public key. + public fun maul_aggregated_public_key(pk: &AggrPublicKeysWithPoP): AggrPublicKeysWithPoP { + AggrPublicKeysWithPoP { + bytes: maul_bytes(&aggregate_pubkey_to_bytes(pk)) + } + } + + #[test_only] + /// Returns a mauled copy of a proof-of-possession. + public fun maul_proof_of_possession(pop: &ProofOfPossession): ProofOfPossession { + ProofOfPossession { + bytes: maul_bytes(&proof_of_possession_to_bytes(pop)) + } + } + + + #[test_only] + /// Generates a proof-of-possession (PoP) for the public key associated with the secret key `sk`. + public fun generate_proof_of_possession(sk: &SecretKey): ProofOfPossession { + ProofOfPossession { + bytes: generate_proof_of_possession_internal(sk.bytes) + } + } + + // + // Native functions + // + + /// CRYPTOGRAPHY WARNING: This function assumes that the caller verified all public keys have a valid + /// proof-of-possesion (PoP) using `verify_proof_of_possession`. + /// + /// Given a vector of serialized public keys, combines them into an aggregated public key, returning `(bytes, true)`, + /// where `bytes` store the serialized public key. + /// Aborts if no public keys are given as input. + native fun aggregate_pubkeys_internal(public_keys: vector): (vector, bool); + + + /// CRYPTOGRAPHY WARNING: This function can be safely called without verifying that the input signatures are elements + /// of the prime-order subgroup of the BLS12-381 curve. + /// + /// Given a vector of serialized signatures, combines them into an aggregate signature, returning `(bytes, true)`, + /// where `bytes` store the serialized signature. + /// Does not check the input signatures nor the final aggregated signatures for prime-order subgroup membership. + /// Returns `(_, false)` if no signatures are given as input. + /// Does not abort. + native fun aggregate_signatures_internal(signatures: vector): (vector, bool); + + /// Return `true` if the bytes in `public_key` are a valid BLS12-381 public key: + /// (1) it is NOT the identity point, and + /// (2) it is a BLS12-381 elliptic curve point, and + /// (3) it is a prime-order point + /// Return `false` otherwise. + /// Does not abort. + native fun validate_pubkey_internal(public_key: vector): bool; + + /// Return `true` if the elliptic curve point serialized in `signature`: + /// (1) is NOT the identity point, and + /// (2) is a BLS12-381 elliptic curve point, and + /// (3) is a prime-order point + /// Return `false` otherwise. + /// Does not abort. + native fun signature_subgroup_check_internal(signature: vector): bool; + + /// CRYPTOGRAPHY WARNING: First, this function assumes all public keys have a valid proof-of-possesion (PoP). + /// This prevents both small-subgroup attacks and rogue-key attacks. Second, this function can be safely called + /// without verifying that the aggregate signature is in the prime-order subgroup of the BLS12-381 curve. + /// + /// Returns `true` if the aggregate signature `aggsig` on `messages` under `public_keys` verifies (where `messages[i]` + /// should be signed by `public_keys[i]`). + /// + /// Returns `false` if either: + /// - no public keys or messages are given as input, + /// - number of messages does not equal number of public keys + /// - `aggsig` (1) is the identity point, or (2) is NOT a BLS12-381 elliptic curve point, or (3) is NOT a + /// prime-order point + /// Does not abort. + native fun verify_aggregate_signature_internal( + aggsig: vector, + public_keys: vector, + messages: vector>, + ): bool; + + /// CRYPTOGRAPHY WARNING: This function assumes verified proofs-of-possesion (PoP) for the public keys used in + /// computing the aggregate public key. This prevents small-subgroup attacks and rogue-key attacks. + /// + /// Return `true` if the BLS `multisignature` on `message` verifies against the BLS aggregate public key `agg_public_key`. + /// Returns `false` otherwise. + /// Does not abort. + native fun verify_multisignature_internal( + multisignature: vector, + agg_public_key: vector, + message: vector + ): bool; + + /// CRYPTOGRAPHY WARNING: This function WILL check that the public key is a prime-order point, in order to prevent + /// library users from misusing the library by forgetting to validate public keys before giving them as arguments to + /// this function. + /// + /// Returns `true` if the `signature` on `message` verifies under `public key`. + /// Returns `false` otherwise. + /// Does not abort. + native fun verify_normal_signature_internal( + signature: vector, + public_key: vector, + message: vector + ): bool; + + /// Return `true` if the bytes in `public_key` are a valid bls12381 public key (as per `validate_pubkey`) + /// *and* this public key has a valid proof-of-possesion (PoP). + /// Return `false` otherwise. + /// Does not abort. + native fun verify_proof_of_possession_internal( + public_key: vector, + proof_of_possesion: vector + ): bool; + + /// CRYPTOGRAPHY WARNING: Assumes the public key has a valid proof-of-possesion (PoP). This prevents rogue-key + /// attacks later on during signature aggregation. + /// + /// Returns `true` if the `signature_share` on `message` verifies under `public key`. + /// Returns `false` otherwise, similar to `verify_multisignature`. + /// Does not abort. + native fun verify_signature_share_internal( + signature_share: vector, + public_key: vector, + message: vector + ): bool; + + #[test_only] + native fun generate_keys_internal(): (vector, vector); + + #[test_only] + native fun sign_internal(sk: vector, msg: vector): vector; + + #[test_only] + native fun generate_proof_of_possession_internal(sk: vector): vector; + + // + // Constants and helpers for tests + // + + /// Random signature generated by running `cargo test -- bls12381_sample_signature --nocapture --include-ignored` in `crates/aptos-crypto`. + /// The message signed is "Hello Aptos!" and the associated SK is 07416693b6b32c84abe45578728e2379f525729e5b94762435a31e65ecc728da. + const RANDOM_SIGNATURE: vector = x"a01a65854f987d3434149b7f08f70730e30b241984e8712bc2aca885d632aafced4c3f661209debb6b1c8601326623cc16ca2f6c9edc53b7b88b7435fb6b05ddece418d2c34dc6aca2f5a11a79e67774582c14084a01dcb7820e4cb4bad0ea8d"; + + /// Random signature generated by running `cargo test -- bls12381_sample_signature --nocapture --include-ignored` in `crates/aptos-crypto`. + /// The associated SK is 07416693b6b32c84abe45578728e2379f525729e5b94762435a31e65ecc728da. + const RANDOM_PK: vector = x"8a53e7ae5270e3e765cd8a4032c2e77c6f7e87a44ebb85bf28a4d7865565698f975346714262f9e47c6f3e0d5d951660"; + + // + // Tests + // + + #[test_only] + fun get_random_aggsig(): AggrOrMultiSignature { + assert!(signature_subgroup_check_internal(RANDOM_SIGNATURE), 1); + + AggrOrMultiSignature { bytes: RANDOM_SIGNATURE } + } + + #[test_only] + fun get_random_pk_with_pop(): PublicKeyWithPoP { + assert!(validate_pubkey_internal(RANDOM_PK), 1); + + PublicKeyWithPoP { + bytes: RANDOM_PK + } + } + + #[test] + fun test_pubkey_validation() { + // test low order points (in group for PK) + assert!(option::is_none(&public_key_from_bytes(x"ae3cd9403b69c20a0d455fd860e977fe6ee7140a7f091f26c860f2caccd3e0a7a7365798ac10df776675b3a67db8faa0")), 1); + assert!(option::is_none(&public_key_from_bytes(x"928d4862a40439a67fd76a9c7560e2ff159e770dcf688ff7b2dd165792541c88ee76c82eb77dd6e9e72c89cbf1a56a68")), 1); + assert!(option::is_some(&public_key_from_bytes(x"b3e4921277221e01ed71284be5e3045292b26c7f465a6fcdba53ee47edd39ec5160da3b229a73c75671024dcb36de091")), 1); + } + + #[test] + #[expected_failure(abort_code = 65537, location = Self)] + fun test_empty_pubkey_aggregation() { + // First, make sure if no inputs are given, the function returns None + // assert!(aggregate_pop_verified_pubkeys(vector::empty()) == option::none(), 1); + aggregate_pubkeys(std::vector::empty()); + } + + #[test] + fun test_pubkey_aggregation() { + // Second, try some test-cases generated by running the following command in `crates/aptos-crypto`: + // $ cargo test -- sample_aggregate_pk_and_multisig --nocapture --include-ignored + let pks = vector[ + PublicKeyWithPoP { bytes: x"92e201a806af246f805f460fbdc6fc90dd16a18d6accc236e85d3578671d6f6690dde22134d19596c58ce9d63252410a" }, + PublicKeyWithPoP { bytes: x"ab9df801c6f96ade1c0490c938c87d5bcc2e52ccb8768e1b5d14197c5e8bfa562783b96711b702dda411a1a9f08ebbfa" }, + PublicKeyWithPoP { bytes: x"b698c932cf7097d99c17bd6e9c9dc4eeba84278c621700a8f80ec726b1daa11e3ab55fc045b4dbadefbeef05c4182494" }, + PublicKeyWithPoP { bytes: x"934706a8b876d47a996d427e1526ce52c952d5ec0858d49cd262efb785b62b1972d06270b0a7adda1addc98433ad1843" }, + PublicKeyWithPoP { bytes: x"a4cd352daad3a0651c1998dfbaa7a748e08d248a54347544bfedd51a197e016bb6008e9b8e45a744e1a030cc3b27d2da" }, + ]; + + // agg_pks[i] = \sum_{j <= i} pk[j] + let agg_pks = vector[ + AggrPublicKeysWithPoP { bytes: x"92e201a806af246f805f460fbdc6fc90dd16a18d6accc236e85d3578671d6f6690dde22134d19596c58ce9d63252410a" }, + AggrPublicKeysWithPoP { bytes: x"b79ad47abb441d7eda9b220a626df2e4e4910738c5f777947f0213398ecafae044ec0c20d552d1348347e9abfcf3eca1" }, + AggrPublicKeysWithPoP { bytes: x"b5f5eb6153ab5388a1a76343d714e4a2dcf224c5d0722d1e8e90c6bcead05c573fffe986460bd4000645a655bf52bc60" }, + AggrPublicKeysWithPoP { bytes: x"b922006ec14c183572a8864c31dc6632dccffa9f9c86411796f8b1b5a93a2457762c8e2f5ef0a2303506c4bca9a4e0bf" }, + AggrPublicKeysWithPoP { bytes: x"b53df1cfee2168f59e5792e710bf22928dc0553e6531dae5c7656c0a66fc12cb82fbb04863938c953dc901a5a79cc0f3" }, + ]; + + let i = 0; + let accum_pk = std::vector::empty(); + while (i < std::vector::length(&pks)) { + std::vector::push_back(&mut accum_pk, *std::vector::borrow(&pks, i)); + + let apk = aggregate_pubkeys(accum_pk); + + // Make sure PKs were aggregated correctly + assert!(apk == *std::vector::borrow(&agg_pks, i), 1); + assert!(validate_pubkey_internal(apk.bytes), 1); + + i = i + 1; + }; + } + + #[test] + fun test_pubkey_validation_against_invalid_keys() { + let (_sk, pk) = generate_keys(); + let pk_bytes = public_key_with_pop_to_bytes(&pk); + assert!(option::is_some(&public_key_from_bytes(pk_bytes)), 1); + assert!(option::is_none(&public_key_from_bytes(maul_bytes(&pk_bytes))), 1); + } + + #[test] + fun test_signature_aggregation() { + // First, test empty aggregation + assert!(option::is_none(&mut aggregate_signatures(vector[])), 1); + + // Second, try some test-cases generated by running the following command in `crates/aptos-crypto`: + // $ cargo test -- sample_aggregate_sigs --nocapture --include-ignored + + // Signatures of each signer i + let sigs = vector[ + signature_from_bytes(x"a55ac2d64b4c1d141b15d876d3e54ad1eea07ee488e8287cce7cdf3eec551458ab5795ab196f8c112590346f7bc7c97e0053cd5be0f9bd74b93a87cd44458e98d125d6d5c6950ea5e62666beb34422ead79121f8cb0815dae41a986688d03eaf"), + signature_from_bytes(x"90a639a44491191c46379a843266c293de3a46197714ead2ad3886233dd5c2b608b6437fa32fbf9d218b20f1cbfa7970182663beb9c148e2e9412b148e16abf283ffa51b8a536c0e55d61b2e5c849edc49f636c0ef07cb99f125cbcf602e22bb"), + signature_from_bytes(x"9527d81aa15863ef3a3bf96bea6d58157d5063a93a6d0eb9d8b4f4bbda3b31142ec4586cb519da2cd7600941283d1bad061b5439703fd584295b44037a969876962ae1897dcc7cadf909d06faae213c4fef8e015dfb33ec109af02ab0c3f6833"), + signature_from_bytes(x"a54d264f5cab9654b1744232c4650c42b29adf2b19bd00bbdaf4a4d792ee4dfd40a1fe1b067f298bcfd8ae4fdc8250660a2848bd4a80d96585afccec5c6cfa617033dd7913c9acfdf98a72467e8a5155d4cad589a72d6665be7cb410aebc0068"), + signature_from_bytes(x"8d22876bdf73e6ad36ed98546018f6258cd47e45904b87c071e774a6ef4b07cac323258cb920b2fe2b07cca1f2b24bcb0a3194ec76f32edb92391ed2c39e1ada8919f8ea755c5e39873d33ff3a8f4fba21b1261c1ddb9d1688c2b40b77e355d1"), + ]; + + // multisigs[i] is a signature on "Hello, Aptoverse!" from signers 1 through i (inclusive) + let multisigs = vector[ + AggrOrMultiSignature { bytes: x"a55ac2d64b4c1d141b15d876d3e54ad1eea07ee488e8287cce7cdf3eec551458ab5795ab196f8c112590346f7bc7c97e0053cd5be0f9bd74b93a87cd44458e98d125d6d5c6950ea5e62666beb34422ead79121f8cb0815dae41a986688d03eaf" }, + AggrOrMultiSignature { bytes: x"8f1949a06b95c3cb62898d861f889350c0d2cb740da513bfa195aa0ab8fa006ea2efe004a7bbbd9bb363637a279aed20132efd0846f520e7ee0e8ed847a1c6969bb986ad2239bcc9af561b6c2aa6d3016e1c722146471f1e28313de189fe7ebc" }, + AggrOrMultiSignature { bytes: x"ab5ad42bb8f350f8a6b4ae897946a05dbe8f2b22db4f6c37eff6ff737aebd6c5d75bd1abdfc99345ac8ec38b9a449700026f98647752e1c99f69bb132340f063b8a989728e0a3d82a753740bf63e5d8f51e413ebd9a36f6acbe1407a00c4b3e7" }, + AggrOrMultiSignature { bytes: x"ae307a0d055d3ba55ad6ec7094adef27ed821bdcf735fb509ab2c20b80952732394bc67ea1fd8c26ea963540df7448f8102509f7b8c694e4d75f30a43c455f251b6b3fd8b580b9228ffeeb9039834927aacefccd3069bef4b847180d036971cf" }, + AggrOrMultiSignature { bytes: x"8284e4e3983f29cb45020c3e2d89066df2eae533a01cb6ca2c4d466b5e02dd22467f59640aa120db2b9cc49e931415c3097e3d54ff977fd9067b5bc6cfa1c885d9d8821aef20c028999a1d97e783ae049d8fa3d0bbac36ce4ca8e10e551d3461" }, + ]; + + let i = 0; + let accum_sigs = std::vector::empty(); + while (i < std::vector::length(&sigs)) { + std::vector::push_back(&mut accum_sigs, *std::vector::borrow(&sigs, i)); + + let multisig = option::extract(&mut aggregate_signatures(accum_sigs)); + + // Make sure sigs were aggregated correctly + assert!(multisig == *std::vector::borrow(&multisigs, i), 1); + assert!(signature_subgroup_check_internal(multisig.bytes), 1); + + i = i + 1; + }; + } + + #[test] + fun test_empty_signature_aggregation() { + assert!(option::is_none(&mut aggregate_signatures(vector[])), 1); + } + + #[test] + fun test_verify_multisig() { + // Second, try some test-cases generated by running the following command in `crates/aptos-crypto`: + // $ cargo test -- sample_aggregate_pk_and_multisig --nocapture --include-ignored + let pks = vector[ + PublicKeyWithPoP { bytes: x"92e201a806af246f805f460fbdc6fc90dd16a18d6accc236e85d3578671d6f6690dde22134d19596c58ce9d63252410a" }, + PublicKeyWithPoP { bytes: x"ab9df801c6f96ade1c0490c938c87d5bcc2e52ccb8768e1b5d14197c5e8bfa562783b96711b702dda411a1a9f08ebbfa" }, + PublicKeyWithPoP { bytes: x"b698c932cf7097d99c17bd6e9c9dc4eeba84278c621700a8f80ec726b1daa11e3ab55fc045b4dbadefbeef05c4182494" }, + PublicKeyWithPoP { bytes: x"934706a8b876d47a996d427e1526ce52c952d5ec0858d49cd262efb785b62b1972d06270b0a7adda1addc98433ad1843" }, + PublicKeyWithPoP { bytes: x"a4cd352daad3a0651c1998dfbaa7a748e08d248a54347544bfedd51a197e016bb6008e9b8e45a744e1a030cc3b27d2da" }, + ]; + + // agg_pks[i] = \sum_{j <= i} pk[j] + let agg_pks = vector[ + AggrPublicKeysWithPoP { bytes: x"92e201a806af246f805f460fbdc6fc90dd16a18d6accc236e85d3578671d6f6690dde22134d19596c58ce9d63252410a" }, + AggrPublicKeysWithPoP { bytes: x"b79ad47abb441d7eda9b220a626df2e4e4910738c5f777947f0213398ecafae044ec0c20d552d1348347e9abfcf3eca1" }, + AggrPublicKeysWithPoP { bytes: x"b5f5eb6153ab5388a1a76343d714e4a2dcf224c5d0722d1e8e90c6bcead05c573fffe986460bd4000645a655bf52bc60" }, + AggrPublicKeysWithPoP { bytes: x"b922006ec14c183572a8864c31dc6632dccffa9f9c86411796f8b1b5a93a2457762c8e2f5ef0a2303506c4bca9a4e0bf" }, + AggrPublicKeysWithPoP { bytes: x"b53df1cfee2168f59e5792e710bf22928dc0553e6531dae5c7656c0a66fc12cb82fbb04863938c953dc901a5a79cc0f3" }, + ]; + + // multisigs[i] is a signature on "Hello, Aptoverse!" under agg_pks[i] + let multisigs = vector[ + AggrOrMultiSignature { bytes: x"ade45c67bff09ae57e0575feb0be870f2d351ce078e8033d847615099366da1299c69497027b77badb226ff1708543cd062597030c3f1553e0aef6c17e7af5dd0de63c1e4f1f9da68c966ea6c1dcade2cdc646bd5e8bcd4773931021ec5be3fd" }, + AggrOrMultiSignature { bytes: x"964af3d83436f6a9a382f34590c0c14e4454dc1de536af205319ce1ed417b87a2374863d5df7b7d5ed900cf91dffa7a105d3f308831d698c0d74fb2259d4813434fb86425db0ded664ae8f85d02ec1d31734910317d4155cbf69017735900d4d" }, + AggrOrMultiSignature { bytes: x"b523a31813e771e55aa0fc99a48db716ecc1085f9899ccadb64e759ecb481a2fb1cdcc0b266f036695f941361de773081729311f6a1bca9d47393f5359c8c87dc34a91f5dae335590aacbff974076ad1f910dd81750553a72ccbcad3c8cc0f07" }, + AggrOrMultiSignature { bytes: x"a945f61699df58617d37530a85e67bd1181349678b89293951ed29d1fb7588b5c12ebb7917dfc9d674f3f4fde4d062740b85a5f4927f5a4f0091e46e1ac6e41bbd650a74dd49e91445339d741e3b10bdeb9bc8bba46833e0011ff91fa5c77bd2" }, + AggrOrMultiSignature { bytes: x"b627b2cfd8ae59dcf5e58cc6c230ae369985fd096e1bc3be38da5deafcbed7d939f07cccc75383539940c56c6b6453db193f563f5b6e4fe54915afd9e1baea40a297fa7eda74abbdcd4cc5c667d6db3b9bd265782f7693798894400f2beb4637" }, + ]; + + let i = 0; + let accum_pk = std::vector::empty(); + while (i < std::vector::length(&pks)) { + std::vector::push_back(&mut accum_pk, *std::vector::borrow(&pks, i)); + + let apk = aggregate_pubkeys(accum_pk); + + assert!(apk == *std::vector::borrow(&agg_pks, i), 1); + + assert!(verify_multisignature(std::vector::borrow(&multisigs, i), &apk, b"Hello, Aptoverse!"), 1); + + i = i + 1; + }; + } + + #[test] + fun test_verify_multisignature_randomized() { + let signer_count = 1; + let max_signer_count = 5; + let msg = b"hello world"; + while (signer_count <= max_signer_count) { + // Generate key pairs. + let signing_keys = vector[]; + let public_keys = vector[]; + let i = 0; + while (i < signer_count) { + let (sk, pk) = generate_keys(); + std::vector::push_back(&mut signing_keys, sk); + std::vector::push_back(&mut public_keys, pk); + i = i + 1; + }; + + // Generate multi-signature. + let aggr_pk = aggregate_pubkeys(public_keys); + let multisig = multi_sign_arbitrary_bytes(&signing_keys, msg); + + // Test signature verification. + assert!(verify_multisignature(&multisig, &aggr_pk, msg), 1); + assert!(!verify_multisignature(&maul_aggr_or_multi_signature(&multisig), &aggr_pk, msg), 1); + assert!(!verify_multisignature(&multisig, &maul_aggregated_public_key(&aggr_pk), msg), 1); + assert!(!verify_multisignature(&multisig, &aggr_pk, maul_bytes(&msg)), 1); + + // Also test signature aggregation. + let signatures = vector[]; + let i = 0; + while (i < signer_count) { + let sk = std::vector::borrow(&signing_keys, i); + let sig = sign_arbitrary_bytes(sk, msg); + std::vector::push_back(&mut signatures, sig); + i = i + 1; + }; + let aggregated_signature = option::extract(&mut aggregate_signatures(signatures)); + assert!(aggr_or_multi_signature_subgroup_check(&aggregated_signature), 1); + assert!(aggr_or_multi_signature_to_bytes(&aggregated_signature) == aggr_or_multi_signature_to_bytes(&multisig), 1); + + signer_count = signer_count + 1; + } + } + + #[test] + fun test_verify_aggsig() { + assert!(aggr_or_multi_signature_to_bytes(&aggr_or_multi_signature_from_bytes(RANDOM_SIGNATURE)) == RANDOM_SIGNATURE, 1); + + // First, make sure verification returns None when no inputs are given or |pks| != |msgs| + assert!(verify_aggregate_signature(&get_random_aggsig(), vector[], vector[]) == false, 1); + + assert!(verify_aggregate_signature( + &get_random_aggsig(), + vector[ get_random_pk_with_pop() ], + vector[]) == false, 1); + + assert!(verify_aggregate_signature( + &get_random_aggsig(), + vector[], + vector[ x"ab" ]) == false, 1); + + assert!(verify_aggregate_signature( + &get_random_aggsig(), + vector[ get_random_pk_with_pop() ], + vector[ + x"cd", x"ef" + ]) == false, 1); + + assert!(verify_aggregate_signature( + &get_random_aggsig(), + vector[ + get_random_pk_with_pop(), + get_random_pk_with_pop(), + get_random_pk_with_pop(), + ], + vector[ + x"cd", x"ef" + ]) == false, 1); + + // Second, try some test-cases generated by running the following command in `crates/aptos-crypto`: + // $ cargo test -- bls12381_sample_aggregate_pk_and_aggsig --nocapture --ignored + + // The signed messages are "Hello, Aptos !", where \in {1, ..., 5} + let msgs = vector[ + x"48656c6c6f2c204170746f73203121", + x"48656c6c6f2c204170746f73203221", + x"48656c6c6f2c204170746f73203321", + x"48656c6c6f2c204170746f73203421", + x"48656c6c6f2c204170746f73203521", + ]; + + // Public key of signer i + let pks = vector[ + PublicKeyWithPoP { bytes: x"b93d6aabb2b83e52f4b8bda43c24ea920bbced87a03ffc80f8f70c814a8b3f5d69fbb4e579ca76ee008d61365747dbc6" }, + PublicKeyWithPoP { bytes: x"b45648ceae3a983bcb816a96db599b5aef3b688c5753fa20ce36ac7a4f2c9ed792ab20af6604e85e42dab746398bb82c" }, + PublicKeyWithPoP { bytes: x"b3e4921277221e01ed71284be5e3045292b26c7f465a6fcdba53ee47edd39ec5160da3b229a73c75671024dcb36de091" }, + PublicKeyWithPoP { bytes: x"8463b8671c9775a7dbd98bf76d3deba90b5a90535fc87dc8c13506bb5c7bbd99be4d257e60c548140e1e30b107ff5822" }, + PublicKeyWithPoP { bytes: x"a79e3d0e9d04587a3b27d05efe5717da05fd93485dc47978c866dc70a01695c2efd247d1dd843a011a4b6b24079d7384" }, + ]; + + // aggsigs[i] = \sum_{j <= i} sigs[j], where sigs[j] is a signature on msgs[j] under pks[j] + let aggsigs = vector[ + AggrOrMultiSignature { bytes: x"a2bc8bdebe6215ba74b5b53c5ed2aa0c68221a4adf868989ccdcfb62bb0eecc6537def9ee686a7960169c5917d25e5220177ed1c5e95ecfd68c09694062e76efcb00759beac874e4f9a715fd144210883bf9bb272f156b0a1fa15d0e9460f01f" }, + AggrOrMultiSignature { bytes: x"a523aa3c3f1f1074d968ffecf017c7b93ae5243006bf0abd2e45c036ddbec99302984b650ebe5ba306cda4071d281ba50a99ef0e66c3957fab94163296f9d673fc58a36de4276f82bfb1d9180b591df93b5c2804d40dd68cf0f72cd92f86442e" }, + AggrOrMultiSignature { bytes: x"abed10f464de74769121fc09715e59a3ac96a5054a43a9d43cc890a2d4d332614c74c7fb4cceef6d25f85c65dee337330f062f89f23fec9ecf7ce3193fbba2c886630d753be6a4513a4634428904b767af2f230c5cadbcb53a451dd9c7d977f6" }, + AggrOrMultiSignature { bytes: x"8362871631ba822742a31209fa4abce6dc94b741ac4725995459da2951324b51efbbf6bc3ab4681e547ebfbadd80e0360dc078c04188198f0acea26c12645ace9107a4a23cf8db46abc7a402637f16a0477c72569fc9966fe804ef4dc0e5e758" }, + AggrOrMultiSignature { bytes: x"a44d967935fbe63a763ce2dd2b16981f967ecd31e20d3266eef5517530cdc233c8a18273b6d9fd7f61dd39178826e3f115df4e7b304f2de17373a95ea0c9a14293dcfd6f0ef416e06fa23f6a3c850d638e4d8f97ab4562ef55d49a96a50baa13" }, + ]; + + let i = 0; + let msg_subset = std::vector::empty>(); + let pk_subset = std::vector::empty(); + while (i < std::vector::length(&pks)) { + let aggsig = *std::vector::borrow(&aggsigs, i); + + std::vector::push_back(&mut pk_subset, *std::vector::borrow(&pks, i)); + std::vector::push_back(&mut msg_subset, *std::vector::borrow(&msgs, i)); + + assert!(verify_aggregate_signature(&aggsig, pk_subset, msg_subset), 1); + + i = i + 1; + }; + } + + #[test] + fun test_verify_aggregated_signature_randomized() { + let signer_count = 1; + let max_signer_count = 5; + while (signer_count <= max_signer_count) { + // Generate key pairs and messages. + let signing_keys = vector[]; + let public_keys = vector[]; + let messages: vector> = vector[]; + let i = 0; + while (i < signer_count) { + let (sk, pk) = generate_keys(); + std::vector::push_back(&mut signing_keys, sk); + std::vector::push_back(&mut public_keys, pk); + let msg: vector = vector[104, 101, 108, 108, 111, 32, 97, 112, 116, 111, 115, 32, 117, 115, 101, 114, 32, 48+(i as u8)]; //"hello aptos user {i}" + std::vector::push_back(&mut messages, msg); + i = i + 1; + }; + + // Maul messages and public keys. + let mauled_public_keys = vector[maul_public_key_with_pop(std::vector::borrow(&public_keys, 0))]; + let mauled_messages = vector[maul_bytes(std::vector::borrow(&messages, 0))]; + let i = 1; + while (i < signer_count) { + let pk = std::vector::borrow(&public_keys, i); + let msg = std::vector::borrow(&messages, i); + std::vector::push_back(&mut mauled_public_keys, *pk); + std::vector::push_back(&mut mauled_messages, *msg); + i = i + 1; + }; + + // Generate aggregated signature. + let aggrsig = aggr_sign_arbitrary_bytes(&signing_keys, &messages); + + // Test signature verification. + assert!(verify_aggregate_signature(&aggrsig, public_keys, messages), 1); + assert!(!verify_aggregate_signature(&maul_aggr_or_multi_signature(&aggrsig), public_keys, messages), 1); + assert!(!verify_aggregate_signature(&aggrsig, mauled_public_keys, messages), 1); + assert!(!verify_aggregate_signature(&aggrsig, public_keys, mauled_messages), 1); + + // Also test signature aggregation. + let signatures = vector[]; + let i = 0; + while (i < signer_count) { + let sk = std::vector::borrow(&signing_keys, i); + let msg = std::vector::borrow(&messages, i); + let sig = sign_arbitrary_bytes(sk, *msg); + std::vector::push_back(&mut signatures, sig); + i = i + 1; + }; + let aggrsig_another = option::extract(&mut aggregate_signatures(signatures)); + assert!(aggr_or_multi_signature_to_bytes(&aggrsig_another) == aggr_or_multi_signature_to_bytes(&aggrsig), 1); + + signer_count = signer_count + 1; + } + } + + #[test] + /// Tests verification of a random BLS signature created using sk = x"" + fun test_verify_normal_and_verify_sigshare() { + // Test case generated by running `cargo test -- bls12381_sample_signature --nocapture --include-ignored` in + // `crates/aptos-crypto` + // ============================================================================================================= + // SK: 077c8a56f26259215a4a245373ab6ddf328ac6e00e5ea38d8700efa361bdc58d + + let message = b"Hello Aptos!"; + + // First, test signatures that verify + let ok = verify_normal_signature( + &signature_from_bytes(x"b01ce4632e94d8c611736e96aa2ad8e0528a02f927a81a92db8047b002a8c71dc2d6bfb94729d0973790c10b6ece446817e4b7543afd7ca9a17c75de301ae835d66231c26a003f11ae26802b98d90869a9e73788c38739f7ac9d52659e1f7cf7"), + &option::extract(&mut public_key_from_bytes(x"94209a296b739577cb076d3bfb1ca8ee936f29b69b7dae436118c4dd1cc26fd43dcd16249476a006b8b949bf022a7858")), + message, + ); + assert!(ok == true, 1); + + let pk = option::extract(&mut public_key_from_bytes(x"94209a296b739577cb076d3bfb1ca8ee936f29b69b7dae436118c4dd1cc26fd43dcd16249476a006b8b949bf022a7858")); + let pk_with_pop = PublicKeyWithPoP { bytes: pk.bytes }; + + let ok = verify_signature_share( + &signature_from_bytes(x"b01ce4632e94d8c611736e96aa2ad8e0528a02f927a81a92db8047b002a8c71dc2d6bfb94729d0973790c10b6ece446817e4b7543afd7ca9a17c75de301ae835d66231c26a003f11ae26802b98d90869a9e73788c38739f7ac9d52659e1f7cf7"), + &pk_with_pop, + message, + ); + assert!(ok == true, 1); + + // Second, test signatures that do NOT verify + let sigs = vector[ + Signature { bytes: x"a01ce4632e94d8c611736e96aa2ad8e0528a02f927a81a92db8047b002a8c71dc2d6bfb94729d0973790c10b6ece446817e4b7543afd7ca9a17c75de301ae835d66231c26a003f11ae26802b98d90869a9e73788c38739f7ac9d52659e1f7cf7" }, + Signature { bytes: x"b01ce4632e94d8c611736e96aa2ad8e0528a02f927a81a92db8047b002a8c71dc2d6bfb94729d0973790c10b6ece446817e4b7543afd7ca9a17c75de301ae835d66231c26a003f11ae26802b98d90869a9e73788c38739f7ac9d52659e1f7cf7" }, + Signature { bytes: x"b01ce4632e94d8c611736e96aa2ad8e0528a02f927a81a92db8047b002a8c71dc2d6bfb94729d0973790c10b6ece446817e4b7543afd7ca9a17c75de301ae835d66231c26a003f11ae26802b98d90869a9e73788c38739f7ac9d52659e1f7cf7" }, + ]; + let pks = vector[ + x"94209a296b739577cb076d3bfb1ca8ee936f29b69b7dae436118c4dd1cc26fd43dcd16249476a006b8b949bf022a7858", + x"ae4851bb9e7782027437ed0e2c026dd63b77a972ddf4bd9f72bcc218e327986568317e3aa9f679c697a2cb7cebf992f3", + x"82ed7bb5528303a2e306775040a7309e0bd597b70d9949d8c6198a01a7be0b00079320ebfeaf7bbd5bfe86809940d252", + ]; + let messages = vector[ + b"Hello Aptos!", + b"Hello Aptos!", + b"Bello Aptos!", + ]; + + let i = 0; + while (i < std::vector::length(&pks)) { + let sig = std::vector::borrow(&sigs, i); + let pk = *std::vector::borrow(&pks, i); + let msg = *std::vector::borrow(&messages, i); + + let pk = option::extract(&mut public_key_from_bytes(pk)); + + let notok = verify_normal_signature( + sig, + &pk, + msg, + ); + assert!(notok == false, 1); + + let notok = verify_signature_share( + sig, + &PublicKeyWithPoP { bytes: pk.bytes }, + msg, + ); + assert!(notok == false, 1); + + i = i + 1; + } + } + + #[test] + fun test_verify_normal_signature_or_signature_share_randomized() { + let (sk, pkpop) = generate_keys(); + let pk = public_key_with_pop_to_normal(&pkpop); + + let msg = b"hello world"; + let sig = sign_arbitrary_bytes(&sk, msg); + assert!(verify_normal_signature(&sig, &pk, msg), 1); + assert!(!verify_normal_signature(&maul_signature(&sig), &pk, msg), 1); + assert!(!verify_normal_signature(&sig, &maul_public_key(&pk), msg), 1); + assert!(!verify_normal_signature(&sig, &pk, maul_bytes(&msg)), 1); + + assert!(verify_signature_share(&sig, &pkpop, msg), 1); + assert!(!verify_signature_share(&maul_signature(&sig), &pkpop, msg), 1); + assert!(!verify_signature_share(&sig, &maul_public_key_with_pop(&pkpop), msg), 1); + assert!(!verify_signature_share(&sig, &pkpop, maul_bytes(&msg)), 1); + } + + #[test] + /// Tests verification of random BLS proofs-of-possession (PoPs) + fun test_verify_pop() { + // Test case generated by running `cargo test -- sample_pop --nocapture --include-ignored` in `crates/aptos-crypto` + // ============================================================================================================= + + let pks = vector[ + x"808864c91ae7a9998b3f5ee71f447840864e56d79838e4785ff5126c51480198df3d972e1e0348c6da80d396983e42d7", + x"8843843c76d167c02842a214c21277bad0bfd83da467cb5cf2d3ee67b2dcc7221b9fafa6d430400164012580e0c34d27", + x"a23b524d4308d46e43ee8cbbf57f3e1c20c47061ad9c3f915212334ea6532451dd5c01d3d3ada6bea10fe180b2c3b450", + x"a2aaa3eae1df3fc36365491afa1da5181acbb03801afd1430f04bb3b3eb18036f8b756b3508e4caee04beff50d455d1c", + x"84985b7e983dbdaddfca1f0b7dad9660bb39fff660e329acec15f69ac48c75dfa5d2df9f0dc320e4e7b7658166e0ac1c", + ]; + + let pops = vector[ + proof_of_possession_from_bytes(x"ab42afff92510034bf1232a37a0d31bc8abfc17e7ead9170d2d100f6cf6c75ccdcfedbd31699a112b4464a06fd636f3f190595863677d660b4c5d922268ace421f9e86e3a054946ee34ce29e1f88c1a10f27587cf5ec528d65ba7c0dc4863364"), + proof_of_possession_from_bytes(x"a6da5f2bc17df70ce664cff3e3a3e09d17162e47e652032b9fedc0c772fd5a533583242cba12095602e422e579c5284b1735009332dbdd23430bbcf61cc506ae37e41ff9a1fc78f0bc0d99b6bc7bf74c8f567dfb59079a035842bdc5fa3a0464"), + proof_of_possession_from_bytes(x"b8eef236595e2eab34d3c1abdab65971f5cfa1988c731ef62bd63c9a9ad3dfc9259f4f183bfffbc8375a38ba62e1c41a11173209705996ce889859bcbb3ddd7faa3c4ea3d8778f30a9ff814fdcfea1fb163d745c54dfb4dcc5a8cee092ee0070"), + proof_of_possession_from_bytes(x"a03a12fab68ad59d85c15dd1528560eff2c89250070ad0654ba260fda4334da179811d2ecdaca57693f80e9ce977d62011e3b1ee7bb4f7e0eb9b349468dd758f10fc35d54e0d0b8536ca713a77a301944392a5c192b6adf2a79ae2b38912dc98"), + proof_of_possession_from_bytes(x"8899b294f3c066e6dfb59bc0843265a1ccd6afc8f0f38a074d45ded8799c39d25ee0376cd6d6153b0d4d2ff8655e578b140254f1287b9e9df4e2aecc5b049d8556a4ab07f574df68e46348fd78e5298b7913377cf5bb3cf4796bfc755902bfdd"), + ]; + + assert!(std::vector::length(&pks) == std::vector::length(&pops), 1); + + let i = 0; + while (i < std::vector::length(&pks)) { + let opt_pk = public_key_from_bytes_with_pop(*std::vector::borrow(&pks, i), std::vector::borrow(&pops, i)); + assert!(option::is_some(&opt_pk), 1); + + i = i + 1; + }; + + // assert first PK's PoP does not verify against modifed PK' = 0xa0 | PK[1:] + let opt_pk = public_key_from_bytes_with_pop( + x"a08864c91ae7a9998b3f5ee71f447840864e56d79838e4785ff5126c51480198df3d972e1e0348c6da80d396983e42d7", + &proof_of_possession_from_bytes(x"ab42afff92510034bf1232a37a0d31bc8abfc17e7ead9170d2d100f6cf6c75ccdcfedbd31699a112b4464a06fd636f3f190595863677d660b4c5d922268ace421f9e86e3a054946ee34ce29e1f88c1a10f27587cf5ec528d65ba7c0dc4863364")); + assert!(option::is_none(&opt_pk), 1); + + // assert first PK's PoP does not verify if modifed as pop' = 0xb0 | pop[1:] + let opt_pk = public_key_from_bytes_with_pop( + x"808864c91ae7a9998b3f5ee71f447840864e56d79838e4785ff5126c51480198df3d972e1e0348c6da80d396983e42d7", + &proof_of_possession_from_bytes(x"bb42afff92510034bf1232a37a0d31bc8abfc17e7ead9170d2d100f6cf6c75ccdcfedbd31699a112b4464a06fd636f3f190595863677d660b4c5d922268ace421f9e86e3a054946ee34ce29e1f88c1a10f27587cf5ec528d65ba7c0dc4863364")); + assert!(option::is_none(&opt_pk), 1); + } + + #[test] + fun test_verify_pop_randomized() { + let (sk, pk) = generate_keys(); + let pk_bytes = public_key_with_pop_to_bytes(&pk); + let pop = generate_proof_of_possession(&sk); + assert!(option::is_some(&public_key_from_bytes_with_pop(pk_bytes, &pop)), 1); + assert!(option::is_none(&public_key_from_bytes_with_pop(pk_bytes, &maul_proof_of_possession(&pop))), 1); + assert!(option::is_none(&public_key_from_bytes_with_pop(maul_bytes(&pk_bytes), &pop)), 1); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/bls12381_algebra.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/bls12381_algebra.move new file mode 100644 index 000000000..5fb99beb9 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/bls12381_algebra.move @@ -0,0 +1,802 @@ +/// This module defines marker types, constants and test cases for working with BLS12-381 curves +/// using the generic API defined in `algebra.move`. +/// See https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-pairing-friendly-curves-11#name-bls-curves-for-the-128-bit- +/// for the full specification of BLS12-381 curves. +/// +/// Currently-supported BLS12-381 structures include `Fq12`, `Fr`, `G1`, `G2` and `Gt`, +/// along with their widely-used serialization formats, +/// the pairing between `G1`, `G2` and `Gt`, +/// and the hash-to-curve operations for `G1` and `G2` defined in https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16. +/// +/// Other unimplemented BLS12-381 structures and serialization formats are also listed here, +/// as they help define some of the currently supported structures. +/// Their implementation may also be added in the future. +/// +/// `Fq`: the finite field $F_q$ used in BLS12-381 curves with a prime order $q$ equal to +/// 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaab. +/// +/// `FormatFqLsb`: a serialization format for `Fq` elements, +/// where an element is represented by a byte array `b[]` of size 48 with the least significant byte (LSB) coming first. +/// +/// `FormatFqMsb`: a serialization format for `Fq` elements, +/// where an element is represented by a byte array `b[]` of size 48 with the most significant byte (MSB) coming first. +/// +/// `Fq2`: the finite field $F_{q^2}$ used in BLS12-381 curves, +/// which is an extension field of `Fq`, constructed as $F_{q^2}=F_q[u]/(u^2+1)$. +/// +/// `FormatFq2LscLsb`: a serialization format for `Fq2` elements, +/// where an element in the form $(c_0+c_1\cdot u)$ is represented by a byte array `b[]` of size 96, +/// which is a concatenation of its coefficients serialized, with the least significant coefficient (LSC) coming first: +/// - `b[0..48]` is $c_0$ serialized using `FormatFqLsb`. +/// - `b[48..96]` is $c_1$ serialized using `FormatFqLsb`. +/// +/// `FormatFq2MscMsb`: a serialization format for `Fq2` elements, +/// where an element in the form $(c_0+c_1\cdot u)$ is represented by a byte array `b[]` of size 96, +/// which is a concatenation of its coefficients serialized, with the most significant coefficient (MSC) coming first: +/// - `b[0..48]` is $c_1$ serialized using `FormatFqLsb`. +/// - `b[48..96]` is $c_0$ serialized using `FormatFqLsb`. +/// +/// `Fq6`: the finite field $F_{q^6}$ used in BLS12-381 curves, +/// which is an extension field of `Fq2`, constructed as $F_{q^6}=F_{q^2}[v]/(v^3-u-1)$. +/// +/// `FormatFq6LscLsb`: a serialization scheme for `Fq6` elements, +/// where an element in the form $(c_0+c_1\cdot v+c_2\cdot v^2)$ is represented by a byte array `b[]` of size 288, +/// which is a concatenation of its coefficients serialized, with the least significant coefficient (LSC) coming first: +/// - `b[0..96]` is $c_0$ serialized using `FormatFq2LscLsb`. +/// - `b[96..192]` is $c_1$ serialized using `FormatFq2LscLsb`. +/// - `b[192..288]` is $c_2$ serialized using `FormatFq2LscLsb`. +/// +/// `G1Full`: a group constructed by the points on the BLS12-381 curve $E(F_q): y^2=x^3+4$ and the point at infinity, +/// under the elliptic curve point addition. +/// It contains the prime-order subgroup $G_1$ used in pairing. +/// +/// `G2Full`: a group constructed by the points on a curve $E'(F_{q^2}): y^2=x^3+4(u+1)$ and the point at infinity, +/// under the elliptic curve point addition. +/// It contains the prime-order subgroup $G_2$ used in pairing. +module aptos_std::bls12381_algebra { + // + // Marker types + serialization formats begin. + // + + /// The finite field $F_{q^12}$ used in BLS12-381 curves, + /// which is an extension field of `Fq6` (defined in the module documentation), constructed as $F_{q^12}=F_{q^6}[w]/(w^2-v)$. + struct Fq12 {} + + /// A serialization scheme for `Fq12` elements, + /// where an element $(c_0+c_1\cdot w)$ is represented by a byte array `b[]` of size 576, + /// which is a concatenation of its coefficients serialized, with the least significant coefficient (LSC) coming first. + /// - `b[0..288]` is $c_0$ serialized using `FormatFq6LscLsb` (defined in the module documentation). + /// - `b[288..576]` is $c_1$ serialized using `FormatFq6LscLsb`. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0. + struct FormatFq12LscLsb {} + + /// The group $G_1$ in BLS12-381-based pairing $G_1 \times G_2 \rightarrow G_t$. + /// It is a subgroup of `G1Full` (defined in the module documentation) with a prime order $r$ + /// equal to 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001. + /// (so `Fr` is the associated scalar field). + struct G1 {} + + /// A serialization scheme for `G1` elements derived from + /// https://www.ietf.org/archive/id/draft-irtf-cfrg-pairing-friendly-curves-11.html#name-zcash-serialization-format-. + /// + /// Below is the serialization procedure that takes a `G1` element `p` and outputs a byte array of size 96. + /// 1. Let `(x,y)` be the coordinates of `p` if `p` is on the curve, or `(0,0)` otherwise. + /// 1. Serialize `x` and `y` into `b_x[]` and `b_y[]` respectively using `FormatFqMsb` (defined in the module documentation). + /// 1. Concatenate `b_x[]` and `b_y[]` into `b[]`. + /// 1. If `p` is the point at infinity, set the infinity bit: `b[0]: = b[0] | 0x40`. + /// 1. Return `b[]`. + /// + /// Below is the deserialization procedure that takes a byte array `b[]` and outputs either a `G1` element or none. + /// 1. If the size of `b[]` is not 96, return none. + /// 1. Compute the compression flag as `b[0] & 0x80 != 0`. + /// 1. If the compression flag is true, return none. + /// 1. Compute the infinity flag as `b[0] & 0x40 != 0`. + /// 1. If the infinity flag is set, return the point at infinity. + /// 1. Deserialize `[b[0] & 0x1f, b[1], ..., b[47]]` to `x` using `FormatFqMsb`. If `x` is none, return none. + /// 1. Deserialize `[b[48], ..., b[95]]` to `y` using `FormatFqMsb`. If `y` is none, return none. + /// 1. Check if `(x,y)` is on curve `E`. If not, return none. + /// 1. Check if `(x,y)` is in the subgroup of order `r`. If not, return none. + /// 1. Return `(x,y)`. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0. + struct FormatG1Uncompr {} + + /// A serialization scheme for `G1` elements derived from + /// https://www.ietf.org/archive/id/draft-irtf-cfrg-pairing-friendly-curves-11.html#name-zcash-serialization-format-. + /// + /// Below is the serialization procedure that takes a `G1` element `p` and outputs a byte array of size 48. + /// 1. Let `(x,y)` be the coordinates of `p` if `p` is on the curve, or `(0,0)` otherwise. + /// 1. Serialize `x` into `b[]` using `FormatFqMsb` (defined in the module documentation). + /// 1. Set the compression bit: `b[0] := b[0] | 0x80`. + /// 1. If `p` is the point at infinity, set the infinity bit: `b[0]: = b[0] | 0x40`. + /// 1. If `y > -y`, set the lexicographical flag: `b[0] := b[0] | 0x20`. + /// 1. Return `b[]`. + /// + /// Below is the deserialization procedure that takes a byte array `b[]` and outputs either a `G1` element or none. + /// 1. If the size of `b[]` is not 48, return none. + /// 1. Compute the compression flag as `b[0] & 0x80 != 0`. + /// 1. If the compression flag is false, return none. + /// 1. Compute the infinity flag as `b[0] & 0x40 != 0`. + /// 1. If the infinity flag is set, return the point at infinity. + /// 1. Compute the lexicographical flag as `b[0] & 0x20 != 0`. + /// 1. Deserialize `[b[0] & 0x1f, b[1], ..., b[47]]` to `x` using `FormatFqMsb`. If `x` is none, return none. + /// 1. Solve the curve equation with `x` for `y`. If no such `y` exists, return none. + /// 1. Let `y'` be `max(y,-y)` if the lexicographical flag is set, or `min(y,-y)` otherwise. + /// 1. Check if `(x,y')` is in the subgroup of order `r`. If not, return none. + /// 1. Return `(x,y')`. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0. + struct FormatG1Compr {} + + /// The group $G_2$ in BLS12-381-based pairing $G_1 \times G_2 \rightarrow G_t$. + /// It is a subgroup of `G2Full` (defined in the module documentation) with a prime order $r$ equal to + /// 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001. + /// (so `Fr` is the scalar field). + struct G2 {} + + /// A serialization scheme for `G2` elements derived from + /// https://www.ietf.org/archive/id/draft-irtf-cfrg-pairing-friendly-curves-11.html#name-zcash-serialization-format-. + /// + /// Below is the serialization procedure that takes a `G2` element `p` and outputs a byte array of size 192. + /// 1. Let `(x,y)` be the coordinates of `p` if `p` is on the curve, or `(0,0)` otherwise. + /// 1. Serialize `x` and `y` into `b_x[]` and `b_y[]` respectively using `FormatFq2MscMsb` (defined in the module documentation). + /// 1. Concatenate `b_x[]` and `b_y[]` into `b[]`. + /// 1. If `p` is the point at infinity, set the infinity bit in `b[]`: `b[0]: = b[0] | 0x40`. + /// 1. Return `b[]`. + /// + /// Below is the deserialization procedure that takes a byte array `b[]` and outputs either a `G2` element or none. + /// 1. If the size of `b[]` is not 192, return none. + /// 1. Compute the compression flag as `b[0] & 0x80 != 0`. + /// 1. If the compression flag is true, return none. + /// 1. Compute the infinity flag as `b[0] & 0x40 != 0`. + /// 1. If the infinity flag is set, return the point at infinity. + /// 1. Deserialize `[b[0] & 0x1f, ..., b[95]]` to `x` using `FormatFq2MscMsb`. If `x` is none, return none. + /// 1. Deserialize `[b[96], ..., b[191]]` to `y` using `FormatFq2MscMsb`. If `y` is none, return none. + /// 1. Check if `(x,y)` is on the curve `E'`. If not, return none. + /// 1. Check if `(x,y)` is in the subgroup of order `r`. If not, return none. + /// 1. Return `(x,y)`. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0. + struct FormatG2Uncompr {} + + /// A serialization scheme for `G2` elements derived from + /// https://www.ietf.org/archive/id/draft-irtf-cfrg-pairing-friendly-curves-11.html#name-zcash-serialization-format-. + /// + /// Below is the serialization procedure that takes a `G2` element `p` and outputs a byte array of size 96. + /// 1. Let `(x,y)` be the coordinates of `p` if `p` is on the curve, or `(0,0)` otherwise. + /// 1. Serialize `x` into `b[]` using `FormatFq2MscMsb` (defined in the module documentation). + /// 1. Set the compression bit: `b[0] := b[0] | 0x80`. + /// 1. If `p` is the point at infinity, set the infinity bit: `b[0]: = b[0] | 0x40`. + /// 1. If `y > -y`, set the lexicographical flag: `b[0] := b[0] | 0x20`. + /// 1. Return `b[]`. + /// + /// Below is the deserialization procedure that takes a byte array `b[]` and outputs either a `G2` element or none. + /// 1. If the size of `b[]` is not 96, return none. + /// 1. Compute the compression flag as `b[0] & 0x80 != 0`. + /// 1. If the compression flag is false, return none. + /// 1. Compute the infinity flag as `b[0] & 0x40 != 0`. + /// 1. If the infinity flag is set, return the point at infinity. + /// 1. Compute the lexicographical flag as `b[0] & 0x20 != 0`. + /// 1. Deserialize `[b[0] & 0x1f, b[1], ..., b[95]]` to `x` using `FormatFq2MscMsb`. If `x` is none, return none. + /// 1. Solve the curve equation with `x` for `y`. If no such `y` exists, return none. + /// 1. Let `y'` be `max(y,-y)` if the lexicographical flag is set, or `min(y,-y)` otherwise. + /// 1. Check if `(x,y')` is in the subgroup of order `r`. If not, return none. + /// 1. Return `(x,y')`. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0. + struct FormatG2Compr {} + + /// The group $G_t$ in BLS12-381-based pairing $G_1 \times G_2 \rightarrow G_t$. + /// It is a multiplicative subgroup of `Fq12`, + /// with a prime order $r$ equal to 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001. + /// (so `Fr` is the scalar field). + /// The identity of `Gt` is 1. + struct Gt {} + + /// A serialization scheme for `Gt` elements. + /// + /// To serialize, it treats a `Gt` element `p` as an `Fq12` element and serialize it using `FormatFq12LscLsb`. + /// + /// To deserialize, it uses `FormatFq12LscLsb` to try deserializing to an `Fq12` element then test the membership in `Gt`. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0. + struct FormatGt {} + + /// The finite field $F_r$ that can be used as the scalar fields + /// associated with the groups $G_1$, $G_2$, $G_t$ in BLS12-381-based pairing. + struct Fr {} + + /// A serialization format for `Fr` elements, + /// where an element is represented by a byte array `b[]` of size 32 with the least significant byte (LSB) coming first. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0, blst-0.3.7. + struct FormatFrLsb {} + + /// A serialization scheme for `Fr` elements, + /// where an element is represented by a byte array `b[]` of size 32 with the most significant byte (MSB) coming first. + /// + /// NOTE: other implementation(s) using this format: ark-bls12-381-0.4.0, blst-0.3.7. + struct FormatFrMsb {} + + // + // (Marker types + serialization formats end here.) + // Hash-to-structure suites begin. + // + + /// The hash-to-curve suite `BLS12381G1_XMD:SHA-256_SSWU_RO_` that hashes a byte array into `G1` elements. + /// + /// Full specification is defined in https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#name-bls12-381-g1. + struct HashG1XmdSha256SswuRo {} + + /// The hash-to-curve suite `BLS12381G2_XMD:SHA-256_SSWU_RO_` that hashes a byte array into `G2` elements. + /// + /// Full specification is defined in https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-hash-to-curve-16#name-bls12-381-g2. + struct HashG2XmdSha256SswuRo {} + + // + // (Hash-to-structure suites end here.) + // Tests begin. + // + + #[test_only] + const FQ12_VAL_0_SERIALIZED: vector = x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FQ12_VAL_1_SERIALIZED: vector = x"010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FQ12_VAL_7_SERIALIZED: vector = x"070000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FQ12_VAL_7_NEG_SERIALIZED: vector = x"a4aafffffffffeb9ffff53b1feffab1e24f6b0f6a0d23067bf1285f3844b7764d7ac4b43b6a71b4b9ae67f39ea11011a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const Q12_SERIALIZED: vector = x"1175f55da544c7625f8ccb1360e2b1d3ca40747811c8f5ed04440afe232b476c0215676aec05f2a44ac2da6b6d1b7cff075e7b2a587e0aab601a8d3db4f0d29906e5e4d0d78119f396d5a59f0f8d1ca8bca62540be6ab9c12d0ca00de1f311f106278d000e55a393c9766a74e0d08a298450f60d7e666575e3354bf14b8731f4e721c0c180a5ed55c2f8f51f815baecbf96b5fc717eb58ac161a27d1d5f2bdc1a079609b9d6449165b2466b32a01eac7992a1ea0cac2f223cde1d56f9bbccc67afe44621daf858df3fc0eb837818f3e42ab3e131ce4e492efa63c108e6ef91c29ed63b3045baebcb0ab8d203c7f558beaffccba31b12aca7f54b58d0c28340e4fdb3c7c94fe9c4fef9d640ff2fcff02f1748416cbed0981fbff49f0e39eaf8a30273e67ed851944d33d6a593ef5ddcd62da84568822a6045b633bf6a513b3cfe8f9de13e76f8dcbd915980dec205eab6a5c0c72dcebd9afff1d25509ddbf33f8e24131fbd74cda93336514340cf8036b66b09ed9e6a6ac37e22fb3ac407e321beae8cd9fe74c8aaeb4edaa9a7272848fc623f6fe835a2e647379f547fc5ec6371318a85bfa60009cb20ccbb8a467492988a87633c14c0324ba0d0c3e1798ed29c8494cea35023746da05e35d184b4a301d5b2238d665495c6318b5af8653758008952d06cb9e62487b196d64383c73c06d6e1cccdf9b3ce8f95679e7050d949004a55f4ccf95b2552880ae36d1f7e09504d2338316d87d14a064511a295d768113e301bdf9d4383a8be32192d3f2f3b2de14181c73839a7cb4af5301"; + + #[test_only] + fun rand_vector(num: u64): vector> { + let elements = vector[]; + while (num > 0) { + std::vector::push_back(&mut elements, rand_insecure()); + num = num - 1; + }; + elements + } + + #[test(fx = @std)] + fun test_fq12(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Constants. + assert!(Q12_SERIALIZED == order(), 1); + + // Serialization/deserialization. + let val_0 = zero(); + let val_1 = one(); + assert!(FQ12_VAL_0_SERIALIZED == serialize(&val_0), 1); + assert!(FQ12_VAL_1_SERIALIZED == serialize(&val_1), 1); + let val_7 = from_u64(7); + let val_7_another = std::option::extract(&mut deserialize(&FQ12_VAL_7_SERIALIZED)); + assert!(eq(&val_7, &val_7_another), 1); + assert!(FQ12_VAL_7_SERIALIZED == serialize(&val_7), 1); + assert!(std::option::is_none(&deserialize(&x"ffff")), 1); + + // Negation. + let val_minus_7 = neg(&val_7); + assert!(FQ12_VAL_7_NEG_SERIALIZED == serialize(&val_minus_7), 1); + + // Addition. + let val_9 = from_u64(9); + let val_2 = from_u64(2); + assert!(eq(&val_2, &add(&val_minus_7, &val_9)), 1); + + // Subtraction. + assert!(eq(&val_9, &sub(&val_2, &val_minus_7)), 1); + + // Multiplication. + let val_63 = from_u64(63); + assert!(eq(&val_63, &mul(&val_7, &val_9)), 1); + + // division. + let val_0 = from_u64(0); + assert!(eq(&val_7, &std::option::extract(&mut div(&val_63, &val_9))), 1); + assert!(std::option::is_none(&div(&val_63, &val_0)), 1); + + // Inversion. + assert!(eq(&val_minus_7, &neg(&val_7)), 1); + assert!(std::option::is_none(&inv(&val_0)), 1); + + // Squaring. + let val_x = rand_insecure(); + assert!(eq(&mul(&val_x, &val_x), &sqr(&val_x)), 1); + + // Downcasting. + assert!(eq(&zero(), &std::option::extract(&mut downcast(&val_1))), 1); + } + + #[test_only] + const R_SERIALIZED: vector = x"01000000fffffffffe5bfeff02a4bd5305d8a10908d83933487d9d2953a7ed73"; + #[test_only] + const G1_INF_SERIALIZED_COMP: vector = x"c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const G1_INF_SERIALIZED_UNCOMP: vector = x"400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const G1_GENERATOR_SERIALIZED_COMP: vector = x"97f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb"; + #[test_only] + const G1_GENERATOR_SERIALIZED_UNCOMP: vector = x"17f1d3a73197d7942695638c4fa9ac0fc3688c4f9774b905a14e3a3f171bac586c55e83ff97a1aeffb3af00adb22c6bb08b3f481e3aaa0f1a09e30ed741d8ae4fcf5e095d5d00af600db18cb2c04b3edd03cc744a2888ae40caa232946c5e7e1"; + #[test_only] + const G1_GENERATOR_MUL_BY_7_SERIALIZED_COMP: vector = x"b928f3beb93519eecf0145da903b40a4c97dca00b21f12ac0df3be9116ef2ef27b2ae6bcd4c5bc2d54ef5a70627efcb7"; + #[test_only] + const G1_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP: vector = x"1928f3beb93519eecf0145da903b40a4c97dca00b21f12ac0df3be9116ef2ef27b2ae6bcd4c5bc2d54ef5a70627efcb7108dadbaa4b636445639d5ae3089b3c43a8a1d47818edd1839d7383959a41c10fdc66849cfa1b08c5a11ec7e28981a1c"; + #[test_only] + const G1_GENERATOR_MUL_BY_7_NEG_SERIALIZED_COMP: vector = x"9928f3beb93519eecf0145da903b40a4c97dca00b21f12ac0df3be9116ef2ef27b2ae6bcd4c5bc2d54ef5a70627efcb7"; + #[test_only] + const G1_GENERATOR_MUL_BY_7_NEG_SERIALIZED_UNCOMP: vector = x"1928f3beb93519eecf0145da903b40a4c97dca00b21f12ac0df3be9116ef2ef27b2ae6bcd4c5bc2d54ef5a70627efcb70973642f94c9b055f4e1d20812c1f91329ed2e3d71f635a72d599a679d0cda1320e597b4e1b24f735fed1381d767908f"; + + #[test(fx = @std)] + fun test_g1affine(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Constants. + assert!(R_SERIALIZED == order(), 1); + let point_at_infinity = zero(); + let generator = one(); + + // Serialization/deserialization. + assert!(G1_GENERATOR_SERIALIZED_UNCOMP == serialize(&generator), 1); + assert!(G1_GENERATOR_SERIALIZED_COMP == serialize(&generator), 1); + let generator_from_comp = std::option::extract(&mut deserialize(&G1_GENERATOR_SERIALIZED_COMP + )); + let generator_from_uncomp = std::option::extract(&mut deserialize(&G1_GENERATOR_SERIALIZED_UNCOMP + )); + assert!(eq(&generator, &generator_from_comp), 1); + assert!(eq(&generator, &generator_from_uncomp), 1); + + // Deserialization should fail if given a byte array of correct size but the value is not a member. + assert!(std::option::is_none(&deserialize(&x"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), 1); + + assert!( + G1_INF_SERIALIZED_UNCOMP == serialize(&point_at_infinity), 1); + assert!(G1_INF_SERIALIZED_COMP == serialize(&point_at_infinity), 1); + let inf_from_uncomp = std::option::extract(&mut deserialize(&G1_INF_SERIALIZED_UNCOMP + )); + let inf_from_comp = std::option::extract(&mut deserialize(&G1_INF_SERIALIZED_COMP + )); + assert!(eq(&point_at_infinity, &inf_from_comp), 1); + assert!(eq(&point_at_infinity, &inf_from_uncomp), 1); + + let point_7g_from_uncomp = std::option::extract(&mut deserialize(&G1_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP + )); + let point_7g_from_comp = std::option::extract(&mut deserialize(&G1_GENERATOR_MUL_BY_7_SERIALIZED_COMP + )); + assert!(eq(&point_7g_from_comp, &point_7g_from_uncomp), 1); + + // Deserialization should fail if given a point on the curve but off its prime-order subgroup, e.g., `(0,2)`. + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002")), 1); + assert!(std::option::is_none(&deserialize(&x"800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")), 1); + + // Deserialization should fail if given a valid point in (Fq,Fq) but not on the curve. + assert!(std::option::is_none(&deserialize(&x"8959e137e0719bf872abb08411010f437a8955bd42f5ba20fca64361af58ce188b1adb96ef229698bb7860b79e24ba12000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")), 1); + + // Deserialization should fail if given an invalid point (x not in Fq). + assert!(std::option::is_none(&deserialize(&x"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa76e9853b35f5c9b2002d9e5833fd8f9ab4cd3934a4722a06f6055bfca720c91629811e2ecae7f0cf301b6d07898a90f")), 1); + assert!(std::option::is_none(&deserialize(&x"9fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ab")), 1); + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ab")), 1); + + // Scalar multiplication. + let scalar_7 = from_u64(7); + let point_7g_calc = scalar_mul(&generator, &scalar_7); + assert!(eq(&point_7g_calc, &point_7g_from_comp), 1); + assert!(G1_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP == serialize(&point_7g_calc), 1); + assert!(G1_GENERATOR_MUL_BY_7_SERIALIZED_COMP == serialize( &point_7g_calc), 1); + + // Multi-scalar multiplication. + let num_entries = 1; + while (num_entries < 10) { + let scalars = rand_vector(num_entries); + let elements = rand_vector(num_entries); + + let expected = zero(); + let i = 0; + while (i < num_entries) { + let element = std::vector::borrow(&elements, i); + let scalar = std::vector::borrow(&scalars, i); + expected = add(&expected, &scalar_mul(element, scalar)); + i = i + 1; + }; + + let actual = multi_scalar_mul(&elements, &scalars); + assert!(eq(&expected, &actual), 1); + + num_entries = num_entries + 1; + }; + + // Doubling. + let scalar_2 = from_u64(2); + let point_2g = scalar_mul(&generator, &scalar_2); + let point_double_g = double(&generator); + assert!(eq(&point_2g, &point_double_g), 1); + + // Negation. + let point_minus_7g_calc = neg(&point_7g_calc); + assert!(G1_GENERATOR_MUL_BY_7_NEG_SERIALIZED_COMP == serialize(&point_minus_7g_calc), 1); + assert!(G1_GENERATOR_MUL_BY_7_NEG_SERIALIZED_UNCOMP == serialize(&point_minus_7g_calc), 1); + + // Addition. + let scalar_9 = from_u64(9); + let point_9g = scalar_mul(&generator, &scalar_9); + let point_2g = scalar_mul(&generator, &scalar_2); + let point_2g_calc = add(&point_minus_7g_calc, &point_9g); + assert!(eq(&point_2g, &point_2g_calc), 1); + + // Subtraction. + assert!(eq(&point_9g, &sub(&point_2g, &point_minus_7g_calc)), 1); + + // Hash-to-group using suite `BLS12381G1_XMD:SHA-256_SSWU_RO_`. + // Test vectors source: https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html#name-bls12381g1_xmdsha-256_sswu_ + let actual = hash_to(&b"QUUX-V01-CS02-with-BLS12381G1_XMD:SHA-256_SSWU_RO_", &b""); + let expected = std::option::extract(&mut deserialize(&x"052926add2207b76ca4fa57a8734416c8dc95e24501772c814278700eed6d1e4e8cf62d9c09db0fac349612b759e79a108ba738453bfed09cb546dbb0783dbb3a5f1f566ed67bb6be0e8c67e2e81a4cc68ee29813bb7994998f3eae0c9c6a265")); + assert!(eq(&expected, &actual), 1); + let actual = hash_to(&b"QUUX-V01-CS02-with-BLS12381G1_XMD:SHA-256_SSWU_RO_", &b"abcdef0123456789"); + let expected = std::option::extract(&mut deserialize(&x"11e0b079dea29a68f0383ee94fed1b940995272407e3bb916bbf268c263ddd57a6a27200a784cbc248e84f357ce82d9803a87ae2caf14e8ee52e51fa2ed8eefe80f02457004ba4d486d6aa1f517c0889501dc7413753f9599b099ebcbbd2d709")); + assert!(eq(&expected, &actual), 1); + } + + #[test_only] + const G2_INF_SERIALIZED_UNCOMP: vector = x"400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const G2_INF_SERIALIZED_COMP: vector = x"c00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const G2_GENERATOR_SERIALIZED_UNCOMP: vector = x"13e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb80606c4a02ea734cc32acd2b02bc28b99cb3e287e85a763af267492ab572e99ab3f370d275cec1da1aaa9075ff05f79be0ce5d527727d6e118cc9cdc6da2e351aadfd9baa8cbdd3a76d429a695160d12c923ac9cc3baca289e193548608b82801"; + #[test_only] + const G2_GENERATOR_SERIALIZED_COMP: vector = x"93e02b6052719f607dacd3a088274f65596bd0d09920b61ab5da61bbdc7f5049334cf11213945d57e5ac7d055d042b7e024aa2b2f08f0a91260805272dc51051c6e47ad4fa403b02b4510b647ae3d1770bac0326a805bbefd48056c8c121bdb8"; + #[test_only] + const G2_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP: vector = x"0d0273f6bf31ed37c3b8d68083ec3d8e20b5f2cc170fa24b9b5be35b34ed013f9a921f1cad1644d4bdb14674247234c8049cd1dbb2d2c3581e54c088135fef36505a6823d61b859437bfc79b617030dc8b40e32bad1fa85b9c0f368af6d38d3c05ecf93654b7a1885695aaeeb7caf41b0239dc45e1022be55d37111af2aecef87799638bec572de86a7437898efa702008b7ae4dbf802c17a6648842922c9467e460a71c88d393ee7af356da123a2f3619e80c3bdcc8e2b1da52f8cd9913ccdd"; + #[test_only] + const G2_GENERATOR_MUL_BY_7_SERIALIZED_COMP: vector = x"8d0273f6bf31ed37c3b8d68083ec3d8e20b5f2cc170fa24b9b5be35b34ed013f9a921f1cad1644d4bdb14674247234c8049cd1dbb2d2c3581e54c088135fef36505a6823d61b859437bfc79b617030dc8b40e32bad1fa85b9c0f368af6d38d3c"; + #[test_only] + const G2_GENERATOR_MUL_BY_7_NEG_SERIALIZED_UNCOMP: vector = x"0d0273f6bf31ed37c3b8d68083ec3d8e20b5f2cc170fa24b9b5be35b34ed013f9a921f1cad1644d4bdb14674247234c8049cd1dbb2d2c3581e54c088135fef36505a6823d61b859437bfc79b617030dc8b40e32bad1fa85b9c0f368af6d38d3c141418b3e4c84511f485fcc78b80b8bc623d6f3f1282e6da09f9c1860402272ba7129c72c4fcd2174f8ac87671053a8b1149639c79ffba82a4b71f73b11f186f8016a4686ab17ed0ec3d7bc6e476c6ee04c3f3c2d48b1d4ddfac073266ebddce"; + #[test_only] + const G2_GENERATOR_MUL_BY_7_NEG_SERIALIZED_COMP: vector = x"ad0273f6bf31ed37c3b8d68083ec3d8e20b5f2cc170fa24b9b5be35b34ed013f9a921f1cad1644d4bdb14674247234c8049cd1dbb2d2c3581e54c088135fef36505a6823d61b859437bfc79b617030dc8b40e32bad1fa85b9c0f368af6d38d3c"; + + #[test(fx = @std)] + fun test_g2affine(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Special constants. + assert!(R_SERIALIZED == order(), 1); + let point_at_infinity = zero(); + let generator = one(); + + // Serialization/deserialization. + assert!(G2_GENERATOR_SERIALIZED_COMP == serialize(&generator), 1); + assert!(G2_GENERATOR_SERIALIZED_UNCOMP == serialize(&generator), 1); + let generator_from_uncomp = std::option::extract(&mut deserialize(&G2_GENERATOR_SERIALIZED_UNCOMP + )); + let generator_from_comp = std::option::extract(&mut deserialize(&G2_GENERATOR_SERIALIZED_COMP + )); + assert!(eq(&generator, &generator_from_comp), 1); + assert!(eq(&generator, &generator_from_uncomp), 1); + assert!(G2_INF_SERIALIZED_UNCOMP == serialize(&point_at_infinity), 1); + assert!(G2_INF_SERIALIZED_COMP == serialize(&point_at_infinity), 1); + let inf_from_uncomp = std::option::extract(&mut deserialize(&G2_INF_SERIALIZED_UNCOMP)); + let inf_from_comp = std::option::extract(&mut deserialize(&G2_INF_SERIALIZED_COMP)); + assert!(eq(&point_at_infinity, &inf_from_comp), 1); + assert!(eq(&point_at_infinity, &inf_from_uncomp), 1); + let point_7g_from_uncomp = std::option::extract(&mut deserialize(&G2_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP + )); + let point_7g_from_comp = std::option::extract(&mut deserialize(&G2_GENERATOR_MUL_BY_7_SERIALIZED_COMP + )); + assert!(eq(&point_7g_from_comp, &point_7g_from_uncomp), 1); + + // Deserialization should fail if given a point on the curve but not in the prime-order subgroup. + assert!(std::option::is_none(&deserialize(&x"f037d4ccd5ee751eba1c1fd4c7edbb76d2b04c3a1f3f554827cf37c3acbc2dbb7cdb320a2727c2462d6c55ca1f637707b96eeebc622c1dbe7c56c34f93887c8751b42bd04f29253a82251c192ef27ece373993b663f4360505299c5bd18c890ddd862a6308796bf47e2265073c1f7d81afd69f9497fc1403e2e97a866129b43b672295229c21116d4a99f3e5c2ae720a31f181dbed8a93e15f909c20cf69d11a8879adbbe6890740def19814e6d4ed23fb0dcbd79291655caf48b466ac9cae04")), 1); + assert!(std::option::is_none(&deserialize(&x"f037d4ccd5ee751eba1c1fd4c7edbb76d2b04c3a1f3f554827cf37c3acbc2dbb7cdb320a2727c2462d6c55ca1f637707b96eeebc622c1dbe7c56c34f93887c8751b42bd04f29253a82251c192ef27ece373993b663f4360505299c5bd18c890d")), 1); + + // Deserialization should fail if given a valid point in (Fq2,Fq2) but not on the curve. + assert!(std::option::is_none(&deserialize(&x"f037d4ccd5ee751eba1c1fd4c7edbb76d2b04c3a1f3f554827cf37c3acbc2dbb7cdb320a2727c2462d6c55ca1f637707b96eeebc622c1dbe7c56c34f93887c8751b42bd04f29253a82251c192ef27ece373993b663f4360505299c5bd18c890d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")), 1); + + // Deserialization should fail if given an invalid point (x not in Fq2). + assert!(std::option::is_none(&deserialize(&x"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdd862a6308796bf47e2265073c1f7d81afd69f9497fc1403e2e97a866129b43b672295229c21116d4a99f3e5c2ae720a31f181dbed8a93e15f909c20cf69d11a8879adbbe6890740def19814e6d4ed23fb0dcbd79291655caf48b466ac9cae04")), 1); + assert!(std::option::is_none(&deserialize(&x"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ab")), 1); + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ab")), 1); + + // Scalar multiplication. + let scalar_7 = from_u64(7); + let point_7g_calc = scalar_mul(&generator, &scalar_7); + assert!(eq(&point_7g_calc, &point_7g_from_comp), 1); + assert!(G2_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP == serialize(&point_7g_calc), 1); + assert!(G2_GENERATOR_MUL_BY_7_SERIALIZED_COMP == serialize(&point_7g_calc), 1); + + // Multi-scalar multiplication. + let num_entries = 1; + while (num_entries < 10) { + let scalars = rand_vector(num_entries); + let elements = rand_vector(num_entries); + + let expected = zero(); + let i = 0; + while (i < num_entries) { + let element = std::vector::borrow(&elements, i); + let scalar = std::vector::borrow(&scalars, i); + expected = add(&expected, &scalar_mul(element, scalar)); + i = i + 1; + }; + + let actual = multi_scalar_mul(&elements, &scalars); + assert!(eq(&expected, &actual), 1); + + num_entries = num_entries + 1; + }; + + // Doubling. + let scalar_2 = from_u64(2); + let point_2g = scalar_mul(&generator, &scalar_2); + let point_double_g = double(&generator); + assert!(eq(&point_2g, &point_double_g), 1); + + // Negation. + let point_minus_7g_calc = neg(&point_7g_calc); + assert!(G2_GENERATOR_MUL_BY_7_NEG_SERIALIZED_COMP == serialize(&point_minus_7g_calc), 1); + assert!(G2_GENERATOR_MUL_BY_7_NEG_SERIALIZED_UNCOMP == serialize(&point_minus_7g_calc), 1); + + // Addition. + let scalar_9 = from_u64(9); + let point_9g = scalar_mul(&generator, &scalar_9); + let point_2g = scalar_mul(&generator, &scalar_2); + let point_2g_calc = add(&point_minus_7g_calc, &point_9g); + assert!(eq(&point_2g, &point_2g_calc), 1); + + // Subtraction. + assert!(eq(&point_9g, &sub(&point_2g, &point_minus_7g_calc)), 1); + + // Hash-to-group using suite `BLS12381G2_XMD:SHA-256_SSWU_RO_`. + // Test vectors source: https://www.ietf.org/archive/id/draft-irtf-cfrg-hash-to-curve-16.html#name-bls12381g2_xmdsha-256_sswu_ + let actual = hash_to(&b"QUUX-V01-CS02-with-BLS12381G2_XMD:SHA-256_SSWU_RO_", &b""); + let expected = std::option::extract(&mut deserialize(&x"05cb8437535e20ecffaef7752baddf98034139c38452458baeefab379ba13dff5bf5dd71b72418717047f5b0f37da03d0141ebfbdca40eb85b87142e130ab689c673cf60f1a3e98d69335266f30d9b8d4ac44c1038e9dcdd5393faf5c41fb78a12424ac32561493f3fe3c260708a12b7c620e7be00099a974e259ddc7d1f6395c3c811cdd19f1e8dbf3e9ecfdcbab8d60503921d7f6a12805e72940b963c0cf3471c7b2a524950ca195d11062ee75ec076daf2d4bc358c4b190c0c98064fdd92")); + assert!(eq(&expected, &actual), 1); + let actual = hash_to(&b"QUUX-V01-CS02-with-BLS12381G2_XMD:SHA-256_SSWU_RO_", &b"abcdef0123456789"); + let expected = std::option::extract(&mut deserialize(&x"190d119345b94fbd15497bcba94ecf7db2cbfd1e1fe7da034d26cbba169fb3968288b3fafb265f9ebd380512a71c3f2c121982811d2491fde9ba7ed31ef9ca474f0e1501297f68c298e9f4c0028add35aea8bb83d53c08cfc007c1e005723cd00bb5e7572275c567462d91807de765611490205a941a5a6af3b1691bfe596c31225d3aabdf15faff860cb4ef17c7c3be05571a0f8d3c08d094576981f4a3b8eda0a8e771fcdcc8ecceaf1356a6acf17574518acb506e435b639353c2e14827c8")); + assert!(eq(&expected, &actual), 1); + } + + #[test_only] + const FQ12_ONE_SERIALIZED: vector = x"010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const GT_GENERATOR_SERIALIZED: vector = x"b68917caaa0543a808c53908f694d1b6e7b38de90ce9d83d505ca1ef1b442d2727d7d06831d8b2a7920afc71d8eb50120f17a0ea982a88591d9f43503e94a8f1abaf2e4589f65aafb7923c484540a868883432a5c60e75860b11e5465b1c9a08873ec29e844c1c888cb396933057ffdd541b03a5220eda16b2b3a6728ea678034ce39c6839f20397202d7c5c44bb68134f93193cec215031b17399577a1de5ff1f5b0666bdd8907c61a7651e4e79e0372951505a07fa73c25788db6eb8023519a5aa97b51f1cad1d43d8aabbff4dc319c79a58cafc035218747c2f75daf8f2fb7c00c44da85b129113173d4722f5b201b6b4454062e9ea8ba78c5ca3cadaf7238b47bace5ce561804ae16b8f4b63da4645b8457a93793cbd64a7254f150781019de87ee42682940f3e70a88683d512bb2c3fb7b2434da5dedbb2d0b3fb8487c84da0d5c315bdd69c46fb05d23763f2191aabd5d5c2e12a10b8f002ff681bfd1b2ee0bf619d80d2a795eb22f2aa7b85d5ffb671a70c94809f0dafc5b73ea2fb0657bae23373b4931bc9fa321e8848ef78894e987bff150d7d671aee30b3931ac8c50e0b3b0868effc38bf48cd24b4b811a2995ac2a09122bed9fd9fa0c510a87b10290836ad06c8203397b56a78e9a0c61c77e56ccb4f1bc3d3fcaea7550f3503efe30f2d24f00891cb45620605fcfaa4292687b3a7db7c1c0554a93579e889a121fd8f72649b2402996a084d2381c5043166673b3849e4fd1e7ee4af24aa8ed443f56dfd6b68ffde4435a92cd7a4ac3bc77e1ad0cb728606cf08bf6386e5410f"; + #[test_only] + const GT_GENERATOR_MUL_BY_7_SERIALIZED: vector = x"2041ea7b66c19680e2c0bb23245a71918753220b31f88a925aa9b1e192e7c188a0b365cb994b3ec5e809206117c6411242b940b10caa37ce734496b3b7c63578a0e3c076f9b31a7ca13a716262e0e4cda4ac994efb9e19893cbfe4d464b9210d099d808a08b3c4c3846e7529984899478639c4e6c46152ef49a04af9c8e6ff442d286c4613a3dac6a4bee4b40e1f6b030f2871dabe4223b250c3181ecd3bc6819004745aeb6bac567407f2b9c7d1978c45ee6712ae46930bc00638383f6696158bad488cbe7663d681c96c035481dbcf78e7a7fbaec3799163aa6914cef3365156bdc3e533a7c883d5974e3462ac6f19e3f9ce26800ae248a45c5f0dd3a48a185969224e6cd6af9a048241bdcac9800d94aeee970e08488fb961e36a769b6c185d185b4605dc9808517196bba9d00a3e37bca466c19187486db104ee03962d39fe473e276355618e44c965f05082bb027a7baa4bcc6d8c0775c1e8a481e77df36ddad91e75a982302937f543a11fe71922dcd4f46fe8f951f91cde412b359507f2b3b6df0374bfe55c9a126ad31ce254e67d64194d32d7955ec791c9555ea5a917fc47aba319e909de82da946eb36e12aff936708402228295db2712f2fc807c95092a86afd71220699df13e2d2fdf2857976cb1e605f72f1b2edabadba3ff05501221fe81333c13917c85d725ce92791e115eb0289a5d0b3330901bb8b0ed146abeb81381b7331f1c508fb14e057b05d8b0190a9e74a3d046dcd24e7ab747049945b3d8a120c4f6d88e67661b55573aa9b361367488a1ef7dffd967d64a1518"; + #[test_only] + const GT_GENERATOR_MUL_BY_7_NEG_SERIALIZED: vector = x"2041ea7b66c19680e2c0bb23245a71918753220b31f88a925aa9b1e192e7c188a0b365cb994b3ec5e809206117c6411242b940b10caa37ce734496b3b7c63578a0e3c076f9b31a7ca13a716262e0e4cda4ac994efb9e19893cbfe4d464b9210d099d808a08b3c4c3846e7529984899478639c4e6c46152ef49a04af9c8e6ff442d286c4613a3dac6a4bee4b40e1f6b030f2871dabe4223b250c3181ecd3bc6819004745aeb6bac567407f2b9c7d1978c45ee6712ae46930bc00638383f6696158bad488cbe7663d681c96c035481dbcf78e7a7fbaec3799163aa6914cef3365156bdc3e533a7c883d5974e3462ac6f19e3f9ce26800ae248a45c5f0dd3a48a185969224e6cd6af9a048241bdcac9800d94aeee970e08488fb961e36a769b6c184e92a4b9fa2366b1ae8ebdf5542fa1e0ec390c90df40a91e5261800581b5492bd9640d1c5352babc551d1a49998f4517312f55b4339272b28a3e6b0c7d182e2bb61bd7d72b29ae3696db8fafe32b904ab5d0764e46bf21f9a0c9a1f7bedc6b12b9f64820fc8b3fd4a26541472be3c9c93d784cdd53a059d1604bf3292fedd1babfb00398128e3241bc63a5a47b5e9207fcb0c88f7bfddc376a242c9f0c032ba28eec8670f1fa1d47567593b4571c983b8015df91cfa1241b7fb8a57e0e6e01145b98de017eccc2a66e83ced9d83119a505e552467838d35b8ce2f4d7cc9a894f6dee922f35f0e72b7e96f0879b0c8614d3f9e5f5618b5be9b82381628448641a8bb0fd1dffb16c70e6831d8d69f61f2a2ef9e90c421f7a5b1ce7a5d113c7eb01"; + + #[test(fx = @std)] + fun test_gt(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Special constants. + assert!(R_SERIALIZED == order(), 1); + let identity = zero(); + let generator = one(); + + // Serialization/deserialization. + assert!(GT_GENERATOR_SERIALIZED == serialize(&generator), 1); + let generator_from_deser = std::option::extract(&mut deserialize(>_GENERATOR_SERIALIZED)); + assert!(eq(&generator, &generator_from_deser), 1); + assert!(FQ12_ONE_SERIALIZED == serialize(&identity), 1); + let identity_from_deser = std::option::extract(&mut deserialize(&FQ12_ONE_SERIALIZED)); + assert!(eq(&identity, &identity_from_deser), 1); + let element_7g_from_deser = std::option::extract(&mut deserialize(>_GENERATOR_MUL_BY_7_SERIALIZED + )); + assert!(std::option::is_none(&deserialize(&x"ffff")), 1); + + // Deserialization should fail if given an element in Fq12 but not in the prime-order subgroup. + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ab")), 1); + + // Element scalar multiplication. + let scalar_7 = from_u64(7); + let element_7g_calc = scalar_mul(&generator, &scalar_7); + assert!(eq(&element_7g_calc, &element_7g_from_deser), 1); + assert!(GT_GENERATOR_MUL_BY_7_SERIALIZED == serialize(&element_7g_calc), 1); + + // Element negation. + let element_minus_7g_calc = neg(&element_7g_calc); + assert!(GT_GENERATOR_MUL_BY_7_NEG_SERIALIZED == serialize(&element_minus_7g_calc), 1); + + // Element addition. + let scalar_9 = from_u64(9); + let element_9g = scalar_mul(&generator, &scalar_9); + let scalar_2 = from_u64(2); + let element_2g = scalar_mul(&generator, &scalar_2); + let element_2g_calc = add(&element_minus_7g_calc, &element_9g); + assert!(eq(&element_2g, &element_2g_calc), 1); + + // Subtraction. + assert!(eq(&element_9g, &sub(&element_2g, &element_minus_7g_calc)), 1); + + // Upcasting to Fq12. + assert!(eq(&one(), &upcast(&identity)), 1); + } + + #[test_only] + use aptos_std::crypto_algebra::{zero, one, from_u64, eq, deserialize, serialize, neg, add, sub, mul, div, inv, rand_insecure, sqr, order, scalar_mul, multi_scalar_mul, double, hash_to, upcast, enable_cryptography_algebra_natives, pairing, multi_pairing, downcast, Element}; + + #[test_only] + const FR_VAL_0_SERIALIZED_LSB: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FR_VAL_1_SERIALIZED_LSB: vector = x"0100000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FR_VAL_7_SERIALIZED_LSB: vector = x"0700000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FR_VAL_7_SERIALIZED_MSB: vector = x"0000000000000000000000000000000000000000000000000000000000000007"; + #[test_only] + const FR_VAL_7_NEG_SERIALIZED_LSB: vector = x"fafffffffefffffffe5bfeff02a4bd5305d8a10908d83933487d9d2953a7ed73"; + + #[test(fx = @std)] + fun test_fr(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Constants. + assert!(R_SERIALIZED == order(), 1); + + // Serialization/deserialization. + let val_0 = zero(); + let val_1 = one(); + assert!(FR_VAL_0_SERIALIZED_LSB == serialize(&val_0), 1); + assert!(FR_VAL_1_SERIALIZED_LSB == serialize(&val_1), 1); + let val_7 = from_u64(7); + let val_7_2nd = std::option::extract(&mut deserialize(&FR_VAL_7_SERIALIZED_LSB)); + let val_7_3rd = std::option::extract(&mut deserialize(&FR_VAL_7_SERIALIZED_MSB)); + assert!(eq(&val_7, &val_7_2nd), 1); + assert!(eq(&val_7, &val_7_3rd), 1); + assert!(FR_VAL_7_SERIALIZED_LSB == serialize(&val_7), 1); + assert!(FR_VAL_7_SERIALIZED_MSB == serialize(&val_7), 1); + + // Deserialization should fail if given a byte array of right size but the value is not a member. + assert!(std::option::is_none(&deserialize(&x"01000000fffffffffe5bfeff02a4bd5305d8a10908d83933487d9d2953a7ed73")), 1); + assert!(std::option::is_none(&deserialize(&x"73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"01000000fffffffffe5bfeff02a4bd5305d8a10908d83933487d9d2953a7ed7300")), 1); + assert!(std::option::is_none(&deserialize(&x"0073eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001")), 1); + assert!(std::option::is_none(&deserialize(&x"ffff")), 1); + assert!(std::option::is_none(&deserialize(&x"ffff")), 1); + + // Negation. + let val_minus_7 = neg(&val_7); + assert!(FR_VAL_7_NEG_SERIALIZED_LSB == serialize(&val_minus_7), 1); + + // Addition. + let val_9 = from_u64(9); + let val_2 = from_u64(2); + assert!(eq(&val_2, &add(&val_minus_7, &val_9)), 1); + + // Subtraction. + assert!(eq(&val_9, &sub(&val_2, &val_minus_7)), 1); + + // Multiplication. + let val_63 = from_u64(63); + assert!(eq(&val_63, &mul(&val_7, &val_9)), 1); + + // division. + let val_0 = from_u64(0); + assert!(eq(&val_7, &std::option::extract(&mut div(&val_63, &val_9))), 1); + assert!(std::option::is_none(&div(&val_63, &val_0)), 1); + + // Inversion. + assert!(eq(&val_minus_7, &neg(&val_7)), 1); + assert!(std::option::is_none(&inv(&val_0)), 1); + + // Squaring. + let val_x = rand_insecure(); + assert!(eq(&mul(&val_x, &val_x), &sqr(&val_x)), 1); + } + + #[test(fx = @std)] + fun test_pairing(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // pairing(a*P,b*Q) == (a*b)*pairing(P,Q) + let element_p = rand_insecure(); + let element_q = rand_insecure(); + let a = rand_insecure(); + let b = rand_insecure(); + let gt_element = pairing(&scalar_mul(&element_p, &a), &scalar_mul(&element_q, &b)); + let gt_element_another = scalar_mul(&pairing(&element_p, &element_q), &mul(&a, &b)); + assert!(eq(>_element, >_element_another), 1); + } + + #[test(fx = @std)] + fun test_multi_pairing(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Will compute e(a0*P0,b0*Q0)+e(a1*P1,b1*Q1)+e(a2*P2,b2*Q2). + let a0 = rand_insecure(); + let a1 = rand_insecure(); + let a2 = rand_insecure(); + let element_p0 = rand_insecure(); + let element_p1 = rand_insecure(); + let element_p2 = rand_insecure(); + let p0_a0 = scalar_mul(&element_p0, &a0); + let p1_a1 = scalar_mul(&element_p1, &a1); + let p2_a2 = scalar_mul(&element_p2, &a2); + let b0 = rand_insecure(); + let b1 = rand_insecure(); + let b2 = rand_insecure(); + let element_q0 = rand_insecure(); + let element_q1 = rand_insecure(); + let element_q2 = rand_insecure(); + let q0_b0 = scalar_mul(&element_q0, &b0); + let q1_b1 = scalar_mul(&element_q1, &b1); + let q2_b2 = scalar_mul(&element_q2, &b2); + + // Naive method. + let n0 = pairing(&p0_a0, &q0_b0); + let n1 = pairing(&p1_a1, &q1_b1); + let n2 = pairing(&p2_a2, &q2_b2); + let n = zero(); + n = add(&n, &n0); + n = add(&n, &n1); + n = add(&n, &n2); + + // Efficient API. + let m = multi_pairing(&vector[p0_a0, p1_a1, p2_a2], &vector[q0_b0, q1_b1, q2_b2]); + assert!(eq(&n, &m), 1); + } + + #[test(fx = @std)] + #[expected_failure(abort_code = 0x010002, location = aptos_std::crypto_algebra)] + fun test_multi_pairing_should_abort_when_sizes_mismatch(fx: signer) { + enable_cryptography_algebra_natives(&fx); + let g1_elements = vector[rand_insecure()]; + let g2_elements = vector[rand_insecure(), rand_insecure()]; + multi_pairing(&g1_elements, &g2_elements); + } + + #[test(fx = @std)] + #[expected_failure(abort_code = 0x010002, location = aptos_std::crypto_algebra)] + fun test_multi_scalar_mul_should_abort_when_sizes_mismatch(fx: signer) { + enable_cryptography_algebra_natives(&fx); + let elements = vector[rand_insecure()]; + let scalars = vector[rand_insecure(), rand_insecure()]; + multi_scalar_mul(&elements, &scalars); + } + + #[test_only] + /// The maximum number of `G1` elements that can be created in a transaction, + /// calculated by the current memory limit (1MB) and the in-mem G1 representation size (144 bytes per element). + const G1_NUM_MAX: u64 = 1048576 / 144; + + #[test(fx = @std)] + fun test_memory_limit(fx: signer) { + enable_cryptography_algebra_natives(&fx); + let remaining = G1_NUM_MAX; + while (remaining > 0) { + zero(); + remaining = remaining - 1; + } + } + + #[test(fx = @std)] + #[expected_failure(abort_code = 0x090003, location = std::crypto_algebra)] + fun test_memory_limit_exceeded_with_g1(fx: signer) { + enable_cryptography_algebra_natives(&fx); + let remaining = G1_NUM_MAX + 1; + while (remaining > 0) { + zero(); + remaining = remaining - 1; + } + } + + // + // (Tests end here.) + // +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/bn254_algebra.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/bn254_algebra.move new file mode 100644 index 000000000..a5cff4df7 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/bn254_algebra.move @@ -0,0 +1,855 @@ +/// This module defines marker types, constants and test cases for working with BN254 curves using the generic API defined in `algebra.move`. +/// BN254 was sampled as part of the [\[BCTV14\]](https://eprint.iacr.org/2013/879.pdf) paper . +/// The name denotes that it is a Barreto-Naehrig curve of embedding degree 12, defined over a 254-bit (prime) field. +/// The scalar field is highly 2-adic which supports subgroups of roots of unity of size <= 2^28. +/// (as (21888242871839275222246405745257275088548364400416034343698204186575808495617 - 1) mod 2^28 = 0) +/// +/// This curve is also implemented in [libff](https://github.com/scipr-lab/libff/tree/master/libff/algebra/curves/alt_bn128) under the name `bn128`. +/// It is the same as the `bn254` curve used in Ethereum (eg: [go-ethereum](https://github.com/ethereum/go-ethereum/tree/master/crypto/bn254/cloudflare)). +/// +/// #CAUTION +/// **This curve does not satisfy the 128-bit security level anymore.** +/// +/// Its current security is estimated at 128-bits (see "Updating Key Size Estimations for Pairings"; by Barbulescu, Razvan and Duquesne, Sylvain; in Journal of Cryptology; 2019; https://doi.org/10.1007/s00145-018-9280-5) +/// +/// +/// Curve information: +/// * Base field: q = +/// 21888242871839275222246405745257275088696311157297823662689037894645226208583 +/// * Scalar field: r = +/// 21888242871839275222246405745257275088548364400416034343698204186575808495617 +/// * valuation(q - 1, 2) = 1 +/// * valuation(r - 1, 2) = 28 +/// * G1 curve equation: y^2 = x^3 + 3 +/// * G2 curve equation: y^2 = x^3 + B, where +/// * B = 3/(u+9) where Fq2 is represented as Fq\[u\]/(u^2+1) = +/// Fq2(19485874751759354771024239261021720505790618469301721065564631296452457478373, +/// 266929791119991161246907387137283842545076965332900288569378510910307636690) +/// +/// +/// Currently-supported BN254 structures include `Fq12`, `Fr`, `Fq`, `Fq2`, `G1`, `G2` and `Gt`, +/// along with their widely-used serialization formats, +/// the pairing between `G1`, `G2` and `Gt`. +/// +/// Other unimplemented BN254 structures and serialization formats are also listed here, +/// as they help define some of the currently supported structures. +/// Their implementation may also be added in the future. +/// +/// `Fq2`: The finite field $F_{q^2}$ that can be used as the base field of $G_2$ +/// which is an extension field of `Fq`, constructed as $F_{q^2}=F_{q}[u]/(u^2+1)$. +/// +/// `FormatFq2LscLsb`: A serialization scheme for `Fq2` elements, +/// where an element $(c_0+c_1\cdot u)$ is represented by a byte array `b[]` of size N=64, +/// which is a concatenation of its coefficients serialized, with the least significant coefficient (LSC) coming first. +/// - `b[0..32]` is $c_0$ serialized using `FormatFqLscLsb`. +/// - `b[32..64]` is $c_1$ serialized using `FormatFqLscLsb`. +/// +/// `Fq6`: the finite field $F_{q^6}$ used in BN254 curves, +/// which is an extension field of `Fq2`, constructed as $F_{q^6}=F_{q^2}[v]/(v^3-u-9)$. +/// +/// `FormatFq6LscLsb`: a serialization scheme for `Fq6` elements, +/// where an element in the form $(c_0+c_1\cdot v+c_2\cdot v^2)$ is represented by a byte array `b[]` of size 192, +/// which is a concatenation of its coefficients serialized, with the least significant coefficient (LSC) coming first: +/// - `b[0..64]` is $c_0$ serialized using `FormatFq2LscLsb`. +/// - `b[64..128]` is $c_1$ serialized using `FormatFq2LscLsb`. +/// - `b[128..192]` is $c_2$ serialized using `FormatFq2LscLsb`. +/// +/// `G1Full`: a group constructed by the points on the BN254 curve $E(F_q): y^2=x^3+3$ and the point at infinity, +/// under the elliptic curve point addition. +/// It contains the prime-order subgroup $G_1$ used in pairing. +/// +/// `G2Full`: a group constructed by the points on a curve $E'(F_{q^2}): y^2=x^3+3/(u+9)$ and the point at infinity, +/// under the elliptic curve point addition. +/// It contains the prime-order subgroup $G_2$ used in pairing. +module std::bn254_algebra { + // + // Marker types + serialization formats begin. + // + + /// The finite field $F_r$ that can be used as the scalar fields + /// associated with the groups $G_1$, $G_2$, $G_t$ in BN254-based pairing. + struct Fr {} + + /// A serialization format for `Fr` elements, + /// where an element is represented by a byte array `b[]` of size 32 with the least significant byte (LSB) coming first. + /// + /// NOTE: other implementation(s) using this format: ark-bn254-0.4.0. + struct FormatFrLsb {} + + /// A serialization scheme for `Fr` elements, + /// where an element is represented by a byte array `b[]` of size 32 with the most significant byte (MSB) coming first. + /// + /// NOTE: other implementation(s) using this format: ark-bn254-0.4.0. + struct FormatFrMsb {} + + /// The finite field $F_q$ that can be used as the base field of $G_1$ + struct Fq {} + + /// A serialization format for `Fq` elements, + /// where an element is represented by a byte array `b[]` of size 32 with the least significant byte (LSB) coming first. + /// + /// NOTE: other implementation(s) using this format: ark-bn254-0.4.0. + struct FormatFqLsb {} + + /// A serialization scheme for `Fq` elements, + /// where an element is represented by a byte array `b[]` of size 32 with the most significant byte (MSB) coming first. + /// + /// NOTE: other implementation(s) using this format: ark-bn254-0.4.0. + struct FormatFqMsb {} + + /// The finite field $F_{q^12}$ used in BN254 curves, + /// which is an extension field of `Fq6` (defined in the module documentation), constructed as $F_{q^12}=F_{q^6}[w]/(w^2-v)$. + /// The field can downcast to `Gt` if it's an element of the multiplicative subgroup `Gt` of `Fq12` + /// with a prime order $r$ = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001. + struct Fq12 {} + /// A serialization scheme for `Fq12` elements, + /// where an element $(c_0+c_1\cdot w)$ is represented by a byte array `b[]` of size 384, + /// which is a concatenation of its coefficients serialized, with the least significant coefficient (LSC) coming first. + /// - `b[0..192]` is $c_0$ serialized using `FormatFq6LscLsb` (defined in the module documentation). + /// - `b[192..384]` is $c_1$ serialized using `FormatFq6LscLsb`. + /// + /// NOTE: other implementation(s) using this format: ark-bn254-0.4.0. + struct FormatFq12LscLsb {} + + /// The group $G_1$ in BN254-based pairing $G_1 \times G_2 \rightarrow G_t$. + /// It is a subgroup of `G1Full` (defined in the module documentation) with a prime order $r$ + /// equal to 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001. + /// (so `Fr` is the associated scalar field). + struct G1 {} + + /// A serialization scheme for `G1` elements derived from arkworks.rs. + /// + /// Below is the serialization procedure that takes a `G1` element `p` and outputs a byte array of size N=64. + /// 1. Let `(x,y)` be the coordinates of `p` if `p` is on the curve, or `(0,0)` otherwise. + /// 1. Serialize `x` and `y` into `b_x[]` and `b_y[]` respectively using `FormatFqLsb` (defined in the module documentation). + /// 1. Concatenate `b_x[]` and `b_y[]` into `b[]`. + /// 1. If `p` is the point at infinity, set the infinity bit: `b[N-1]: = b[N-1] | 0b0100_0000`. + /// 1. If `y > -y`, set the lexicographical bit: `b[N-1]: = b[N-1] | 0b1000_0000`. + /// 1. Return `b[]`. + /// + /// Below is the deserialization procedure that takes a byte array `b[]` and outputs either a `G1` element or none. + /// 1. If the size of `b[]` is not N, return none. + /// 1. Compute the infinity flag as `b[N-1] & 0b0100_0000 != 0`. + /// 1. If the infinity flag is set, return the point at infinity. + /// 1. Deserialize `[b[0], b[1], ..., b[N/2-1]]` to `x` using `FormatFqLsb`. If `x` is none, return none. + /// 1. Deserialize `[b[N/2], ..., b[N] & 0b0011_1111]` to `y` using `FormatFqLsb`. If `y` is none, return none. + /// 1. Check if `(x,y)` is on curve `E`. If not, return none. + /// 1. Check if `(x,y)` is in the subgroup of order `r`. If not, return none. + /// 1. Return `(x,y)`. + /// + /// NOTE: other implementation(s) using this format: ark-bn254-0.4.0. + struct FormatG1Uncompr {} + + /// A serialization scheme for `G1` elements derived from arkworks.rs + /// + /// Below is the serialization procedure that takes a `G1` element `p` and outputs a byte array of size N=32. + /// 1. Let `(x,y)` be the coordinates of `p` if `p` is on the curve, or `(0,0)` otherwise. + /// 1. Serialize `x` into `b[]` using `FormatFqLsb` (defined in the module documentation). + /// 1. If `p` is the point at infinity, set the infinity bit: `b[N-1]: = b[N-1] | 0b0100_0000`. + /// 1. If `y > -y`, set the lexicographical flag: `b[N-1] := b[N-1] | 0x1000_0000`. + /// 1. Return `b[]`. + /// + /// Below is the deserialization procedure that takes a byte array `b[]` and outputs either a `G1` element or none. + /// 1. If the size of `b[]` is not N, return none. + /// 1. Compute the infinity flag as `b[N-1] & 0b0100_0000 != 0`. + /// 1. If the infinity flag is set, return the point at infinity. + /// 1. Compute the lexicographical flag as `b[N-1] & 0b1000_0000 != 0`. + /// 1. Deserialize `[b[0], b[1], ..., b[N/2-1] & 0b0011_1111]` to `x` using `FormatFqLsb`. If `x` is none, return none. + /// 1. Solve the curve equation with `x` for `y`. If no such `y` exists, return none. + /// 1. Let `y'` be `max(y,-y)` if the lexicographical flag is set, or `min(y,-y)` otherwise. + /// 1. Check if `(x,y')` is in the subgroup of order `r`. If not, return none. + /// 1. Return `(x,y')`. + /// + /// NOTE: other implementation(s) using this format: ark-bn254-0.4.0. + struct FormatG1Compr {} + + /// The group $G_2$ in BN254-based pairing $G_1 \times G_2 \rightarrow G_t$. + /// It is a subgroup of `G2Full` (defined in the module documentation) with a prime order $r$ equal to + /// 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001. + /// (so `Fr` is the scalar field). + struct G2 {} + + /// A serialization scheme for `G2` elements derived from arkworks.rs. + /// + /// Below is the serialization procedure that takes a `G2` element `p` and outputs a byte array of size N=128. + /// 1. Let `(x,y)` be the coordinates of `p` if `p` is on the curve, or `(0,0)` otherwise. + /// 1. Serialize `x` and `y` into `b_x[]` and `b_y[]` respectively using `FormatFq2LscLsb` (defined in the module documentation). + /// 1. Concatenate `b_x[]` and `b_y[]` into `b[]`. + /// 1. If `p` is the point at infinity, set the infinity bit: `b[N-1]: = b[N-1] | 0b0100_0000`. + /// 1. If `y > -y`, set the lexicographical bit: `b[N-1]: = b[N-1] | 0b1000_0000`. + /// 1. Return `b[]`. + /// + /// Below is the deserialization procedure that takes a byte array `b[]` and outputs either a `G1` element or none. + /// 1. If the size of `b[]` is not N, return none. + /// 1. Compute the infinity flag as `b[N-1] & 0b0100_0000 != 0`. + /// 1. If the infinity flag is set, return the point at infinity. + /// 1. Deserialize `[b[0], b[1], ..., b[N/2-1]]` to `x` using `FormatFq2LscLsb`. If `x` is none, return none. + /// 1. Deserialize `[b[N/2], ..., b[N] & 0b0011_1111]` to `y` using `FormatFq2LscLsb`. If `y` is none, return none. + /// 1. Check if `(x,y)` is on curve `E`. If not, return none. + /// 1. Check if `(x,y)` is in the subgroup of order `r`. If not, return none. + /// 1. Return `(x,y)`. + /// + /// NOTE: other implementation(s) using this format: ark-bn254-0.4.0. + struct FormatG2Uncompr {} + + /// A serialization scheme for `G1` elements derived from arkworks.rs + /// + /// Below is the serialization procedure that takes a `G1` element `p` and outputs a byte array of size N=64. + /// 1. Let `(x,y)` be the coordinates of `p` if `p` is on the curve, or `(0,0)` otherwise. + /// 1. Serialize `x` into `b[]` using `FormatFq2LscLsb` (defined in the module documentation). + /// 1. If `p` is the point at infinity, set the infinity bit: `b[N-1]: = b[N-1] | 0b0100_0000`. + /// 1. If `y > -y`, set the lexicographical flag: `b[N-1] := b[N-1] | 0x1000_0000`. + /// 1. Return `b[]`. + /// + /// Below is the deserialization procedure that takes a byte array `b[]` and outputs either a `G1` element or none. + /// 1. If the size of `b[]` is not N, return none. + /// 1. Compute the infinity flag as `b[N-1] & 0b0100_0000 != 0`. + /// 1. If the infinity flag is set, return the point at infinity. + /// 1. Compute the lexicographical flag as `b[N-1] & 0b1000_0000 != 0`. + /// 1. Deserialize `[b[0], b[1], ..., b[N/2-1] & 0b0011_1111]` to `x` using `FormatFq2LscLsb`. If `x` is none, return none. + /// 1. Solve the curve equation with `x` for `y`. If no such `y` exists, return none. + /// 1. Let `y'` be `max(y,-y)` if the lexicographical flag is set, or `min(y,-y)` otherwise. + /// 1. Check if `(x,y')` is in the subgroup of order `r`. If not, return none. + /// 1. Return `(x,y')`. + /// + /// NOTE: other implementation(s) using this format: ark-bn254-0.4.0. + struct FormatG2Compr {} + + /// The group $G_t$ in BN254-based pairing $G_1 \times G_2 \rightarrow G_t$. + /// It is a multiplicative subgroup of `Fq12`, so it can upcast to `Fq12`. + /// with a prime order $r$ equal to 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001. + /// (so `Fr` is the scalar field). + /// The identity of `Gt` is 1. + struct Gt {} + + /// A serialization scheme for `Gt` elements. + /// + /// To serialize, it treats a `Gt` element `p` as an `Fq12` element and serialize it using `FormatFq12LscLsb`. + /// + /// To deserialize, it uses `FormatFq12LscLsb` to try deserializing to an `Fq12` element then test the membership in `Gt`. + /// + /// NOTE: other implementation(s) using this format: ark-bn254-0.4.0. + struct FormatGt {} + + // Tests begin. + + #[test_only] + fun rand_vector(num: u64): vector> { + let elements = vector[]; + while (num > 0) { + std::vector::push_back(&mut elements, rand_insecure()); + num = num - 1; + }; + elements + } + + + #[test_only] + const FQ12_VAL_0_SERIALIZED: vector = x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FQ12_VAL_1_SERIALIZED: vector = x"010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FQ12_VAL_7_SERIALIZED: vector = x"070000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FQ12_VAL_7_NEG_SERIALIZED: vector = x"40fd7cd8168c203c8dca7168916a81975d588181b64550b829a031e1724e643000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const Q12_SERIALIZED: vector = x"21f186cad2e2d4c1dbaf8a066b0ebf41f734e3f859b1c523a6c1f4d457413fdbe3cd44add090135d3ae519acc30ee3bdb6bfac6573b767e975b18a77d53cdcddebf3672c74da9d1409d51b2b2db7ff000d59e3aa7cf09220159f925c86b65459ca6558c4eaa703bf45d85030ff85cc6a879c7e2c4034f7045faf20e4d3dcfffac5eb6634c3e7b939b69b2be70bdf6b9a4680297839b4e3a48cd746bd4d0ea82749ffb7e71bd9b3fb10aa684d71e6adab1250b1d8604d91b51c76c256a50b60ddba2f52b6cc853ac926c6ea86d09d400b2f2330e5c8e92e38905ba50a50c9e11cd979c284bf1327ccdc051a6da1a4a7eac5cec16757a27a1a2311bedd108a9b21ac0814269e7523a5dd3a1f5f4767ffe504a6cb3994fb0ec98d5cd5da00b9cb1188a85f2aa871ecb8a0f9d64141f1ccd2699c138e0ef9ac4d8d6a692b29db0f38b60eb08426ab46109fbab9a5221bb44dd338aafebcc4e6c10dd933597f3ff44ba41d04e82871447f3a759cfa9397c22c0c77f13618dfb65adc8aacf008"; + + + #[test(fx = @std)] + fun test_fq12(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Constants. + assert!(Q12_SERIALIZED == order(), 1); + + // Serialization/deserialization. + let val_0 = zero(); + let val_1 = one(); + assert!(FQ12_VAL_0_SERIALIZED == serialize(&val_0), 1); + assert!(FQ12_VAL_1_SERIALIZED == serialize(&val_1), 1); + let val_7 = from_u64(7); + let val_7_another = std::option::extract(&mut deserialize(&FQ12_VAL_7_SERIALIZED)); + assert!(eq(&val_7, &val_7_another), 1); + assert!(FQ12_VAL_7_SERIALIZED == serialize(&val_7), 1); + assert!(std::option::is_none(&deserialize(&x"ffff")), 1); + + // Negation. + let val_minus_7 = neg(&val_7); + assert!(FQ12_VAL_7_NEG_SERIALIZED == serialize(&val_minus_7), 1); + + // Addition. + let val_9 = from_u64(9); + let val_2 = from_u64(2); + assert!(eq(&val_2, &add(&val_minus_7, &val_9)), 1); + + // Subtraction. + assert!(eq(&val_9, &sub(&val_2, &val_minus_7)), 1); + + // Multiplication. + let val_63 = from_u64(63); + assert!(eq(&val_63, &mul(&val_7, &val_9)), 1); + + // division. + let val_0 = from_u64(0); + assert!(eq(&val_7, &std::option::extract(&mut div(&val_63, &val_9))), 1); + assert!(std::option::is_none(&div(&val_63, &val_0)), 1); + + // Inversion. + assert!(eq(&val_minus_7, &neg(&val_7)), 1); + assert!(std::option::is_none(&inv(&val_0)), 1); + + // Squaring. + let val_x = rand_insecure(); + assert!(eq(&mul(&val_x, &val_x), &sqr(&val_x)), 1); + + // Downcasting. + assert!(eq(&zero(), &std::option::extract(&mut downcast(&val_1))), 1); + // upcasting + assert!(eq(&val_1, &upcast(&zero())), 1); + } + + #[test_only] + const R_SERIALIZED: vector = x"010000f093f5e1439170b97948e833285d588181b64550b829a031e1724e6430"; + #[test_only] + const G1_INF_SERIALIZED_COMP: vector = x"0000000000000000000000000000000000000000000000000000000000000040"; + #[test_only] + const G1_INF_SERIALIZED_UNCOMP: vector = x"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040"; + #[test_only] + const G1_GENERATOR_SERIALIZED_COMP: vector = x"0100000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const G1_GENERATOR_SERIALIZED_UNCOMP: vector = x"01000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const G1_GENERATOR_MUL_BY_7_SERIALIZED_COMP: vector = x"78e0ffab866b3a9876bd01b8ecc66fcb86936277f425539a758dbbd32e2b0717"; + #[test_only] + const G1_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP: vector = x"78e0ffab866b3a9876bd01b8ecc66fcb86936277f425539a758dbbd32e2b07179eafd4607f9f80771bf4185df03bfead7a3719fa4bb57b0152dd30d16cda8a16"; + #[test_only] + const G1_GENERATOR_MUL_BY_7_NEG_SERIALIZED_COMP: vector = x"78e0ffab866b3a9876bd01b8ecc66fcb86936277f425539a758dbbd32e2b0797"; + #[test_only] + const G1_GENERATOR_MUL_BY_7_NEG_SERIALIZED_UNCOMP: vector = x"78e0ffab866b3a9876bd01b8ecc66fcb86936277f425539a758dbbd32e2b0717a94da87797ec9fc471d6580ba12e83e9e22068876a90d4b6d7c200100674d999"; + + #[test(fx = @std)] + fun test_g1affine(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Constants. + assert!(R_SERIALIZED == order(), 1); + let point_at_infinity = zero(); + let generator = one(); + + // Serialization/deserialization. + assert!(G1_GENERATOR_SERIALIZED_UNCOMP == serialize(&generator), 1); + assert!(G1_GENERATOR_SERIALIZED_COMP == serialize(&generator), 1); + let generator_from_comp = std::option::extract(&mut deserialize(&G1_GENERATOR_SERIALIZED_COMP)); + let generator_from_uncomp = std::option::extract(&mut deserialize(&G1_GENERATOR_SERIALIZED_UNCOMP)); + assert!(eq(&generator, &generator_from_comp), 1); + assert!(eq(&generator, &generator_from_uncomp), 1); + + // Deserialization should fail if given a byte array of correct size but the value is not a member. + assert!(std::option::is_none(&deserialize(&x"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), 1); + + assert!( + G1_INF_SERIALIZED_UNCOMP == serialize(&point_at_infinity), 1); + assert!(G1_INF_SERIALIZED_COMP == serialize(&point_at_infinity), 1); + let inf_from_uncomp = std::option::extract(&mut deserialize(&G1_INF_SERIALIZED_UNCOMP + )); + let inf_from_comp = std::option::extract(&mut deserialize(&G1_INF_SERIALIZED_COMP + )); + assert!(eq(&point_at_infinity, &inf_from_comp), 1); + assert!(eq(&point_at_infinity, &inf_from_uncomp), 1); + + let point_7g_from_uncomp = std::option::extract(&mut deserialize(&G1_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP + )); + let point_7g_from_comp = std::option::extract(&mut deserialize(&G1_GENERATOR_MUL_BY_7_SERIALIZED_COMP + )); + assert!(eq(&point_7g_from_comp, &point_7g_from_uncomp), 1); + + // Deserialization should fail if given a point on the curve but off its prime-order subgroup, e.g., `(0,2)`. + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002")), 1); + assert!(std::option::is_none(&deserialize(&x"800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")), 1); + + // Deserialization should fail if given a valid point in (Fq,Fq) but not on the curve. + assert!(std::option::is_none(&deserialize(&x"8959e137e0719bf872abb08411010f437a8955bd42f5ba20fca64361af58ce188b1adb96ef229698bb7860b79e24ba12000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")), 1); + + // Deserialization should fail if given an invalid point (x not in Fq). + assert!(std::option::is_none(&deserialize(&x"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffa76e9853b35f5c9b2002d9e5833fd8f9ab4cd3934a4722a06f6055bfca720c91629811e2ecae7f0cf301b6d07898a90f")), 1); + assert!(std::option::is_none(&deserialize(&x"9fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ab")), 1); + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ab")), 1); + + // Scalar multiplication. + let scalar_7 = from_u64(7); + let point_7g_calc = scalar_mul(&generator, &scalar_7); + assert!(eq(&point_7g_calc, &point_7g_from_comp), 1); + assert!(G1_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP == serialize(&point_7g_calc), 1); + assert!(G1_GENERATOR_MUL_BY_7_SERIALIZED_COMP == serialize( &point_7g_calc), 1); + + // Multi-scalar multiplication. + let num_entries = 1; + while (num_entries < 10) { + let scalars = rand_vector(num_entries); + let elements = rand_vector(num_entries); + + let expected = zero(); + let i = 0; + while (i < num_entries) { + let element = std::vector::borrow(&elements, i); + let scalar = std::vector::borrow(&scalars, i); + expected = add(&expected, &scalar_mul(element, scalar)); + i = i + 1; + }; + + let actual = multi_scalar_mul(&elements, &scalars); + assert!(eq(&expected, &actual), 1); + + num_entries = num_entries + 1; + }; + + // Doubling. + let scalar_2 = from_u64(2); + let point_2g = scalar_mul(&generator, &scalar_2); + let point_double_g = double(&generator); + assert!(eq(&point_2g, &point_double_g), 1); + + // Negation. + let point_minus_7g_calc = neg(&point_7g_calc); + assert!(G1_GENERATOR_MUL_BY_7_NEG_SERIALIZED_COMP == serialize(&point_minus_7g_calc), 1); + assert!(G1_GENERATOR_MUL_BY_7_NEG_SERIALIZED_UNCOMP == serialize(&point_minus_7g_calc), 1); + + // Addition. + let scalar_9 = from_u64(9); + let point_9g = scalar_mul(&generator, &scalar_9); + let point_2g = scalar_mul(&generator, &scalar_2); + let point_2g_calc = add(&point_minus_7g_calc, &point_9g); + assert!(eq(&point_2g, &point_2g_calc), 1); + + // Subtraction. + assert!(eq(&point_9g, &sub(&point_2g, &point_minus_7g_calc)), 1); + } + + #[test_only] + const G2_INF_SERIALIZED_COMP: vector = x"00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040"; + #[test_only] + const G2_INF_SERIALIZED_UNCOMP: vector = x"0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040"; + #[test_only] + const G2_GENERATOR_SERIALIZED_COMP: vector = x"edf692d95cbdde46ddda5ef7d422436779445c5e66006a42761e1f12efde0018c212f3aeb785e49712e7a9353349aaf1255dfb31b7bf60723a480d9293938e19"; + #[test_only] + const G2_GENERATOR_SERIALIZED_UNCOMP: vector = x"edf692d95cbdde46ddda5ef7d422436779445c5e66006a42761e1f12efde0018c212f3aeb785e49712e7a9353349aaf1255dfb31b7bf60723a480d9293938e19aa7dfa6601cce64c7bd3430c69e7d1e38f40cb8d8071ab4aeb6d8cdba55ec8125b9722d1dcdaac55f38eb37033314bbc95330c69ad999eec75f05f58d0890609"; + #[test_only] + const G2_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP: vector = x"08b328aa2a1490c3892ae375ba53a257162f1cde012e70edf8fc27435ddc4b2255243646bade3e596dee466e51d40fbe631e55841e085d6ae2bd9a5a01ba03293f23144105e8212ed8df28ca0e8031d47b7a7de372b3ccee1750262af5ff921dd8e03503be1eedbaadf7e6c4a1be3670d14a46da5fafee7adbdeb2a6cdb7c803"; + #[test_only] + const G2_GENERATOR_MUL_BY_7_SERIALIZED_COMP: vector = x"08b328aa2a1490c3892ae375ba53a257162f1cde012e70edf8fc27435ddc4b2255243646bade3e596dee466e51d40fbe631e55841e085d6ae2bd9a5a01ba0329"; + #[test_only] + const G2_GENERATOR_MUL_BY_7_NEG_SERIALIZED_UNCOMP: vector = x"08b328aa2a1490c3892ae375ba53a257162f1cde012e70edf8fc27435ddc4b2255243646bade3e596dee466e51d40fbe631e55841e085d6ae2bd9a5a01ba032908da689711a4fe0db5ea489e82ea4fc3e1dd039e439283c911500bb77d4ed1126f1c47d5586d3381dfd28aa3efab4a278c0d3ba75696613d4ec17e3aa5969bac"; + #[test_only] + const G2_GENERATOR_MUL_BY_7_NEG_SERIALIZED_COMP: vector = x"08b328aa2a1490c3892ae375ba53a257162f1cde012e70edf8fc27435ddc4b2255243646bade3e596dee466e51d40fbe631e55841e085d6ae2bd9a5a01ba03a9"; + + #[test(fx = @std)] + fun test_g2affine(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Special constants. + assert!(R_SERIALIZED == order(), 1); + let point_at_infinity = zero(); + let generator = one(); + + // Serialization/deserialization. + assert!(G2_GENERATOR_SERIALIZED_COMP == serialize(&generator), 1); + assert!(G2_GENERATOR_SERIALIZED_UNCOMP == serialize(&generator), 1); + let generator_from_uncomp = std::option::extract(&mut deserialize(&G2_GENERATOR_SERIALIZED_UNCOMP + )); + let generator_from_comp = std::option::extract(&mut deserialize(&G2_GENERATOR_SERIALIZED_COMP + )); + assert!(eq(&generator, &generator_from_comp), 1); + assert!(eq(&generator, &generator_from_uncomp), 1); + assert!(G2_INF_SERIALIZED_UNCOMP == serialize(&point_at_infinity), 1); + assert!(G2_INF_SERIALIZED_COMP == serialize(&point_at_infinity), 1); + let inf_from_uncomp = std::option::extract(&mut deserialize(&G2_INF_SERIALIZED_UNCOMP)); + let inf_from_comp = std::option::extract(&mut deserialize(&G2_INF_SERIALIZED_COMP)); + assert!(eq(&point_at_infinity, &inf_from_comp), 1); + assert!(eq(&point_at_infinity, &inf_from_uncomp), 1); + let point_7g_from_uncomp = std::option::extract(&mut deserialize(&G2_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP + )); + let point_7g_from_comp = std::option::extract(&mut deserialize(&G2_GENERATOR_MUL_BY_7_SERIALIZED_COMP + )); + assert!(eq(&point_7g_from_comp, &point_7g_from_uncomp), 1); + + // Deserialization should fail if given a point on the curve but not in the prime-order subgroup. + assert!(std::option::is_none(&deserialize(&x"f037d4ccd5ee751eba1c1fd4c7edbb76d2b04c3a1f3f554827cf37c3acbc2dbb7cdb320a2727c2462d6c55ca1f637707b96eeebc622c1dbe7c56c34f93887c8751b42bd04f29253a82251c192ef27ece373993b663f4360505299c5bd18c890ddd862a6308796bf47e2265073c1f7d81afd69f9497fc1403e2e97a866129b43b672295229c21116d4a99f3e5c2ae720a31f181dbed8a93e15f909c20cf69d11a8879adbbe6890740def19814e6d4ed23fb0dcbd79291655caf48b466ac9cae04")), 1); + assert!(std::option::is_none(&deserialize(&x"f037d4ccd5ee751eba1c1fd4c7edbb76d2b04c3a1f3f554827cf37c3acbc2dbb7cdb320a2727c2462d6c55ca1f637707b96eeebc622c1dbe7c56c34f93887c8751b42bd04f29253a82251c192ef27ece373993b663f4360505299c5bd18c890d")), 1); + + // Deserialization should fail if given a valid point in (Fq2,Fq2) but not on the curve. + assert!(std::option::is_none(&deserialize(&x"f037d4ccd5ee751eba1c1fd4c7edbb76d2b04c3a1f3f554827cf37c3acbc2dbb7cdb320a2727c2462d6c55ca1f637707b96eeebc622c1dbe7c56c34f93887c8751b42bd04f29253a82251c192ef27ece373993b663f4360505299c5bd18c890d000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")), 1); + + // Deserialization should fail if given an invalid point (x not in Fq2). + assert!(std::option::is_none(&deserialize(&x"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdd862a6308796bf47e2265073c1f7d81afd69f9497fc1403e2e97a866129b43b672295229c21116d4a99f3e5c2ae720a31f181dbed8a93e15f909c20cf69d11a8879adbbe6890740def19814e6d4ed23fb0dcbd79291655caf48b466ac9cae04")), 1); + assert!(std::option::is_none(&deserialize(&x"ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ab")), 1); + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ab")), 1); + + // Scalar multiplication. + let scalar_7 = from_u64(7); + let point_7g_calc = scalar_mul(&generator, &scalar_7); + assert!(eq(&point_7g_calc, &point_7g_from_comp), 1); + assert!(G2_GENERATOR_MUL_BY_7_SERIALIZED_UNCOMP == serialize(&point_7g_calc), 1); + assert!(G2_GENERATOR_MUL_BY_7_SERIALIZED_COMP == serialize(&point_7g_calc), 1); + + // Multi-scalar multiplication. + let num_entries = 1; + while (num_entries < 10) { + let scalars = rand_vector(num_entries); + let elements = rand_vector(num_entries); + + let expected = zero(); + let i = 0; + while (i < num_entries) { + let element = std::vector::borrow(&elements, i); + let scalar = std::vector::borrow(&scalars, i); + expected = add(&expected, &scalar_mul(element, scalar)); + i = i + 1; + }; + + let actual = multi_scalar_mul(&elements, &scalars); + assert!(eq(&expected, &actual), 1); + + num_entries = num_entries + 1; + }; + + // Doubling. + let scalar_2 = from_u64(2); + let point_2g = scalar_mul(&generator, &scalar_2); + let point_double_g = double(&generator); + assert!(eq(&point_2g, &point_double_g), 1); + + // Negation. + let point_minus_7g_calc = neg(&point_7g_calc); + assert!(G2_GENERATOR_MUL_BY_7_NEG_SERIALIZED_COMP == serialize(&point_minus_7g_calc), 1); + assert!(G2_GENERATOR_MUL_BY_7_NEG_SERIALIZED_UNCOMP == serialize(&point_minus_7g_calc), 1); + + // Addition. + let scalar_9 = from_u64(9); + let point_9g = scalar_mul(&generator, &scalar_9); + let point_2g = scalar_mul(&generator, &scalar_2); + let point_2g_calc = add(&point_minus_7g_calc, &point_9g); + assert!(eq(&point_2g, &point_2g_calc), 1); + + // Subtraction. + assert!(eq(&point_9g, &sub(&point_2g, &point_minus_7g_calc)), 1); + } + + #[test_only] + const FQ12_ONE_SERIALIZED: vector = x"010000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const GT_GENERATOR_SERIALIZED: vector = x"950e879d73631f5eb5788589eb5f7ef8d63e0a28de1ba00dfe4ca9ed3f252b264a8afb8eb4349db466ed1809ea4d7c39bdab7938821f1b0a00a295c72c2de002e01dbdfd0254134efcb1ec877395d25f937719b344adb1a58d129be2d6f2a9132b16a16e8ab030b130e69c69bd20b4c45986e6744a98314b5c1a0f50faa90b04dbaf9ef8aeeee3f50be31c210b598f4752f073987f9d35be8f6770d83f2ffc0af0d18dd9d2dbcdf943825acc12a7a9ddca45e629d962c6bd64908c3930a5541cfe2924dcc5580d5cef7a4bfdec90a91b59926f850d4a7923c01a5a5dbf0f5c094a2b9fb9d415820fa6b40c59bb9eade9c953407b0fc11da350a9d872cad6d3142974ca385854afdf5f583c04231adc5957c8914b6b20dc89660ed7c3bbe7c01d972be2d53ecdb27a1bcc16ac610db95aa7d237c8ff55a898cb88645a0e32530b23d7ebf5dafdd79b0f9c2ac4ba07ce18d3d16cf36e47916c4cae5d08d3afa813972c769e8514533e380c9443b3e1ee5c96fa3a0a73f301b626454721527bf900"; + #[test_only] + const GT_GENERATOR_MUL_BY_7_SERIALIZED: vector = x"533a587534641b568125fb273eac723c789a347eba9fcfd58d93742b3a0b782fd61bbf6202e04b8a33b6c60150fc62a071cb9ac9749a79031fd0dbb6dd8a1f2bcf1eb450bdf58fd3d124b2e0aaf878d11e96af3051631145a4bf0530b5d19d08bfe2d515530b9059525b2826587f7bf1f146bfd0e91e84411c7722abb7a8c418b20b1660b41e6949beff93b2b36303e74804df3335ab5bd85bfd7959d6fd3101d0bf6f681eb809c9a6c3544db7f81444e5c4fbdd0a31e920616ae08a2ab5f51ebf064c4906c7b29521e8fda3d704830a9a6ef5d455a85ae09216f55fd0e74d0aaf83ad81ba50218f08024910184c9ddab42a28f51912c779556c41c61aba2d075cfc020b61a18a9366c9f71658f00b44369bd86929725cf867a0b8fda694a7134a2790ebf19cbea1f972eedfd51787683f98d80895f630ff0bd513edebd5a217c00e231869178bd41cf47a7c0125379a3926353e5310a578066dfbb974424802b942a8b4f6338d7f9d8b9c4031dc46163a59c58ff503eca69b642398b5a1212b"; + #[test_only] + const GT_GENERATOR_MUL_BY_7_NEG_SERIALIZED: vector = x"533a587534641b568125fb273eac723c789a347eba9fcfd58d93742b3a0b782fd61bbf6202e04b8a33b6c60150fc62a071cb9ac9749a79031fd0dbb6dd8a1f2bcf1eb450bdf58fd3d124b2e0aaf878d11e96af3051631145a4bf0530b5d19d08bfe2d515530b9059525b2826587f7bf1f146bfd0e91e84411c7722abb7a8c418b20b1660b41e6949beff93b2b36303e74804df3335ab5bd85bfd7959d6fd3101d0bf6f681eb809c9a6c3544db7f81444e5c4fbdd0a31e920616ae08a2ab5f51e88f6308f10c56da66be273c4b965fe8cc3e98bac609df5d796893c81a26616269879cf565c3bffac84c82858791ee4bca82d598c9c33893ed433f01a58943629eb007acdb5ea95a826017a51397a755327bda8178dd3f3bfc1ff78e3cbb9bc1cfdd5ecec24ef619a93578388bb52fa2e1ec0a878214f1fb91dcb1df48678c11887ee59c0ad74956770d6f6eb8f454afd23324c436335ab3f23333627fe0b1c2e8ebad423205893bcef3ed527608e3a8123ffbbf1c04164118e3b0e49bdac4205"; + + + #[test(fx = @std)] + fun test_gt(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Special constants. + assert!(R_SERIALIZED == order(), 1); + let identity = zero(); + let generator = one(); + + // Serialization/deserialization. + assert!(GT_GENERATOR_SERIALIZED == serialize(&generator), 1); + let generator_from_deser = std::option::extract(&mut deserialize(>_GENERATOR_SERIALIZED)); + assert!(eq(&generator, &generator_from_deser), 1); + assert!(FQ12_ONE_SERIALIZED == serialize(&identity), 1); + let identity_from_deser = std::option::extract(&mut deserialize(&FQ12_ONE_SERIALIZED)); + assert!(eq(&identity, &identity_from_deser), 1); + let element_7g_from_deser = std::option::extract(&mut deserialize(>_GENERATOR_MUL_BY_7_SERIALIZED + )); + assert!(std::option::is_none(&deserialize(&x"ffff")), 1); + + // Deserialization should fail if given an element in Fq12 but not in the prime-order subgroup. + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000ab")), 1); + + // Element scalar multiplication. + let scalar_7 = from_u64(7); + let element_7g_calc = scalar_mul(&generator, &scalar_7); + assert!(eq(&element_7g_calc, &element_7g_from_deser), 1); + assert!(GT_GENERATOR_MUL_BY_7_SERIALIZED == serialize(&element_7g_calc), 1); + + // Element negation. + let element_minus_7g_calc = neg(&element_7g_calc); + assert!(GT_GENERATOR_MUL_BY_7_NEG_SERIALIZED == serialize(&element_minus_7g_calc), 1); + + // Element addition. + let scalar_9 = from_u64(9); + let element_9g = scalar_mul(&generator, &scalar_9); + let scalar_2 = from_u64(2); + let element_2g = scalar_mul(&generator, &scalar_2); + let element_2g_calc = add(&element_minus_7g_calc, &element_9g); + assert!(eq(&element_2g, &element_2g_calc), 1); + + // Subtraction. + assert!(eq(&element_9g, &sub(&element_2g, &element_minus_7g_calc)), 1); + + // Upcasting to Fq12. + assert!(eq(&one(), &upcast(&identity)), 1); + } + + #[test_only] + use aptos_std::crypto_algebra::{zero, one, from_u64, eq, deserialize, serialize, neg, add, sub, mul, div, inv, rand_insecure, sqr, order, scalar_mul, multi_scalar_mul, double, upcast, enable_cryptography_algebra_natives, pairing, multi_pairing, downcast, Element}; + + #[test_only] + const FR_VAL_0_SERIALIZED_LSB: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FR_VAL_1_SERIALIZED_LSB: vector = x"0100000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FR_VAL_7_SERIALIZED_LSB: vector = x"0700000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FR_VAL_7_SERIALIZED_MSB: vector = x"0000000000000000000000000000000000000000000000000000000000000007"; + #[test_only] + const FR_VAL_7_NEG_SERIALIZED_LSB: vector = x"faffffef93f5e1439170b97948e833285d588181b64550b829a031e1724e6430"; + + #[test(fx = @std)] + fun test_fr(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Constants. + assert!(R_SERIALIZED == order(), 1); + + // Serialization/deserialization. + let val_0 = zero(); + let val_1 = one(); + assert!(FR_VAL_0_SERIALIZED_LSB == serialize(&val_0), 1); + assert!(FR_VAL_1_SERIALIZED_LSB == serialize(&val_1), 1); + let val_7 = from_u64(7); + let val_7_2nd = std::option::extract(&mut deserialize(&FR_VAL_7_SERIALIZED_LSB)); + let val_7_3rd = std::option::extract(&mut deserialize(&FR_VAL_7_SERIALIZED_MSB)); + assert!(eq(&val_7, &val_7_2nd), 1); + assert!(eq(&val_7, &val_7_3rd), 1); + assert!(FR_VAL_7_SERIALIZED_LSB == serialize(&val_7), 1); + assert!(FR_VAL_7_SERIALIZED_MSB == serialize(&val_7), 1); + + // Deserialization should fail if given a byte array of right size but the value is not a member. + assert!(std::option::is_none(&deserialize(&x"01000000fffffffffe5bfeff02a4bd5305d8a10908d83933487d9d2953a7ed73")), 1); + assert!(std::option::is_none(&deserialize(&x"73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"01000000fffffffffe5bfeff02a4bd5305d8a10908d83933487d9d2953a7ed7300")), 1); + assert!(std::option::is_none(&deserialize(&x"0073eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff00000001")), 1); + assert!(std::option::is_none(&deserialize(&x"ffff")), 1); + assert!(std::option::is_none(&deserialize(&x"ffff")), 1); + + // Negation. + let val_minus_7 = neg(&val_7); + assert!(FR_VAL_7_NEG_SERIALIZED_LSB == serialize(&val_minus_7), 1); + + // Addition. + let val_9 = from_u64(9); + let val_2 = from_u64(2); + assert!(eq(&val_2, &add(&val_minus_7, &val_9)), 1); + + // Subtraction. + assert!(eq(&val_9, &sub(&val_2, &val_minus_7)), 1); + + // Multiplication. + let val_63 = from_u64(63); + assert!(eq(&val_63, &mul(&val_7, &val_9)), 1); + + // division. + let val_0 = from_u64(0); + assert!(eq(&val_7, &std::option::extract(&mut div(&val_63, &val_9))), 1); + assert!(std::option::is_none(&div(&val_63, &val_0)), 1); + + // Inversion. + assert!(eq(&val_minus_7, &neg(&val_7)), 1); + assert!(std::option::is_none(&inv(&val_0)), 1); + + // Squaring. + let val_x = rand_insecure(); + assert!(eq(&mul(&val_x, &val_x), &sqr(&val_x)), 1); + } + + #[test_only] + const Q_SERIALIZED: vector = x"47fd7cd8168c203c8dca7168916a81975d588181b64550b829a031e1724e6430"; + #[test_only] + const FQ_VAL_0_SERIALIZED_LSB: vector = x"0000000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FQ_VAL_1_SERIALIZED_LSB: vector = x"0100000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FQ_VAL_7_SERIALIZED_LSB: vector = x"0700000000000000000000000000000000000000000000000000000000000000"; + #[test_only] + const FQ_VAL_7_SERIALIZED_MSB: vector = x"0000000000000000000000000000000000000000000000000000000000000007"; + #[test_only] + const FQ_VAL_7_NEG_SERIALIZED_LSB: vector = x"40fd7cd8168c203c8dca7168916a81975d588181b64550b829a031e1724e6430"; + + #[test(fx = @std)] + fun test_fq(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Constants. + assert!(Q_SERIALIZED == order(), 1); + + // Serialization/deserialization. + let val_0 = zero(); + let val_1 = one(); + assert!(FQ_VAL_0_SERIALIZED_LSB == serialize(&val_0), 1); + assert!(FQ_VAL_1_SERIALIZED_LSB == serialize(&val_1), 1); + let val_7 = from_u64(7); + let val_7_2nd = std::option::extract(&mut deserialize(&FQ_VAL_7_SERIALIZED_LSB)); + let val_7_3rd = std::option::extract(&mut deserialize(&FQ_VAL_7_SERIALIZED_MSB)); + assert!(eq(&val_7, &val_7_2nd), 1); + assert!(eq(&val_7, &val_7_3rd), 1); + assert!(FQ_VAL_7_SERIALIZED_LSB == serialize(&val_7), 1); + assert!(FQ_VAL_7_SERIALIZED_MSB == serialize(&val_7), 1); + + // Deserialization should fail if given a byte array of right size but the value is not a member. + assert!(std::option::is_none(&deserialize(&x"47fd7cd8168c203c8dca7168916a81975d588181b64550b829a031e1724e6430")), 1); + assert!(std::option::is_none(&deserialize(&x"30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47")), 1); + + // Deserialization should fail if given a byte array of wrong size. + assert!(std::option::is_none(&deserialize(&x"46fd7cd8168c203c8dca7168916a81975d588181b64550b829a031e1724e643000")), 1); + assert!(std::option::is_none(&deserialize(&x"30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4600")), 1); + assert!(std::option::is_none(&deserialize(&x"ffff")), 1); + assert!(std::option::is_none(&deserialize(&x"ffff")), 1); + + // Negation. + let val_minus_7 = neg(&val_7); + assert!(FQ_VAL_7_NEG_SERIALIZED_LSB == serialize(&val_minus_7), 1); + + // Addition. + let val_9 = from_u64(9); + let val_2 = from_u64(2); + assert!(eq(&val_2, &add(&val_minus_7, &val_9)), 1); + + // Subtraction. + assert!(eq(&val_9, &sub(&val_2, &val_minus_7)), 1); + + // Multiplication. + let val_63 = from_u64(63); + assert!(eq(&val_63, &mul(&val_7, &val_9)), 1); + + // division. + let val_0 = from_u64(0); + assert!(eq(&val_7, &std::option::extract(&mut div(&val_63, &val_9))), 1); + assert!(std::option::is_none(&div(&val_63, &val_0)), 1); + + // Inversion. + assert!(eq(&val_minus_7, &neg(&val_7)), 1); + assert!(std::option::is_none(&inv(&val_0)), 1); + + // Squaring. + let val_x = rand_insecure(); + assert!(eq(&mul(&val_x, &val_x), &sqr(&val_x)), 1); + } + + #[test(fx = @std)] + fun test_pairing(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // pairing(a*P,b*Q) == (a*b)*pairing(P,Q) + let element_p = rand_insecure(); + let element_q = rand_insecure(); + let a = rand_insecure(); + let b = rand_insecure(); + let gt_element = pairing(&scalar_mul(&element_p, &a), &scalar_mul(&element_q, &b)); + let gt_element_another = scalar_mul(&pairing(&element_p, &element_q), &mul(&a, &b)); + assert!(eq(>_element, >_element_another), 1); + } + + #[test(fx = @std)] + fun test_multi_pairing(fx: signer) { + enable_cryptography_algebra_natives(&fx); + + // Will compute e(a0*P0,b0*Q0)+e(a1*P1,b1*Q1)+e(a2*P2,b2*Q2). + let a0 = rand_insecure(); + let a1 = rand_insecure(); + let a2 = rand_insecure(); + let element_p0 = rand_insecure(); + let element_p1 = rand_insecure(); + let element_p2 = rand_insecure(); + let p0_a0 = scalar_mul(&element_p0, &a0); + let p1_a1 = scalar_mul(&element_p1, &a1); + let p2_a2 = scalar_mul(&element_p2, &a2); + let b0 = rand_insecure(); + let b1 = rand_insecure(); + let b2 = rand_insecure(); + let element_q0 = rand_insecure(); + let element_q1 = rand_insecure(); + let element_q2 = rand_insecure(); + let q0_b0 = scalar_mul(&element_q0, &b0); + let q1_b1 = scalar_mul(&element_q1, &b1); + let q2_b2 = scalar_mul(&element_q2, &b2); + + // Naive method. + let n0 = pairing(&p0_a0, &q0_b0); + let n1 = pairing(&p1_a1, &q1_b1); + let n2 = pairing(&p2_a2, &q2_b2); + let n = zero(); + n = add(&n, &n0); + n = add(&n, &n1); + n = add(&n, &n2); + + // Efficient API. + let m = multi_pairing(&vector[p0_a0, p1_a1, p2_a2], &vector[q0_b0, q1_b1, q2_b2]); + assert!(eq(&n, &m), 1); + } + + #[test(fx = @std)] + #[expected_failure(abort_code = 0x010002, location = aptos_std::crypto_algebra)] + fun test_multi_pairing_should_abort_when_sizes_mismatch(fx: signer) { + enable_cryptography_algebra_natives(&fx); + let g1_elements = vector[rand_insecure()]; + let g2_elements = vector[rand_insecure(), rand_insecure()]; + multi_pairing(&g1_elements, &g2_elements); + } + + #[test(fx = @std)] + #[expected_failure(abort_code = 0x010002, location = aptos_std::crypto_algebra)] + fun test_multi_scalar_mul_should_abort_when_sizes_mismatch(fx: signer) { + enable_cryptography_algebra_natives(&fx); + let elements = vector[rand_insecure()]; + let scalars = vector[rand_insecure(), rand_insecure()]; + multi_scalar_mul(&elements, &scalars); + } + + #[test_only] + /// The maximum number of `G1` elements that can be created in a transaction, + /// calculated by the current memory limit (1MB) and the in-mem G1 representation size (96 bytes per element). + const G1_NUM_MAX: u64 = 1048576 / 96; + + #[test(fx = @std)] + fun test_memory_limit(fx: signer) { + enable_cryptography_algebra_natives(&fx); + let remaining = G1_NUM_MAX; + while (remaining > 0) { + zero(); + remaining = remaining - 1; + } + } + + #[test(fx = @std)] + #[expected_failure(abort_code = 0x090003, location = std::crypto_algebra)] + fun test_memory_limit_exceeded_with_g1(fx: signer) { + enable_cryptography_algebra_natives(&fx); + let remaining = G1_NUM_MAX + 1; + while (remaining > 0) { + zero(); + remaining = remaining - 1; + } + } + + // + // (Tests end here.) + // + +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/capability.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/capability.move new file mode 100644 index 000000000..b61c18ccc --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/capability.move @@ -0,0 +1,193 @@ +/// A module which defines the basic concept of +/// [*capabilities*](https://en.wikipedia.org/wiki/Capability-based_security) for managing access control. +/// +/// EXPERIMENTAL +/// +/// # Overview +/// +/// A capability is a unforgeable token which testifies that a signer has authorized a certain operation. +/// The token is valid during the transaction where it is obtained. Since the type `capability::Cap` has +/// no ability to be stored in global memory, capabilities cannot leak out of a transaction. For every function +/// called within a transaction which has a capability as a parameter, it is guaranteed that the capability +/// has been obtained via a proper signer-based authorization step previously in the transaction's execution. +/// +/// ## Usage +/// +/// Initializing and acquiring capabilities is usually encapsulated in a module with a type +/// tag which can only be constructed by this module. +/// +/// ``` +/// module Pkg::Feature { +/// use std::capability::Cap; +/// +/// /// A type tag used in Cap. Only this module can create an instance, +/// /// and there is no public function other than Self::acquire which returns a value of this type. +/// /// This way, this module has full control how Cap is given out. +/// struct Feature has drop {} +/// +/// /// Initializes this module. +/// public fun initialize(s: &signer) { +/// // Create capability. This happens once at module initialization time. +/// // One needs to provide a witness for being the owner of Feature +/// // in the 2nd parameter. +/// <> +/// capability::create(s, &Feature{}); +/// } +/// +/// /// Acquires the capability to work with this feature. +/// public fun acquire(s: &signer): Cap { +/// <> +/// capability::acquire(s, &Feature{}); +/// } +/// +/// /// Does something related to the feature. The caller must pass a Cap. +/// public fun do_something(_cap: Cap) { ... } +/// } +/// ``` +/// +/// ## Delegation +/// +/// Capabilities come with the optional feature of *delegation*. Via `Self::delegate`, an owner of a capability +/// can designate another signer to be also capable of acquiring the capability. Like the original creator, +/// the delegate needs to present his signer to obtain the capability in his transactions. Delegation can +/// be revoked via `Self::revoke`, removing this access right from the delegate. +/// +/// While the basic authorization mechanism for delegates is the same as with core capabilities, the +/// target of delegation might be subject of restrictions which need to be specified and verified. This can +/// be done via global invariants in the specification language. For example, in order to prevent delegation +/// all together for a capability, one can use the following invariant: +/// +/// ``` +/// invariant forall a: address where capability::spec_has_cap(a): +/// len(capability::spec_delegates(a)) == 0; +/// ``` +/// +/// Similarly, the following invariant would enforce that delegates, if existent, must satisfy a certain +/// predicate: +/// +/// ``` +/// invariant forall a: address where capability::spec_has_cap(a): +/// forall d in capability::spec_delegates(a): +/// is_valid_delegate_for_feature(d); +/// ``` +/// +module aptos_std::capability { + use std::error; + use std::signer; + use std::vector; + + /// Capability resource already exists on the specified account + const ECAPABILITY_ALREADY_EXISTS: u64 = 1; + /// Capability resource not found + const ECAPABILITY_NOT_FOUND: u64 = 2; + /// Account does not have delegated permissions + const EDELEGATE: u64 = 3; + + /// The token representing an acquired capability. Cannot be stored in memory, but copied and dropped freely. + struct Cap has copy, drop { + root: address + } + + /// A linear version of a capability token. This can be used if an acquired capability should be enforced + /// to be used only once for an authorization. + struct LinearCap has drop { + root: address + } + + /// An internal data structure for representing a configured capability. + struct CapState has key { + delegates: vector
+ } + + /// An internal data structure for representing a configured delegated capability. + struct CapDelegateState has key { + root: address + } + + /// Creates a new capability class, owned by the passed signer. A caller must pass a witness that + /// they own the `Feature` type parameter. + public fun create(owner: &signer, _feature_witness: &Feature) { + let addr = signer::address_of(owner); + assert!(!exists>(addr), error::already_exists(ECAPABILITY_ALREADY_EXISTS)); + move_to>(owner, CapState { delegates: vector::empty() }); + } + + /// Acquires a capability token. Only the owner of the capability class, or an authorized delegate, + /// can succeed with this operation. A caller must pass a witness that they own the `Feature` type + /// parameter. + public fun acquire(requester: &signer, _feature_witness: &Feature): Cap + acquires CapState, CapDelegateState { + Cap { root: validate_acquire(requester) } + } + + /// Acquires a linear capability token. It is up to the module which owns `Feature` to decide + /// whether to expose a linear or non-linear capability. + public fun acquire_linear(requester: &signer, _feature_witness: &Feature): LinearCap + acquires CapState, CapDelegateState { + LinearCap { root: validate_acquire(requester) } + } + + /// Helper to validate an acquire. Returns the root address of the capability. + fun validate_acquire(requester: &signer): address + acquires CapState, CapDelegateState { + let addr = signer::address_of(requester); + if (exists>(addr)) { + let root_addr = borrow_global>(addr).root; + // double check that requester is actually registered as a delegate + assert!(exists>(root_addr), error::invalid_state(EDELEGATE)); + assert!(vector::contains(&borrow_global>(root_addr).delegates, &addr), + error::invalid_state(EDELEGATE)); + root_addr + } else { + assert!(exists>(addr), error::not_found(ECAPABILITY_NOT_FOUND)); + addr + } + } + + /// Returns the root address associated with the given capability token. Only the owner + /// of the feature can do this. + public fun root_addr(cap: Cap, _feature_witness: &Feature): address { + cap.root + } + + /// Returns the root address associated with the given linear capability token. + public fun linear_root_addr(cap: LinearCap, _feature_witness: &Feature): address { + cap.root + } + + /// Registers a delegation relation. If the relation already exists, this function does + /// nothing. + // TODO: explore whether this should be idempotent like now or abort + public fun delegate(cap: Cap, _feature_witness: &Feature, to: &signer) + acquires CapState { + let addr = signer::address_of(to); + if (exists>(addr)) return; + move_to(to, CapDelegateState { root: cap.root }); + add_element(&mut borrow_global_mut>(cap.root).delegates, addr); + } + + /// Revokes a delegation relation. If no relation exists, this function does nothing. + // TODO: explore whether this should be idempotent like now or abort + public fun revoke(cap: Cap, _feature_witness: &Feature, from: address) + acquires CapState, CapDelegateState + { + if (!exists>(from)) return; + let CapDelegateState { root: _root } = move_from>(from); + remove_element(&mut borrow_global_mut>(cap.root).delegates, &from); + } + + /// Helper to remove an element from a vector. + fun remove_element(v: &mut vector, x: &E) { + let (found, index) = vector::index_of(v, x); + if (found) { + vector::remove(v, index); + } + } + + /// Helper to add an element to a vector. + fun add_element(v: &mut vector, x: E) { + if (!vector::contains(v, &x)) { + vector::push_back(v, x) + } + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/comparator.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/comparator.move new file mode 100644 index 000000000..869b486b4 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/comparator.move @@ -0,0 +1,173 @@ +/// Provides a framework for comparing two elements +module aptos_std::comparator { + use std::bcs; + use std::vector; + + const EQUAL: u8 = 0; + const SMALLER: u8 = 1; + const GREATER: u8 = 2; + + struct Result has drop { + inner: u8, + } + + public fun is_equal(result: &Result): bool { + result.inner == EQUAL + } + + public fun is_smaller_than(result: &Result): bool { + result.inner == SMALLER + } + + public fun is_greater_than(result: &Result): bool { + result.inner == GREATER + } + + // Performs a comparison of two types after BCS serialization. + // BCS uses little endian encoding for all integer types, + // so comparison between primitive integer types will not behave as expected. + // For example, 1(0x1) will be larger than 256(0x100) after BCS serialization. + public fun compare(left: &T, right: &T): Result { + let left_bytes = bcs::to_bytes(left); + let right_bytes = bcs::to_bytes(right); + + compare_u8_vector(left_bytes, right_bytes) + } + + // Performs a comparison of two vectors or byte vectors + public fun compare_u8_vector(left: vector, right: vector): Result { + let left_length = vector::length(&left); + let right_length = vector::length(&right); + + let idx = 0; + + while (idx < left_length && idx < right_length) { + let left_byte = *vector::borrow(&left, idx); + let right_byte = *vector::borrow(&right, idx); + + if (left_byte < right_byte) { + return Result { inner: SMALLER } + } else if (left_byte > right_byte) { + return Result { inner: GREATER } + }; + idx = idx + 1; + }; + + if (left_length < right_length) { + Result { inner: SMALLER } + } else if (left_length > right_length) { + Result { inner: GREATER } + } else { + Result { inner: EQUAL } + } + } + + #[test] + public fun test_strings() { + use std::string; + + let value0 = string::utf8(b"alpha"); + let value1 = string::utf8(b"beta"); + let value2 = string::utf8(b"betaa"); + + assert!(is_equal(&compare(&value0, &value0)), 0); + assert!(is_equal(&compare(&value1, &value1)), 1); + assert!(is_equal(&compare(&value2, &value2)), 2); + + assert!(is_greater_than(&compare(&value0, &value1)), 3); + assert!(is_smaller_than(&compare(&value1, &value0)), 4); + + assert!(is_smaller_than(&compare(&value0, &value2)), 5); + assert!(is_greater_than(&compare(&value2, &value0)), 6); + + assert!(is_smaller_than(&compare(&value1, &value2)), 7); + assert!(is_greater_than(&compare(&value2, &value1)), 8); + } + + #[test] + #[expected_failure] + public fun test_integer() { + // 1(0x1) will be larger than 256(0x100) after BCS serialization. + let value0: u128 = 1; + let value1: u128 = 256; + + assert!(is_equal(&compare(&value0, &value0)), 0); + assert!(is_equal(&compare(&value1, &value1)), 1); + + assert!(is_smaller_than(&compare(&value0, &value1)), 2); + assert!(is_greater_than(&compare(&value1, &value0)), 3); + } + + #[test] + public fun test_u128() { + let value0: u128 = 5; + let value1: u128 = 152; + let value2: u128 = 511; // 0x1ff + + assert!(is_equal(&compare(&value0, &value0)), 0); + assert!(is_equal(&compare(&value1, &value1)), 1); + assert!(is_equal(&compare(&value2, &value2)), 2); + + assert!(is_smaller_than(&compare(&value0, &value1)), 2); + assert!(is_greater_than(&compare(&value1, &value0)), 3); + + assert!(is_smaller_than(&compare(&value0, &value2)), 3); + assert!(is_greater_than(&compare(&value2, &value0)), 4); + + assert!(is_smaller_than(&compare(&value1, &value2)), 5); + assert!(is_greater_than(&compare(&value2, &value1)), 6); + } + + #[test_only] + struct Complex has drop { + value0: vector, + value1: u8, + value2: u64, + } + + #[test] + public fun test_complex() { + let value0_0 = vector::empty(); + vector::push_back(&mut value0_0, 10); + vector::push_back(&mut value0_0, 9); + vector::push_back(&mut value0_0, 5); + + let value0_1 = vector::empty(); + vector::push_back(&mut value0_1, 10); + vector::push_back(&mut value0_1, 9); + vector::push_back(&mut value0_1, 5); + vector::push_back(&mut value0_1, 1); + + let base = Complex { + value0: value0_0, + value1: 13, + value2: 41, + }; + + let other_0 = Complex { + value0: value0_1, + value1: 13, + value2: 41, + }; + + let other_1 = Complex { + value0: copy value0_0, + value1: 14, + value2: 41, + }; + + let other_2 = Complex { + value0: value0_0, + value1: 13, + value2: 42, + }; + + assert!(is_equal(&compare(&base, &base)), 0); + assert!(is_smaller_than(&compare(&base, &other_0)), 1); + assert!(is_greater_than(&compare(&other_0, &base)), 2); + assert!(is_smaller_than(&compare(&base, &other_1)), 3); + assert!(is_greater_than(&compare(&other_1, &base)), 4); + assert!(is_smaller_than(&compare(&base, &other_2)), 5); + assert!(is_greater_than(&compare(&other_2, &base)), 6); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/copyable_any.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/copyable_any.move new file mode 100644 index 000000000..b12303a3f --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/copyable_any.move @@ -0,0 +1,45 @@ +module aptos_std::copyable_any { + use aptos_std::type_info; + use aptos_std::from_bcs::from_bytes; + use std::bcs; + use std::error; + use std::string::String; + + /// The type provided for `unpack` is not the same as was given for `pack`. + const ETYPE_MISMATCH: u64 = 0; + + /// The same as `any::Any` but with the copy ability. + struct Any has drop, store, copy { + type_name: String, + data: vector + } + + /// Pack a value into the `Any` representation. Because Any can be stored, dropped, and copied this is + /// also required from `T`. + public fun pack(x: T): Any { + Any { + type_name: type_info::type_name(), + data: bcs::to_bytes(&x) + } + } + + /// Unpack a value from the `Any` representation. This aborts if the value has not the expected type `T`. + public fun unpack(x: Any): T { + assert!(type_info::type_name() == x.type_name, error::invalid_argument(ETYPE_MISMATCH)); + from_bytes(x.data) + } + + /// Returns the type name of this Any + public fun type_name(x: &Any): &String { + &x.type_name + } + + #[test_only] + struct S has store, drop, copy { x: u64 } + + #[test] + fun test_any() { + assert!(unpack(pack(22)) == 22, 1); + assert!(unpack(pack(S { x: 22 })) == S { x: 22 }, 2); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/crypto_algebra.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/crypto_algebra.move new file mode 100644 index 000000000..b31f028f8 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/crypto_algebra.move @@ -0,0 +1,351 @@ +/// This module provides generic structs/functions for operations of algebraic structures (e.g. fields and groups), +/// which can be used to build generic cryptographic schemes atop. +/// E.g., a Groth16 ZK proof verifier can be built to work over any pairing supported in this module. +/// +/// In general, every structure implements basic operations like (de)serialization, equality check, random sampling. +/// +/// A group may also implement the following operations. (Additive group notation is assumed.) +/// - `order()` for getting the group order. +/// - `zero()` for getting the group identity. +/// - `one()` for getting the group generator (if exists). +/// - `neg()` for group element inversion. +/// - `add()` for group operation (i.e., a group addition). +/// - `sub()` for group element subtraction. +/// - `double()` for efficient doubling. +/// - `scalar_mul()` for group scalar multiplication. +/// - `multi_scalar_mul()` for efficient group multi-scalar multiplication. +/// - `hash_to()` for hash-to-group. +/// +/// A field may also implement the following operations. +/// - `zero()` for getting the field additive identity. +/// - `one()` for getting the field multiplicative identity. +/// - `add()` for field addition. +/// - `sub()` for field subtraction. +/// - `mul()` for field multiplication. +/// - `div()` for field division. +/// - `neg()` for field negation. +/// - `inv()` for field inversion. +/// - `sqr()` for efficient field element squaring. +/// - `from_u64()` for quick conversion from u64 to field element. +/// +/// For 3 groups that admit a bilinear map, `pairing()` and `multi_pairing()` may be implemented. +/// +/// For a subset/superset relationship between 2 structures, `upcast()` and `downcast()` may be implemented. +/// E.g., in BLS12-381 pairing, since `Gt` is a subset of `Fq12`, +/// `upcast()` and `downcast()` will be supported. +/// +/// See `*_algebra.move` for currently implemented algebraic structures. +module aptos_std::crypto_algebra { + use std::option::{Option, some, none}; + use std::features; + + const E_NOT_IMPLEMENTED: u64 = 1; + const E_NON_EQUAL_LENGTHS: u64 = 2; + const E_TOO_MUCH_MEMORY_USED: u64 = 3; + + /// This struct represents an element of a structure `S`. + struct Element has copy, drop { + handle: u64 + } + + // + // Public functions begin. + // + + /// Check if `x == y` for elements `x` and `y` of a structure `S`. + public fun eq(x: &Element, y: &Element): bool { + abort_unless_cryptography_algebra_natives_enabled(); + eq_internal(x.handle, y.handle) + } + + /// Convert a u64 to an element of a structure `S`. + public fun from_u64(value: u64): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: from_u64_internal(value) + } + } + + /// Return the additive identity of field `S`, or the identity of group `S`. + public fun zero(): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: zero_internal() + } + } + + /// Return the multiplicative identity of field `S`, or a fixed generator of group `S`. + public fun one(): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: one_internal() + } + } + + /// Compute `-x` for an element `x` of a structure `S`. + public fun neg(x: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: neg_internal(x.handle) + } + } + + /// Compute `x + y` for elements `x` and `y` of structure `S`. + public fun add(x: &Element, y: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: add_internal(x.handle, y.handle) + } + } + + /// Compute `x - y` for elements `x` and `y` of a structure `S`. + public fun sub(x: &Element, y: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: sub_internal(x.handle, y.handle) + } + } + + /// Compute `x * y` for elements `x` and `y` of a structure `S`. + public fun mul(x: &Element, y: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: mul_internal(x.handle, y.handle) + } + } + + /// Try computing `x / y` for elements `x` and `y` of a structure `S`. + /// Return none if `y` does not have a multiplicative inverse in the structure `S` + /// (e.g., when `S` is a field, and `y` is zero). + public fun div(x: &Element, y: &Element): Option> { + abort_unless_cryptography_algebra_natives_enabled(); + let (succ, handle) = div_internal(x.handle, y.handle); + if (succ) { + some(Element { handle }) + } else { + none() + } + } + + /// Compute `x^2` for an element `x` of a structure `S`. Faster and cheaper than `mul(x, x)`. + public fun sqr(x: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: sqr_internal(x.handle) + } + } + + /// Try computing `x^(-1)` for an element `x` of a structure `S`. + /// Return none if `x` does not have a multiplicative inverse in the structure `S` + /// (e.g., when `S` is a field, and `x` is zero). + public fun inv(x: &Element): Option> { + abort_unless_cryptography_algebra_natives_enabled(); + let (succeeded, handle) = inv_internal(x.handle); + if (succeeded) { + let scalar = Element { handle }; + some(scalar) + } else { + none() + } + } + + /// Compute `2*P` for an element `P` of a structure `S`. Faster and cheaper than `add(P, P)`. + public fun double(element_p: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: double_internal(element_p.handle) + } + } + + /// Compute `k[0]*P[0]+...+k[n-1]*P[n-1]`, where + /// `P[]` are `n` elements of group `G` represented by parameter `elements`, and + /// `k[]` are `n` elements of the scalarfield `S` of group `G` represented by parameter `scalars`. + /// + /// Abort with code `std::error::invalid_argument(E_NON_EQUAL_LENGTHS)` if the sizes of `elements` and `scalars` do not match. + public fun multi_scalar_mul(elements: &vector>, scalars: &vector>): Element { + let element_handles = handles_from_elements(elements); + let scalar_handles = handles_from_elements(scalars); + Element { + handle: multi_scalar_mul_internal(element_handles, scalar_handles) + } + } + + /// Compute `k*P`, where `P` is an element of a group `G` and `k` is an element of the scalar field `S` associated to the group `G`. + public fun scalar_mul(element_p: &Element, scalar_k: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: scalar_mul_internal(element_p.handle, scalar_k.handle) + } + } + + /// Efficiently compute `e(P[0],Q[0])+...+e(P[n-1],Q[n-1])`, + /// where `e: (G1,G2) -> (Gt)` is the pairing function from groups `(G1,G2)` to group `Gt`, + /// `P[]` are `n` elements of group `G1` represented by parameter `g1_elements`, and + /// `Q[]` are `n` elements of group `G2` represented by parameter `g2_elements`. + /// + /// Abort with code `std::error::invalid_argument(E_NON_EQUAL_LENGTHS)` if the sizes of `g1_elements` and `g2_elements` do not match. + /// + /// NOTE: we are viewing the target group `Gt` of the pairing as an additive group, + /// rather than a multiplicative one (which is typically the case). + public fun multi_pairing(g1_elements: &vector>, g2_elements: &vector>): Element { + abort_unless_cryptography_algebra_natives_enabled(); + let g1_handles = handles_from_elements(g1_elements); + let g2_handles = handles_from_elements(g2_elements); + Element { + handle: multi_pairing_internal(g1_handles, g2_handles) + } + } + + /// Compute the pairing function (a.k.a., bilinear map) on a `G1` element and a `G2` element. + /// Return an element in the target group `Gt`. + public fun pairing(element_1: &Element, element_2: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: pairing_internal(element_1.handle, element_2.handle) + } + } + + /// Try deserializing a byte array to an element of an algebraic structure `S` using a given serialization format `F`. + /// Return none if the deserialization failed. + public fun deserialize(bytes: &vector): Option> { + abort_unless_cryptography_algebra_natives_enabled(); + let (succeeded, handle) = deserialize_internal(bytes); + if (succeeded) { + some(Element { handle }) + } else { + none() + } + } + + /// Serialize an element of an algebraic structure `S` to a byte array using a given serialization format `F`. + public fun serialize(element: &Element): vector { + abort_unless_cryptography_algebra_natives_enabled(); + serialize_internal(element.handle) + } + + /// Get the order of structure `S`, a big integer little-endian encoded as a byte array. + public fun order(): vector { + abort_unless_cryptography_algebra_natives_enabled(); + order_internal() + } + + /// Cast an element of a structure `S` to a parent structure `L`. + public fun upcast(element: &Element): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: upcast_internal(element.handle) + } + } + + /// Try casting an element `x` of a structure `L` to a sub-structure `S`. + /// Return none if `x` is not a member of `S`. + /// + /// NOTE: Membership check in `S` is performed inside, which can be expensive, depending on the structures `L` and `S`. + public fun downcast(element_x: &Element): Option> { + abort_unless_cryptography_algebra_natives_enabled(); + let (succ, new_handle) = downcast_internal(element_x.handle); + if (succ) { + some(Element { handle: new_handle }) + } else { + none() + } + } + + /// Hash an arbitrary-length byte array `msg` into structure `S` with a domain separation tag `dst` + /// using the given hash-to-structure suite `H`. + /// + /// NOTE: some hashing methods do not accept a `dst` and will abort if a non-empty one is provided. + public fun hash_to(dst: &vector, msg: &vector): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: hash_to_internal(dst, msg) + } + } + + #[test_only] + /// Generate a random element of an algebraic structure `S`. + public fun rand_insecure(): Element { + abort_unless_cryptography_algebra_natives_enabled(); + Element { + handle: rand_insecure_internal() + } + } + + // + // (Public functions end here.) + // Private functions begin. + // + + fun abort_unless_cryptography_algebra_natives_enabled() { + if (features::cryptography_algebra_enabled()) return; + abort(std::error::not_implemented(0)) + } + + #[test_only] + public fun enable_cryptography_algebra_natives(fx: &signer) { + std::features::change_feature_flags_for_testing(fx, vector[std::features::get_cryptography_algebra_natives_feature()], vector[]); + } + + fun handles_from_elements(elements: &vector>): vector { + let num_elements = std::vector::length(elements); + let element_handles = std::vector::empty(); + let i = 0; + while ({ + spec { + invariant len(element_handles) == i; + invariant forall k in 0..i: element_handles[k] == elements[k].handle; + }; + i < num_elements + }) { + std::vector::push_back(&mut element_handles, std::vector::borrow(elements, i).handle); + i = i + 1; + }; + element_handles + } + + // + // (Private functions end here.) + // Native functions begin. + // + + native fun add_internal(handle_1: u64, handle_2: u64): u64; + native fun deserialize_internal(bytes: &vector): (bool, u64); + native fun div_internal(handle_1: u64, handle_2: u64): (bool, u64); + native fun double_internal(element_handle: u64): u64; + native fun downcast_internal(handle: u64): (bool, u64); + native fun from_u64_internal(value: u64): u64; + native fun eq_internal(handle_1: u64, handle_2: u64): bool; + native fun hash_to_internal(dst: &vector, bytes: &vector): u64; + native fun inv_internal(handle: u64): (bool, u64); + #[test_only] + native fun rand_insecure_internal(): u64; + native fun mul_internal(handle_1: u64, handle_2: u64): u64; + native fun multi_pairing_internal(g1_handles: vector, g2_handles: vector): u64; + native fun multi_scalar_mul_internal(element_handles: vector, scalar_handles: vector): u64; + native fun neg_internal(handle: u64): u64; + native fun one_internal(): u64; + native fun order_internal(): vector; + native fun pairing_internal(g1_handle: u64, g2_handle: u64): u64; + native fun scalar_mul_internal(element_handle: u64, scalar_handle: u64): u64; + native fun serialize_internal(handle: u64): vector; + native fun sqr_internal(handle: u64): u64; + native fun sub_internal(handle_1: u64, handle_2: u64): u64; + native fun upcast_internal(handle: u64): u64; + native fun zero_internal(): u64; + + // + // (Native functions end here.) + // Tests begin. + // + + #[test_only] + struct MysteriousGroup {} + + #[test(fx = @std)] + #[expected_failure(abort_code = 0x0c0001, location = Self)] + fun test_generic_operation_should_abort_with_unsupported_structures(fx: signer) { + enable_cryptography_algebra_natives(&fx); + let _ = order(); + } + // Tests end. +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/debug.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/debug.move new file mode 100644 index 000000000..21b707c7a --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/debug.move @@ -0,0 +1,278 @@ +/// Module providing debug functionality. +module aptos_std::debug { + use std::string::String; + + public fun print(x: &T) { + native_print(format(x)); + } + + public fun print_stack_trace() { + native_print(native_stack_trace()); + } + + inline fun format(x: &T): String { + aptos_std::string_utils::debug_string(x) + } + + native fun native_print(x: String); + native fun native_stack_trace(): String; + + #[test_only] + use std::vector; + + #[test_only] + struct Foo has drop {} + #[test_only] + struct Bar has drop { x: u128, y: Foo, z: bool } + #[test_only] + struct Box has drop { x: T } + + #[test_only] + struct GenericStruct has drop { + val: u64, + } + + #[test_only] + struct TestInner has drop { + val: u128, + vec: vector, + msgs: vector> + } + + #[test_only] + struct TestStruct has drop { + addr: address, + number: u8, + bytes: vector, + name: String, + vec: vector, + } + + #[test_only] + fun assert_equal(x: &T, expected: vector) { + if (std::string::bytes(&format(x)) != &expected) { + print(&format(x)); + print(&std::string::utf8(expected)); + assert!(false, 1); + }; + } + + #[test_only] + fun assert_string_equal(x: vector, expected: vector) { + assert!(std::string::bytes(&format(&std::string::utf8(x))) == &expected, 1); + } + + #[test] + public fun test() { + let x = 42; + assert_equal(&x, b"42"); + + let v = vector::empty(); + vector::push_back(&mut v, 100); + vector::push_back(&mut v, 200); + vector::push_back(&mut v, 300); + assert_equal(&v, b"[ 100, 200, 300 ]"); + + let foo = Foo {}; + assert_equal(&foo, b"0x1::debug::Foo {\n dummy_field: false\n}"); + + let bar = Bar { x: 404, y: Foo {}, z: true }; + assert_equal(&bar, b"0x1::debug::Bar {\n x: 404,\n y: 0x1::debug::Foo {\n dummy_field: false\n },\n z: true\n}"); + + let box = Box { x: Foo {} }; + assert_equal(&box, b"0x1::debug::Box<0x1::debug::Foo> {\n x: 0x1::debug::Foo {\n dummy_field: false\n }\n}"); + } + + #[test] + fun test_print_string() { + let str_bytes = b"Hello, sane Move debugging!"; + + assert_equal(&str_bytes, b"0x48656c6c6f2c2073616e65204d6f766520646562756767696e6721"); + + let str = std::string::utf8(str_bytes); + assert_equal(&str, b"\"Hello, sane Move debugging!\""); + } + + #[test] + fun test_print_quoted_string() { + let str_bytes = b"Can you say \"Hel\\lo\"?"; + + let str = std::string::utf8(str_bytes); + assert_equal(&str, b"\"Can you say \\\"Hel\\\\lo\\\"?\""); + } + + + #[test_only] + use std::features; + #[test(s = @0x123)] + fun test_print_primitive_types(s: signer) { + let u8 = 255u8; + assert_equal(&u8, b"255"); + + let u16 = 65535u16; + assert_equal(&u16, b"65535"); + + let u32 = 4294967295u32; + assert_equal(&u32, b"4294967295"); + + let u64 = 18446744073709551615u64; + assert_equal(&u64, b"18446744073709551615"); + + let u128 = 340282366920938463463374607431768211455u128; + assert_equal(&u128, b"340282366920938463463374607431768211455"); + + let u256 = 115792089237316195423570985008687907853269984665640564039457584007913129639935u256; + assert_equal(&u256, b"115792089237316195423570985008687907853269984665640564039457584007913129639935"); + + let bool = false; + assert_equal(&bool, b"false"); + + let bool = true; + assert_equal(&bool, b"true"); + + let a = @0x1234c0ffee; + assert_equal(&a, b"@0x1234c0ffee"); + + if (features::signer_native_format_fix_enabled()) { + let signer = s; + assert_equal(&signer, b"signer(@0x123)"); + } + } + + const MSG_1 : vector = b"abcdef"; + const MSG_2 : vector = b"123456"; + + #[test] + fun test_print_struct() { + let obj = TestInner { + val: 100, + vec: vector[200u128, 400u128], + msgs: vector[MSG_1, MSG_2], + }; + + assert_equal(&obj, b"0x1::debug::TestInner {\n val: 100,\n vec: [ 200, 400 ],\n msgs: [\n 0x616263646566,\n 0x313233343536\n ]\n}"); + + let obj = TestInner { + val: 10, + vec: vector[], + msgs: vector[], + }; + + assert_equal(&obj, b"0x1::debug::TestInner {\n val: 10,\n vec: [],\n msgs: []\n}"); + } + + #[test(s1 = @0x123, s2 = @0x456)] + fun test_print_vectors(s1: signer, s2: signer) { + let v_u8 = x"ffabcdef"; + assert_equal(&v_u8, b"0xffabcdef"); + + let v_u16 = vector[16u16, 17u16, 18u16, 19u16]; + assert_equal(&v_u16, b"[ 16, 17, 18, 19 ]"); + + let v_u32 = vector[32u32, 33u32, 34u32, 35u32]; + assert_equal(&v_u32, b"[ 32, 33, 34, 35 ]"); + + let v_u64 = vector[64u64, 65u64, 66u64, 67u64]; + assert_equal(&v_u64, b"[ 64, 65, 66, 67 ]"); + + let v_u128 = vector[128u128, 129u128, 130u128, 131u128]; + assert_equal(&v_u128, b"[ 128, 129, 130, 131 ]"); + + let v_u256 = vector[256u256, 257u256, 258u256, 259u256]; + assert_equal(&v_u256, b"[ 256, 257, 258, 259 ]"); + + let v_bool = vector[true, false]; + assert_equal(&v_bool, b"[ true, false ]"); + + let v_addr = vector[@0x1234, @0x5678, @0xabcdef]; + assert_equal(&v_addr, b"[ @0x1234, @0x5678, @0xabcdef ]"); + + if (features::signer_native_format_fix_enabled()) { + let v_signer = vector[s1, s2]; + assert_equal(&v_signer, b"[ signer(@0x123), signer(@0x456) ]"); + }; + + let v = vector[ + TestInner { + val: 4u128, + vec: vector[127u128, 128u128], + msgs: vector[x"00ff", x"abcd"], + }, + TestInner { + val: 8u128 , + vec: vector[128u128, 129u128], + msgs: vector[x"0000"], + } + ]; + assert_equal(&v, b"[\n 0x1::debug::TestInner {\n val: 4,\n vec: [ 127, 128 ],\n msgs: [\n 0x00ff,\n 0xabcd\n ]\n },\n 0x1::debug::TestInner {\n val: 8,\n vec: [ 128, 129 ],\n msgs: [\n 0x0000\n ]\n }\n]"); + } + + #[test(s1 = @0x123, s2 = @0x456)] + fun test_print_vector_of_vectors(s1: signer, s2: signer) { + let v_u8 = vector[x"ffab", x"cdef"]; + assert_equal(&v_u8, b"[\n 0xffab,\n 0xcdef\n]"); + + let v_u16 = vector[vector[16u16, 17u16], vector[18u16, 19u16]]; + assert_equal(&v_u16, b"[\n [ 16, 17 ],\n [ 18, 19 ]\n]"); + + let v_u32 = vector[vector[32u32, 33u32], vector[34u32, 35u32]]; + assert_equal(&v_u32, b"[\n [ 32, 33 ],\n [ 34, 35 ]\n]"); + + let v_u64 = vector[vector[64u64, 65u64], vector[66u64, 67u64]]; + assert_equal(&v_u64, b"[\n [ 64, 65 ],\n [ 66, 67 ]\n]"); + + let v_u128 = vector[vector[128u128, 129u128], vector[130u128, 131u128]]; + assert_equal(&v_u128, b"[\n [ 128, 129 ],\n [ 130, 131 ]\n]"); + + let v_u256 = vector[vector[256u256, 257u256], vector[258u256, 259u256]]; + assert_equal(&v_u256, b"[\n [ 256, 257 ],\n [ 258, 259 ]\n]"); + + let v_bool = vector[vector[true, false], vector[false, true]]; + assert_equal(&v_bool, b"[\n [ true, false ],\n [ false, true ]\n]"); + + let v_addr = vector[vector[@0x1234, @0x5678], vector[@0xabcdef, @0x9999]]; + assert_equal(&v_addr, b"[\n [ @0x1234, @0x5678 ],\n [ @0xabcdef, @0x9999 ]\n]"); + + if (features::signer_native_format_fix_enabled()) { + let v_signer = vector[vector[s1], vector[s2]]; + assert_equal(&v_signer, b"[\n [ signer(@0x123) ],\n [ signer(@0x456) ]\n]"); + }; + + let v = vector[ + vector[ + TestInner { val: 4u128, vec: vector[127u128, 128u128], msgs: vector[] }, + TestInner { val: 8u128 , vec: vector[128u128, 129u128], msgs: vector[] } + ], + vector[ + TestInner { val: 4u128, vec: vector[127u128, 128u128], msgs: vector[] }, + TestInner { val: 8u128 , vec: vector[128u128, 129u128], msgs: vector[] } + ] + ]; + assert_equal(&v, b"[\n [\n 0x1::debug::TestInner {\n val: 4,\n vec: [ 127, 128 ],\n msgs: []\n },\n 0x1::debug::TestInner {\n val: 8,\n vec: [ 128, 129 ],\n msgs: []\n }\n ],\n [\n 0x1::debug::TestInner {\n val: 4,\n vec: [ 127, 128 ],\n msgs: []\n },\n 0x1::debug::TestInner {\n val: 8,\n vec: [ 128, 129 ],\n msgs: []\n }\n ]\n]"); + } + + #[test] + fun test_print_nested_struct() { + let obj = TestStruct { + addr: @0x1, + number: 255u8, + bytes: x"c0ffee", + name: std::string::utf8(b"He\"llo"), + vec: vector[ + TestInner { val: 1, vec: vector[130u128, 131u128], msgs: vector[] }, + TestInner { val: 2, vec: vector[132u128, 133u128], msgs: vector[] } + ], + }; + + assert_equal(&obj, b"0x1::debug::TestStruct {\n addr: @0x1,\n number: 255,\n bytes: 0xc0ffee,\n name: \"He\\\"llo\",\n vec: [\n 0x1::debug::TestInner {\n val: 1,\n vec: [ 130, 131 ],\n msgs: []\n },\n 0x1::debug::TestInner {\n val: 2,\n vec: [ 132, 133 ],\n msgs: []\n }\n ]\n}"); + } + + #[test] + fun test_print_generic_struct() { + let obj = GenericStruct { + val: 60u64, + }; + + assert_equal(&obj, b"0x1::debug::GenericStruct<0x1::debug::Foo> {\n val: 60\n}"); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/ed25519.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/ed25519.move new file mode 100644 index 000000000..0f8d9c812 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/ed25519.move @@ -0,0 +1,262 @@ +/// Contains functions for: +/// +/// 1. [Ed25519](https://en.wikipedia.org/wiki/EdDSA#Ed25519) digital signatures: i.e., EdDSA signatures over Edwards25519 curves with co-factor 8 +/// +module aptos_std::ed25519 { + use std::bcs; + use aptos_std::type_info::{Self, TypeInfo}; + use std::option::{Self, Option}; + + // + // Error codes + // + + /// Wrong number of bytes were given as input when deserializing an Ed25519 public key. + const E_WRONG_PUBKEY_SIZE: u64 = 1; + + /// Wrong number of bytes were given as input when deserializing an Ed25519 signature. + const E_WRONG_SIGNATURE_SIZE: u64 = 2; + + // + // Constants + // + + /// The identifier of the Ed25519 signature scheme, which is used when deriving Aptos authentication keys by hashing + /// it together with an Ed25519 public key. + const SIGNATURE_SCHEME_ID: u8 = 0; + + /// The size of a serialized public key, in bytes. + const PUBLIC_KEY_NUM_BYTES: u64 = 32; + + /// The size of a serialized signature, in bytes. + const SIGNATURE_NUM_BYTES: u64 = 64; + + // + // Structs + // + + #[test_only] + /// This struct holds an Ed25519 secret key that can be used to generate Ed25519 signatures during testing. + struct SecretKey has drop { + bytes: vector + } + + /// A BCS-serializable message, which one can verify signatures on via `signature_verify_strict_t` + struct SignedMessage has drop { + type_info: TypeInfo, + inner: MessageType, + } + + /// An *unvalidated* Ed25519 public key: not necessarily an elliptic curve point, just a sequence of 32 bytes + struct UnvalidatedPublicKey has copy, drop, store { + bytes: vector + } + + /// A *validated* Ed25519 public key: not necessarily a prime-order point, could be mixed-order, but will never be + /// a small-order point. + /// + /// For now, this struct is not used in any verification functions, but it might be in the future. + struct ValidatedPublicKey has copy, drop, store { + bytes: vector + } + + /// A purported Ed25519 signature that can be verified via `signature_verify_strict` or `signature_verify_strict_t`. + struct Signature has copy, drop, store { + bytes: vector + } + + // + // Functions + // + + /// Parses the input 32 bytes as an *unvalidated* Ed25519 public key. + public fun new_unvalidated_public_key_from_bytes(bytes: vector): UnvalidatedPublicKey { + assert!(std::vector::length(&bytes) == PUBLIC_KEY_NUM_BYTES, std::error::invalid_argument(E_WRONG_PUBKEY_SIZE)); + UnvalidatedPublicKey { bytes } + } + + /// Parses the input 32 bytes as a *validated* Ed25519 public key. + public fun new_validated_public_key_from_bytes(bytes: vector): Option { + if (public_key_validate_internal(bytes)) { + option::some(ValidatedPublicKey { + bytes + }) + } else { + option::none() + } + } + + /// Parses the input 64 bytes as a purported Ed25519 signature. + public fun new_signature_from_bytes(bytes: vector): Signature { + assert!(std::vector::length(&bytes) == SIGNATURE_NUM_BYTES, std::error::invalid_argument(E_WRONG_SIGNATURE_SIZE)); + Signature { bytes } + } + + /// Converts a ValidatedPublicKey to an UnvalidatedPublicKey, which can be used in the strict verification APIs. + public fun public_key_to_unvalidated(pk: &ValidatedPublicKey): UnvalidatedPublicKey { + UnvalidatedPublicKey { + bytes: pk.bytes + } + } + + /// Moves a ValidatedPublicKey into an UnvalidatedPublicKey, which can be used in the strict verification APIs. + public fun public_key_into_unvalidated(pk: ValidatedPublicKey): UnvalidatedPublicKey { + UnvalidatedPublicKey { + bytes: pk.bytes + } + } + + /// Serializes an UnvalidatedPublicKey struct to 32-bytes. + public fun unvalidated_public_key_to_bytes(pk: &UnvalidatedPublicKey): vector { + pk.bytes + } + + /// Serializes an ValidatedPublicKey struct to 32-bytes. + public fun validated_public_key_to_bytes(pk: &ValidatedPublicKey): vector { + pk.bytes + } + + /// Serializes a Signature struct to 64-bytes. + public fun signature_to_bytes(sig: &Signature): vector { + sig.bytes + } + + /// Takes in an *unvalidated* public key and attempts to validate it. + /// Returns `Some(ValidatedPublicKey)` if successful and `None` otherwise. + public fun public_key_validate(pk: &UnvalidatedPublicKey): Option { + new_validated_public_key_from_bytes(pk.bytes) + } + + /// Verifies a purported Ed25519 `signature` under an *unvalidated* `public_key` on the specified `message`. + /// This call will validate the public key by checking it is NOT in the small subgroup. + public fun signature_verify_strict( + signature: &Signature, + public_key: &UnvalidatedPublicKey, + message: vector + ): bool { + signature_verify_strict_internal(signature.bytes, public_key.bytes, message) + } + + /// This function is used to verify a signature on any BCS-serializable type T. For now, it is used to verify the + /// proof of private key ownership when rotating authentication keys. + public fun signature_verify_strict_t(signature: &Signature, public_key: &UnvalidatedPublicKey, data: T): bool { + let encoded = SignedMessage { + type_info: type_info::type_of(), + inner: data, + }; + + signature_verify_strict_internal(signature.bytes, public_key.bytes, bcs::to_bytes(&encoded)) + } + + /// Helper method to construct a SignedMessage struct. + public fun new_signed_message(data: T): SignedMessage { + SignedMessage { + type_info: type_info::type_of(), + inner: data, + } + } + + /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + public fun unvalidated_public_key_to_authentication_key(pk: &UnvalidatedPublicKey): vector { + public_key_bytes_to_authentication_key(pk.bytes) + } + + /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + public fun validated_public_key_to_authentication_key(pk: &ValidatedPublicKey): vector { + public_key_bytes_to_authentication_key(pk.bytes) + } + + /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + fun public_key_bytes_to_authentication_key(pk_bytes: vector): vector { + std::vector::push_back(&mut pk_bytes, SIGNATURE_SCHEME_ID); + std::hash::sha3_256(pk_bytes) + } + + #[test_only] + /// Generates an Ed25519 key pair. + public fun generate_keys(): (SecretKey, ValidatedPublicKey) { + let (sk_bytes, pk_bytes) = generate_keys_internal(); + let sk = SecretKey { + bytes: sk_bytes + }; + let pk = ValidatedPublicKey { + bytes: pk_bytes + }; + (sk,pk) + } + + #[test_only] + /// Generates an Ed25519 signature for a given byte array using a given signing key. + public fun sign_arbitrary_bytes(sk: &SecretKey, msg: vector): Signature { + Signature { + bytes: sign_internal(sk.bytes, msg) + } + } + + #[test_only] + /// Generates an Ed25519 signature for given structured data using a given signing key. + public fun sign_struct(sk: &SecretKey, data: T): Signature { + let encoded = new_signed_message(data); + Signature { + bytes: sign_internal(sk.bytes, bcs::to_bytes(&encoded)) + } + } + + // + // Native functions + // + + /// Return `true` if the bytes in `public_key` can be parsed as a valid Ed25519 public key: i.e., it passes + /// points-on-curve and not-in-small-subgroup checks. + /// Returns `false` otherwise. + native fun public_key_validate_internal(bytes: vector): bool; + + /// Return true if the Ed25519 `signature` on `message` verifies against the Ed25519 `public_key`. + /// Returns `false` if either: + /// - `signature` or `public key` are of wrong sizes + /// - `public_key` does not pass points-on-curve or not-in-small-subgroup checks, + /// - `signature` does not pass points-on-curve or not-in-small-subgroup checks, + /// - the signature on `message` does not verify. + native fun signature_verify_strict_internal( + signature: vector, + public_key: vector, + message: vector + ): bool; + + #[test_only] + /// Generates an Ed25519 key pair. + native fun generate_keys_internal(): (vector, vector); + + #[test_only] + /// Generates an Ed25519 signature for a given byte array using a given signing key. + native fun sign_internal(sk: vector, msg: vector): vector; + + // + // Tests + // + + #[test_only] + struct TestMessage has copy, drop { + title: vector, + content: vector, + } + + #[test] + fun test_gen_sign_verify_combo() { + let (sk, vpk) = generate_keys(); + let pk = public_key_into_unvalidated(vpk); + + let msg1: vector = x"0123456789abcdef"; + let sig1 = sign_arbitrary_bytes(&sk, msg1); + assert!(signature_verify_strict(&sig1, &pk, msg1), std::error::invalid_state(1)); + + let msg2 = TestMessage { + title: b"Some Title", + content: b"That is it.", + }; + let sig2 = sign_struct(&sk, copy msg2); + assert!(signature_verify_strict_t(&sig2, &pk, copy msg2), std::error::invalid_state(2)); + } + + +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/fixed_point64.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/fixed_point64.move new file mode 100644 index 000000000..ac864c821 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/fixed_point64.move @@ -0,0 +1,447 @@ +/// Defines a fixed-point numeric type with a 64-bit integer part and +/// a 64-bit fractional part. + +module aptos_std::fixed_point64 { + + /// Define a fixed-point numeric type with 64 fractional bits. + /// This is just a u128 integer but it is wrapped in a struct to + /// make a unique type. This is a binary representation, so decimal + /// values may not be exactly representable, but it provides more + /// than 9 decimal digits of precision both before and after the + /// decimal point (18 digits total). For comparison, double precision + /// floating-point has less than 16 decimal digits of precision, so + /// be careful about using floating-point to convert these values to + /// decimal. + struct FixedPoint64 has copy, drop, store { value: u128 } + + const MAX_U128: u256 = 340282366920938463463374607431768211455; + + /// The denominator provided was zero + const EDENOMINATOR: u64 = 0x10001; + /// The quotient value would be too large to be held in a `u128` + const EDIVISION: u64 = 0x20002; + /// The multiplied value would be too large to be held in a `u128` + const EMULTIPLICATION: u64 = 0x20003; + /// A division by zero was encountered + const EDIVISION_BY_ZERO: u64 = 0x10004; + /// The computed ratio when converting to a `FixedPoint64` would be unrepresentable + const ERATIO_OUT_OF_RANGE: u64 = 0x20005; + /// Abort code on calculation result is negative. + const ENEGATIVE_RESULT: u64 = 0x10006; + + /// Returns x - y. x must be not less than y. + public fun sub(x: FixedPoint64, y: FixedPoint64): FixedPoint64 { + let x_raw = get_raw_value(x); + let y_raw = get_raw_value(y); + assert!(x_raw >= y_raw, ENEGATIVE_RESULT); + create_from_raw_value(x_raw - y_raw) + } + spec sub { + pragma opaque; + aborts_if x.value < y.value with ENEGATIVE_RESULT; + ensures result.value == x.value - y.value; + } + + /// Returns x + y. The result cannot be greater than MAX_U128. + public fun add(x: FixedPoint64, y: FixedPoint64): FixedPoint64 { + let x_raw = get_raw_value(x); + let y_raw = get_raw_value(y); + let result = (x_raw as u256) + (y_raw as u256); + assert!(result <= MAX_U128, ERATIO_OUT_OF_RANGE); + create_from_raw_value((result as u128)) + } + spec add { + pragma opaque; + aborts_if (x.value as u256) + (y.value as u256) > MAX_U128 with ERATIO_OUT_OF_RANGE; + ensures result.value == x.value + y.value; + } + + /// Multiply a u128 integer by a fixed-point number, truncating any + /// fractional part of the product. This will abort if the product + /// overflows. + public fun multiply_u128(val: u128, multiplier: FixedPoint64): u128 { + // The product of two 128 bit values has 256 bits, so perform the + // multiplication with u256 types and keep the full 256 bit product + // to avoid losing accuracy. + let unscaled_product = (val as u256) * (multiplier.value as u256); + // The unscaled product has 64 fractional bits (from the multiplier) + // so rescale it by shifting away the low bits. + let product = unscaled_product >> 64; + // Check whether the value is too large. + assert!(product <= MAX_U128, EMULTIPLICATION); + (product as u128) + } + spec multiply_u128 { + pragma opaque; + include MultiplyAbortsIf; + ensures result == spec_multiply_u128(val, multiplier); + } + spec schema MultiplyAbortsIf { + val: num; + multiplier: FixedPoint64; + aborts_if spec_multiply_u128(val, multiplier) > MAX_U128 with EMULTIPLICATION; + } + spec fun spec_multiply_u128(val: num, multiplier: FixedPoint64): num { + (val * multiplier.value) >> 64 + } + + /// Divide a u128 integer by a fixed-point number, truncating any + /// fractional part of the quotient. This will abort if the divisor + /// is zero or if the quotient overflows. + public fun divide_u128(val: u128, divisor: FixedPoint64): u128 { + // Check for division by zero. + assert!(divisor.value != 0, EDIVISION_BY_ZERO); + // First convert to 256 bits and then shift left to + // add 64 fractional zero bits to the dividend. + let scaled_value = (val as u256) << 64; + let quotient = scaled_value / (divisor.value as u256); + // Check whether the value is too large. + assert!(quotient <= MAX_U128, EDIVISION); + // the value may be too large, which will cause the cast to fail + // with an arithmetic error. + (quotient as u128) + } + spec divide_u128 { + pragma opaque; + include DivideAbortsIf; + ensures result == spec_divide_u128(val, divisor); + } + spec schema DivideAbortsIf { + val: num; + divisor: FixedPoint64; + aborts_if divisor.value == 0 with EDIVISION_BY_ZERO; + aborts_if spec_divide_u128(val, divisor) > MAX_U128 with EDIVISION; + } + spec fun spec_divide_u128(val: num, divisor: FixedPoint64): num { + (val << 64) / divisor.value + } + + /// Create a fixed-point value from a rational number specified by its + /// numerator and denominator. Calling this function should be preferred + /// for using `Self::create_from_raw_value` which is also available. + /// This will abort if the denominator is zero. It will also + /// abort if the numerator is nonzero and the ratio is not in the range + /// 2^-64 .. 2^64-1. When specifying decimal fractions, be careful about + /// rounding errors: if you round to display N digits after the decimal + /// point, you can use a denominator of 10^N to avoid numbers where the + /// very small imprecision in the binary representation could change the + /// rounding, e.g., 0.0125 will round down to 0.012 instead of up to 0.013. + public fun create_from_rational(numerator: u128, denominator: u128): FixedPoint64 { + // If the denominator is zero, this will abort. + // Scale the numerator to have 64 fractional bits, so that the quotient will have 64 + // fractional bits. + let scaled_numerator = (numerator as u256) << 64; + assert!(denominator != 0, EDENOMINATOR); + let quotient = scaled_numerator / (denominator as u256); + assert!(quotient != 0 || numerator == 0, ERATIO_OUT_OF_RANGE); + // Return the quotient as a fixed-point number. We first need to check whether the cast + // can succeed. + assert!(quotient <= MAX_U128, ERATIO_OUT_OF_RANGE); + FixedPoint64 { value: (quotient as u128) } + } + spec create_from_rational { + pragma opaque; + pragma verify_duration_estimate = 1000; // TODO: set because of timeout (property proved). + include CreateFromRationalAbortsIf; + ensures result == spec_create_from_rational(numerator, denominator); + } + spec schema CreateFromRationalAbortsIf { + numerator: u128; + denominator: u128; + let scaled_numerator = (numerator as u256)<< 64; + let scaled_denominator = (denominator as u256); + let quotient = scaled_numerator / scaled_denominator; + aborts_if scaled_denominator == 0 with EDENOMINATOR; + aborts_if quotient == 0 && scaled_numerator != 0 with ERATIO_OUT_OF_RANGE; + aborts_if quotient > MAX_U128 with ERATIO_OUT_OF_RANGE; + } + spec fun spec_create_from_rational(numerator: num, denominator: num): FixedPoint64 { + FixedPoint64{value: (numerator << 128) / (denominator << 64)} + } + + /// Create a fixedpoint value from a raw value. + public fun create_from_raw_value(value: u128): FixedPoint64 { + FixedPoint64 { value } + } + spec create_from_raw_value { + pragma opaque; + aborts_if false; + ensures result.value == value; + } + + /// Accessor for the raw u128 value. Other less common operations, such as + /// adding or subtracting FixedPoint64 values, can be done using the raw + /// values directly. + public fun get_raw_value(num: FixedPoint64): u128 { + num.value + } + + /// Returns true if the ratio is zero. + public fun is_zero(num: FixedPoint64): bool { + num.value == 0 + } + + /// Returns the smaller of the two FixedPoint64 numbers. + public fun min(num1: FixedPoint64, num2: FixedPoint64): FixedPoint64 { + if (num1.value < num2.value) { + num1 + } else { + num2 + } + } + spec min { + pragma opaque; + aborts_if false; + ensures result == spec_min(num1, num2); + } + spec fun spec_min(num1: FixedPoint64, num2: FixedPoint64): FixedPoint64 { + if (num1.value < num2.value) { + num1 + } else { + num2 + } + } + + /// Returns the larger of the two FixedPoint64 numbers. + public fun max(num1: FixedPoint64, num2: FixedPoint64): FixedPoint64 { + if (num1.value > num2.value) { + num1 + } else { + num2 + } + } + spec max { + pragma opaque; + aborts_if false; + ensures result == spec_max(num1, num2); + } + spec fun spec_max(num1: FixedPoint64, num2: FixedPoint64): FixedPoint64 { + if (num1.value > num2.value) { + num1 + } else { + num2 + } + } + + /// Returns true if num1 <= num2 + public fun less_or_equal(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value <= num2.value + } + spec less_or_equal { + pragma opaque; + aborts_if false; + ensures result == spec_less_or_equal(num1, num2); + } + spec fun spec_less_or_equal(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value <= num2.value + } + + /// Returns true if num1 < num2 + public fun less(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value < num2.value + } + spec less { + pragma opaque; + aborts_if false; + ensures result == spec_less(num1, num2); + } + spec fun spec_less(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value < num2.value + } + + /// Returns true if num1 >= num2 + public fun greater_or_equal(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value >= num2.value + } + spec greater_or_equal { + pragma opaque; + aborts_if false; + ensures result == spec_greater_or_equal(num1, num2); + } + spec fun spec_greater_or_equal(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value >= num2.value + } + + /// Returns true if num1 > num2 + public fun greater(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value > num2.value + } + spec greater { + pragma opaque; + aborts_if false; + ensures result == spec_greater(num1, num2); + } + spec fun spec_greater(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value > num2.value + } + + /// Returns true if num1 = num2 + public fun equal(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value == num2.value + } + spec equal { + pragma opaque; + aborts_if false; + ensures result == spec_equal(num1, num2); + } + spec fun spec_equal(num1: FixedPoint64, num2: FixedPoint64): bool { + num1.value == num2.value + } + + /// Returns true if num1 almost equals to num2, which means abs(num1-num2) <= precision + public fun almost_equal(num1: FixedPoint64, num2: FixedPoint64, precision: FixedPoint64): bool { + if (num1.value > num2.value) { + (num1.value - num2.value <= precision.value) + } else { + (num2.value - num1.value <= precision.value) + } + } + spec almost_equal { + pragma opaque; + aborts_if false; + ensures result == spec_almost_equal(num1, num2, precision); + } + spec fun spec_almost_equal(num1: FixedPoint64, num2: FixedPoint64, precision: FixedPoint64): bool { + if (num1.value > num2.value) { + (num1.value - num2.value <= precision.value) + } else { + (num2.value - num1.value <= precision.value) + } + } + /// Create a fixedpoint value from a u128 value. + public fun create_from_u128(val: u128): FixedPoint64 { + let value = (val as u256) << 64; + assert!(value <= MAX_U128, ERATIO_OUT_OF_RANGE); + FixedPoint64 {value: (value as u128)} + } + spec create_from_u128 { + pragma opaque; + include CreateFromU64AbortsIf; + ensures result == spec_create_from_u128(val); + } + spec schema CreateFromU64AbortsIf { + val: num; + let scaled_value = (val as u256) << 64; + aborts_if scaled_value > MAX_U128; + } + spec fun spec_create_from_u128(val: num): FixedPoint64 { + FixedPoint64 {value: val << 64} + } + + /// Returns the largest integer less than or equal to a given number. + public fun floor(num: FixedPoint64): u128 { + num.value >> 64 + } + spec floor { + pragma opaque; + aborts_if false; + ensures result == spec_floor(num); + } + spec fun spec_floor(val: FixedPoint64): u128 { + let fractional = val.value % (1 << 64); + if (fractional == 0) { + val.value >> 64 + } else { + (val.value - fractional) >> 64 + } + } + + /// Rounds up the given FixedPoint64 to the next largest integer. + public fun ceil(num: FixedPoint64): u128 { + let floored_num = floor(num) << 64; + if (num.value == floored_num) { + return floored_num >> 64 + }; + let val = ((floored_num as u256) + (1 << 64)); + (val >> 64 as u128) + } + spec ceil { + // TODO: set because of timeout (property proved). + pragma verify_duration_estimate = 1000; + pragma opaque; + aborts_if false; + ensures result == spec_ceil(num); + } + spec fun spec_ceil(val: FixedPoint64): u128 { + let fractional = val.value % (1 << 64); + let one = 1 << 64; + if (fractional == 0) { + val.value >> 64 + } else { + (val.value - fractional + one) >> 64 + } + } + + /// Returns the value of a FixedPoint64 to the nearest integer. + public fun round(num: FixedPoint64): u128 { + let floored_num = floor(num) << 64; + let boundary = floored_num + ((1 << 64) / 2); + if (num.value < boundary) { + floored_num >> 64 + } else { + ceil(num) + } + } + spec round { + pragma opaque; + aborts_if false; + ensures result == spec_round(num); + } + spec fun spec_round(val: FixedPoint64): u128 { + let fractional = val.value % (1 << 64); + let boundary = (1 << 64) / 2; + let one = 1 << 64; + if (fractional < boundary) { + (val.value - fractional) >> 64 + } else { + (val.value - fractional + one) >> 64 + } + } + + // **************** SPECIFICATIONS **************** + + spec module {} // switch documentation context to module level + + spec module { + pragma aborts_if_is_strict; + } + + #[test] + public entry fun test_sub() { + let x = create_from_rational(9, 7); + let y = create_from_rational(1, 3); + let result = sub(x, y); + // 9/7 - 1/3 = 20/21 + let expected_result = create_from_rational(20, 21); + assert_approx_the_same((get_raw_value(result) as u256), (get_raw_value(expected_result) as u256), 16); + } + + #[test] + #[expected_failure(abort_code = 0x10006, location = Self)] + public entry fun test_sub_should_abort() { + let x = create_from_rational(1, 3); + let y = create_from_rational(9, 7); + let _ = sub(x, y); + } + + #[test_only] + /// For functions that approximate a value it's useful to test a value is close + /// to the most correct value up to last digit + fun assert_approx_the_same(x: u256, y: u256, precission: u128) { + if (x < y) { + let tmp = x; + x = y; + y = tmp; + }; + let mult = 1u256; + let n = 10u256; + while (precission > 0) { + if (precission % 2 == 1) { + mult = mult * n; + }; + precission = precission / 2; + n = n * n; + }; + assert!((x - y) * mult < x, 0); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/from_bcs.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/from_bcs.move new file mode 100644 index 000000000..1d7c3c542 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/from_bcs.move @@ -0,0 +1,91 @@ +/// This module provides a number of functions to convert _primitive_ types from their representation in `std::bcs` +/// to values. This is the opposite of `bcs::to_bytes`. Note that it is not safe to define a generic public `from_bytes` +/// function because this can violate implicit struct invariants, therefore only primitive types are offerred. If +/// a general conversion back-and-force is needed, consider the `aptos_std::Any` type which preserves invariants. +/// +/// Example: +/// ``` +/// use std::bcs; +/// use aptos_std::from_bcs; +/// +/// assert!(from_bcs::to_address(bcs::to_bytes(&@0xabcdef)) == @0xabcdef, 0); +/// ``` +module aptos_std::from_bcs { + use std::string::{Self, String}; + + /// UTF8 check failed in conversion from bytes to string + const EINVALID_UTF8: u64 = 0x1; + + public fun to_bool(v: vector): bool { + from_bytes(v) + } + + public fun to_u8(v: vector): u8 { + from_bytes(v) + } + + public fun to_u16(v: vector): u16 { + from_bytes(v) + } + + public fun to_u32(v: vector): u32 { + from_bytes(v) + } + + public fun to_u64(v: vector): u64 { + from_bytes(v) + } + + public fun to_u128(v: vector): u128 { + from_bytes(v) + } + + public fun to_u256(v: vector): u256 { + from_bytes(v) + } + + public fun to_address(v: vector): address { + from_bytes
(v) + } + + public fun to_bytes(v: vector): vector { + from_bytes>(v) + } + + public fun to_string(v: vector): String { + // To make this safe, we need to evaluate the utf8 invariant. + let s = from_bytes(v); + assert!(string::internal_check_utf8(string::bytes(&s)), EINVALID_UTF8); + s + } + + /// Package private native function to deserialize a type T. + /// + /// Note that this function does not put any constraint on `T`. If code uses this function to + /// deserialize a linear value, its their responsibility that the data they deserialize is + /// owned. + public(friend) native fun from_bytes(bytes: vector): T; + friend aptos_std::any; + friend aptos_std::copyable_any; + + + #[test_only] + use std::bcs; + + #[test] + fun test_address() { + let addr = @0x01; + let addr_vec = x"0000000000000000000000000000000000000000000000000000000000000001"; + let addr_out = to_address(addr_vec); + let addr_vec_out = bcs::to_bytes(&addr_out); + assert!(addr == addr_out, 0); + assert!(addr_vec == addr_vec_out, 1); + } + + #[test] + #[expected_failure(abort_code = 0x10001, location = Self)] + fun test_address_fail() { + let bad_vec = b"01"; + to_address(bad_vec); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/math128.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/math128.move new file mode 100644 index 000000000..652815369 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/math128.move @@ -0,0 +1,350 @@ +/// Standard math utilities missing in the Move Language. +module aptos_std::math128 { + + use std::fixed_point32::FixedPoint32; + use std::fixed_point32; + use aptos_std::fixed_point64::FixedPoint64; + use aptos_std::fixed_point64; + + /// Cannot log2 the value 0 + const EINVALID_ARG_FLOOR_LOG2: u64 = 1; + + /// Return the largest of two numbers. + public fun max(a: u128, b: u128): u128 { + if (a >= b) a else b + } + + /// Return the smallest of two numbers. + public fun min(a: u128, b: u128): u128 { + if (a < b) a else b + } + + /// Return the average of two. + public fun average(a: u128, b: u128): u128 { + if (a < b) { + a + (b - a) / 2 + } else { + b + (a - b) / 2 + } + } + + /// Return greatest common divisor of `a` & `b`, via the Euclidean algorithm. + public inline fun gcd(a: u128, b: u128): u128 { + let (large, small) = if (a > b) (a, b) else (b, a); + while (small != 0) { + let tmp = small; + small = large % small; + large = tmp; + }; + large + } + + /// Returns a * b / c going through u256 to prevent intermediate overflow + public inline fun mul_div(a: u128, b: u128, c: u128): u128 { + // Inline functions cannot take constants, as then every module using it needs the constant + assert!(c != 0, std::error::invalid_argument(4)); + (((a as u256) * (b as u256) / (c as u256)) as u128) + } + + /// Return x clamped to the interval [lower, upper]. + public fun clamp(x: u128, lower: u128, upper: u128): u128 { + min(upper, max(lower, x)) + } + + /// Return the value of n raised to power e + public fun pow(n: u128, e: u128): u128 { + if (e == 0) { + 1 + } else { + let p = 1; + while (e > 1) { + if (e % 2 == 1) { + p = p * n; + }; + e = e / 2; + n = n * n; + }; + p * n + } + } + + /// Returns floor(log2(x)) + public fun floor_log2(x: u128): u8 { + let res = 0; + assert!(x != 0, std::error::invalid_argument(EINVALID_ARG_FLOOR_LOG2)); + // Effectively the position of the most significant set bit + let n = 64; + while (n > 0) { + if (x >= (1 << n)) { + x = x >> n; + res = res + n; + }; + n = n >> 1; + }; + res + } + + // Returns log2(x) + public fun log2(x: u128): FixedPoint32 { + let integer_part = floor_log2(x); + // Normalize x to [1, 2) in fixed point 32. + if (x >= 1 << 32) { + x = x >> (integer_part - 32); + } else { + x = x << (32 - integer_part); + }; + let frac = 0; + let delta = 1 << 31; + while (delta != 0) { + // log x = 1/2 log x^2 + // x in [1, 2) + x = (x * x) >> 32; + // x is now in [1, 4) + // if x in [2, 4) then log x = 1 + log (x / 2) + if (x >= (2 << 32)) { frac = frac + delta; x = x >> 1; }; + delta = delta >> 1; + }; + fixed_point32::create_from_raw_value (((integer_part as u64) << 32) + frac) + } + + // Return log2(x) as FixedPoint64 + public fun log2_64(x: u128): FixedPoint64 { + let integer_part = floor_log2(x); + // Normalize x to [1, 2) in fixed point 63. To ensure x is smaller then 1<<64 + if (x >= 1 << 63) { + x = x >> (integer_part - 63); + } else { + x = x << (63 - integer_part); + }; + let frac = 0; + let delta = 1 << 63; + while (delta != 0) { + // log x = 1/2 log x^2 + // x in [1, 2) + x = (x * x) >> 63; + // x is now in [1, 4) + // if x in [2, 4) then log x = 1 + log (x / 2) + if (x >= (2 << 63)) { frac = frac + delta; x = x >> 1; }; + delta = delta >> 1; + }; + fixed_point64::create_from_raw_value (((integer_part as u128) << 64) + frac) + } + + /// Returns square root of x, precisely floor(sqrt(x)) + public fun sqrt(x: u128): u128 { + if (x == 0) return 0; + // Note the plus 1 in the expression. Let n = floor_lg2(x) we have x in [2^n, 2^{n+1}) and thus the answer in + // the half-open interval [2^(n/2), 2^{(n+1)/2}). For even n we can write this as [2^(n/2), sqrt(2) 2^{n/2}) + // for odd n [2^((n+1)/2)/sqrt(2), 2^((n+1)/2). For even n the left end point is integer for odd the right + // end point is integer. If we choose as our first approximation the integer end point we have as maximum + // relative error either (sqrt(2) - 1) or (1 - 1/sqrt(2)) both are smaller then 1/2. + let res = 1 << ((floor_log2(x) + 1) >> 1); + // We use standard newton-rhapson iteration to improve the initial approximation. + // The error term evolves as delta_i+1 = delta_i^2 / 2 (quadratic convergence). + // It turns out that after 5 iterations the delta is smaller than 2^-64 and thus below the treshold. + res = (res + x / res) >> 1; + res = (res + x / res) >> 1; + res = (res + x / res) >> 1; + res = (res + x / res) >> 1; + res = (res + x / res) >> 1; + min(res, x / res) + } + + public inline fun ceil_div(x: u128, y: u128): u128 { + // ceil_div(x, y) = floor((x + y - 1) / y) = floor((x - 1) / y) + 1 + // (x + y - 1) could spuriously overflow. so we use the later version + if (x == 0) { + // Inline functions cannot take constants, as then every module using it needs the constant + assert!(y != 0, std::error::invalid_argument(4)); + 0 + } + else (x - 1) / y + 1 + } + + #[test] + public entry fun test_ceil_div() { + assert!(ceil_div(9, 3) == 3, 0); + assert!(ceil_div(10, 3) == 4, 0); + assert!(ceil_div(11, 3) == 4, 0); + assert!(ceil_div(12, 3) == 4, 0); + assert!(ceil_div(13, 3) == 5, 0); + + // No overflow + assert!(ceil_div((((1u256<<128) - 9) as u128), 11) == 30934760629176223951215873402888019223, 0); + } + + #[test] + fun test_gcd() { + assert!(gcd(20, 8) == 4, 0); + assert!(gcd(8, 20) == 4, 0); + assert!(gcd(1, 100) == 1, 0); + assert!(gcd(100, 1) == 1, 0); + assert!(gcd(210, 45) == 15, 0); + assert!(gcd(45, 210) == 15, 0); + assert!(gcd(0, 0) == 0, 0); + assert!(gcd(1, 0) == 1, 0); + assert!(gcd(50, 0) == 50, 0); + assert!(gcd(0, 1) == 1, 0); + assert!(gcd(0, 50) == 50, 0); + assert!(gcd(54, 24) == 6, 0); + assert!(gcd(24, 54) == 6, 0); + assert!(gcd(10, 10) == 10, 0); + assert!(gcd(1071, 462) == 21, 0); + assert!(gcd(462, 1071) == 21, 0); + } + + #[test] + public entry fun test_max() { + let result = max(3u128, 6u128); + assert!(result == 6, 0); + + let result = max(15u128, 12u128); + assert!(result == 15, 1); + } + + #[test] + public entry fun test_min() { + let result = min(3u128, 6u128); + assert!(result == 3, 0); + + let result = min(15u128, 12u128); + assert!(result == 12, 1); + } + + #[test] + public entry fun test_average() { + let result = average(3u128, 6u128); + assert!(result == 4, 0); + + let result = average(15u128, 12u128); + assert!(result == 13, 0); + } + + #[test] + public entry fun test_pow() { + let result = pow(10u128, 18u128); + assert!(result == 1000000000000000000, 0); + + let result = pow(10u128, 1u128); + assert!(result == 10, 0); + + let result = pow(10u128, 0u128); + assert!(result == 1, 0); + } + + #[test] + public entry fun test_mul_div() { + let tmp: u128 = 1<<127; + assert!(mul_div(tmp,tmp,tmp) == tmp, 0); + + assert!(mul_div(tmp,5,5) == tmp, 0); + // Note that ordering other way is imprecise. + assert!((tmp / 5) * 5 != tmp, 0); + } + + #[test] + #[expected_failure(abort_code = 0x10004, location = aptos_std::math128)] + public entry fun test_mul_div_by_zero() { + mul_div(1, 1, 0); + } + + #[test] + public entry fun test_floor_log2() { + let idx: u8 = 0; + while (idx < 128) { + assert!(floor_log2(1<> 32; + let taylor3 = (taylor2 * taylor1) >> 32; + let expected = expected - ((taylor1 + taylor2 / 2 + taylor3 / 3) << 32) / 2977044472; + // verify it matches to 8 significant digits + assert_approx_the_same((fixed_point32::get_raw_value(res) as u128), expected, 8); + idx = idx + 1; + }; + } + + #[test] + public entry fun test_log2_64() { + let idx: u8 = 0; + while (idx < 128) { + let res = log2_64(1<> 64; + let taylor3 = (taylor2 * taylor1) >> 64; + let taylor4 = (taylor3 * taylor1) >> 64; + let expected = expected - ((taylor1 + taylor2 / 2 + taylor3 / 3 + taylor4 / 4) << 64) / 12786308645202655660; + // verify it matches to 8 significant digits + assert_approx_the_same(fixed_point64::get_raw_value(res), (expected as u128), 14); + idx = idx + 1; + }; + } + + #[test] + public entry fun test_sqrt() { + let result = sqrt(0); + assert!(result == 0, 0); + + let result = sqrt(1); + assert!(result == 1, 0); + + let result = sqrt(256); + assert!(result == 16, 0); + + let result = sqrt(1<<126); + assert!(result == 1<<63, 0); + + let result = sqrt((((1u256 << 128) - 1) as u128)); + assert!(result == (1u128 << 64) - 1, 0); + + let result = sqrt((1u128 << 127)); + assert!(result == 13043817825332782212, 0); + + let result = sqrt((1u128 << 127) - 1); + assert!(result == 13043817825332782212, 0); + } + + #[test_only] + /// For functions that approximate a value it's useful to test a value is close + /// to the most correct value up to last digit + fun assert_approx_the_same(x: u128, y: u128, precission: u128) { + if (x < y) { + let tmp = x; + x = y; + y = tmp; + }; + let mult = pow(10, precission); + assert!((x - y) * mult < x, 0); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/math64.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/math64.move new file mode 100644 index 000000000..50fd38ed3 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/math64.move @@ -0,0 +1,305 @@ +/// Standard math utilities missing in the Move Language. +module aptos_std::math64 { + + use std::fixed_point32::FixedPoint32; + use std::fixed_point32; + + /// Cannot log2 the value 0 + const EINVALID_ARG_FLOOR_LOG2: u64 = 1; + + /// Return the largest of two numbers. + public fun max(a: u64, b: u64): u64 { + if (a >= b) a else b + } + + /// Return the smallest of two numbers. + public fun min(a: u64, b: u64): u64 { + if (a < b) a else b + } + + /// Return the average of two. + public fun average(a: u64, b: u64): u64 { + if (a < b) { + a + (b - a) / 2 + } else { + b + (a - b) / 2 + } + } + + /// Return greatest common divisor of `a` & `b`, via the Euclidean algorithm. + public inline fun gcd(a: u64, b: u64): u64 { + let (large, small) = if (a > b) (a, b) else (b, a); + while (small != 0) { + let tmp = small; + small = large % small; + large = tmp; + }; + large + } + + /// Returns a * b / c going through u128 to prevent intermediate overflow + public inline fun mul_div(a: u64, b: u64, c: u64): u64 { + // Inline functions cannot take constants, as then every module using it needs the constant + assert!(c != 0, std::error::invalid_argument(4)); + (((a as u128) * (b as u128) / (c as u128)) as u64) + } + + /// Return x clamped to the interval [lower, upper]. + public fun clamp(x: u64, lower: u64, upper: u64): u64 { + min(upper, max(lower, x)) + } + + /// Return the value of n raised to power e + public fun pow(n: u64, e: u64): u64 { + if (e == 0) { + 1 + } else { + let p = 1; + while (e > 1) { + if (e % 2 == 1) { + p = p * n; + }; + e = e / 2; + n = n * n; + }; + p * n + } + } + + /// Returns floor(lg2(x)) + public fun floor_log2(x: u64): u8 { + let res = 0; + assert!(x != 0, std::error::invalid_argument(EINVALID_ARG_FLOOR_LOG2)); + // Effectively the position of the most significant set bit + let n = 32; + while (n > 0) { + if (x >= (1 << n)) { + x = x >> n; + res = res + n; + }; + n = n >> 1; + }; + res + } + + // Returns log2(x) + public fun log2(x: u64): FixedPoint32 { + let integer_part = floor_log2(x); + // Normalize x to [1, 2) in fixed point 32. + let y = (if (x >= 1 << 32) { + x >> (integer_part - 32) + } else { + x << (32 - integer_part) + } as u128); + let frac = 0; + let delta = 1 << 31; + while (delta != 0) { + // log x = 1/2 log x^2 + // x in [1, 2) + y = (y * y) >> 32; + // x is now in [1, 4) + // if x in [2, 4) then log x = 1 + log (x / 2) + if (y >= (2 << 32)) { frac = frac + delta; y = y >> 1; }; + delta = delta >> 1; + }; + fixed_point32::create_from_raw_value (((integer_part as u64) << 32) + frac) + } + + /// Returns square root of x, precisely floor(sqrt(x)) + public fun sqrt(x: u64): u64 { + if (x == 0) return 0; + // Note the plus 1 in the expression. Let n = floor_lg2(x) we have x in [2^n, 2^(n+1)> and thus the answer in + // the half-open interval [2^(n/2), 2^((n+1)/2)>. For even n we can write this as [2^(n/2), sqrt(2) 2^(n/2)> + // for odd n [2^((n+1)/2)/sqrt(2), 2^((n+1)/2>. For even n the left end point is integer for odd the right + // end point is integer. If we choose as our first approximation the integer end point we have as maximum + // relative error either (sqrt(2) - 1) or (1 - 1/sqrt(2)) both are smaller then 1/2. + let res = 1 << ((floor_log2(x) + 1) >> 1); + // We use standard newton-rhapson iteration to improve the initial approximation. + // The error term evolves as delta_i+1 = delta_i^2 / 2 (quadratic convergence). + // It turns out that after 4 iterations the delta is smaller than 2^-32 and thus below the treshold. + res = (res + x / res) >> 1; + res = (res + x / res) >> 1; + res = (res + x / res) >> 1; + res = (res + x / res) >> 1; + min(res, x / res) + } + + public inline fun ceil_div(x: u64, y: u64): u64 { + // ceil_div(x, y) = floor((x + y - 1) / y) = floor((x - 1) / y) + 1 + // (x + y - 1) could spuriously overflow. so we use the later version + if (x == 0) { + // Inline functions cannot take constants, as then every module using it needs the constant + assert!(y != 0, std::error::invalid_argument(4)); + 0 + } + else (x - 1) / y + 1 + } + + #[test] + public entry fun test_ceil_div() { + assert!(ceil_div(9, 3) == 3, 0); + assert!(ceil_div(10, 3) == 4, 0); + assert!(ceil_div(11, 3) == 4, 0); + assert!(ceil_div(12, 3) == 4, 0); + assert!(ceil_div(13, 3) == 5, 0); + + // No overflow + assert!(ceil_div((((1u128<<64) - 9) as u64), 11) == 1676976733973595601, 0); + } + + #[test] + fun test_gcd() { + assert!(gcd(20, 8) == 4, 0); + assert!(gcd(8, 20) == 4, 0); + assert!(gcd(1, 100) == 1, 0); + assert!(gcd(100, 1) == 1, 0); + assert!(gcd(210, 45) == 15, 0); + assert!(gcd(45, 210) == 15, 0); + assert!(gcd(0, 0) == 0, 0); + assert!(gcd(1, 0) == 1, 0); + assert!(gcd(50, 0) == 50, 0); + assert!(gcd(0, 1) == 1, 0); + assert!(gcd(0, 50) == 50, 0); + assert!(gcd(54, 24) == 6, 0); + assert!(gcd(24, 54) == 6, 0); + assert!(gcd(10, 10) == 10, 0); + assert!(gcd(1071, 462) == 21, 0); + assert!(gcd(462, 1071) == 21, 0); + } + + #[test] + public entry fun test_max_64() { + let result = max(3u64, 6u64); + assert!(result == 6, 0); + + let result = max(15u64, 12u64); + assert!(result == 15, 1); + } + + #[test] + public entry fun test_min() { + let result = min(3u64, 6u64); + assert!(result == 3, 0); + + let result = min(15u64, 12u64); + assert!(result == 12, 1); + } + + #[test] + public entry fun test_average() { + let result = average(3u64, 6u64); + assert!(result == 4, 0); + + let result = average(15u64, 12u64); + assert!(result == 13, 0); + } + + #[test] + public entry fun test_average_does_not_overflow() { + let result = average(18446744073709551615, 18446744073709551615); + assert!(result == 18446744073709551615, 0); + } + + #[test] + public entry fun test_pow() { + let result = pow(10u64, 18u64); + assert!(result == 1000000000000000000, 0); + + let result = pow(10u64, 1u64); + assert!(result == 10, 0); + + let result = pow(10u64, 0u64); + assert!(result == 1, 0); + } + + #[test] + public entry fun test_mul_div() { + let tmp: u64 = 1<<63; + assert!(mul_div(tmp,tmp,tmp) == tmp, 0); + + assert!(mul_div(tmp,5,5) == tmp, 0); + // Note that ordering other way is imprecise. + assert!((tmp / 5) * 5 != tmp, 0); + } + + #[test] + #[expected_failure(abort_code = 0x10004, location = aptos_std::math64)] + public entry fun test_mul_div_by_zero() { + mul_div(1, 1, 0); + } + + #[test] + public entry fun test_floor_lg2() { + let idx: u8 = 0; + while (idx < 64) { + assert!(floor_log2(1<> 32; + let taylor3 = (taylor2 * taylor1) >> 32; + let expected = expected - ((taylor1 + taylor2 / 2 + taylor3 / 3) << 32) / 2977044472; + // verify it matches to 8 significant digits + assert_approx_the_same((fixed_point32::get_raw_value(res) as u128), expected, 8); + idx = idx + 1; + }; + } + + #[test] + public entry fun test_sqrt() { + let result = sqrt(0); + assert!(result == 0, 0); + + let result = sqrt(1); + assert!(result == 1, 0); + + let result = sqrt(256); + assert!(result == 16, 0); + + let result = sqrt(1<<62); + assert!(result == 1<<31, 0); + + let result = sqrt((((1u128 << 64) - 1) as u64)); + assert!(result == (1u64 << 32) - 1, 0); + + let result = sqrt((1u64 << 63)); + assert!(result == 3037000499, 0); + + let result = sqrt((1u64 << 63) - 1); + assert!(result == 3037000499, 0); + } + + #[test_only] + /// For functions that approximate a value it's useful to test a value is close + /// to the most correct value up to last digit + fun assert_approx_the_same(x: u128, y: u128, precission: u64) { + if (x < y) { + let tmp = x; + x = y; + y = tmp; + }; + let mult = (pow(10, precission) as u128); + assert!((x - y) * mult < x, 0); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/math_fixed.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/math_fixed.move new file mode 100644 index 000000000..a2a854d0c --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/math_fixed.move @@ -0,0 +1,139 @@ +/// Standard math utilities missing in the Move Language. +module aptos_std::math_fixed { + use std::fixed_point32; + use std::fixed_point32::FixedPoint32; + use aptos_std::math128; + use aptos_std::math64; + + /// Abort code on overflow + const EOVERFLOW_EXP: u64 = 1; + + /// Natural log 2 in 32 bit fixed point + const LN2: u128 = 2977044472; // ln(2) in fixed 32 representation + const LN2_X_32: u64 = 32 * 2977044472; // 32 * ln(2) in fixed 32 representation + + /// Square root of fixed point number + public fun sqrt(x: FixedPoint32): FixedPoint32 { + let y = (fixed_point32::get_raw_value(x) as u128); + fixed_point32::create_from_raw_value((math128::sqrt(y << 32) as u64)) + } + + /// Exponent function with a precission of 9 digits. + public fun exp(x: FixedPoint32): FixedPoint32 { + let raw_value = (fixed_point32::get_raw_value(x) as u128); + fixed_point32::create_from_raw_value((exp_raw(raw_value) as u64)) + } + + /// Because log2 is negative for values < 1 we instead return log2(x) + 32 which + /// is positive for all values of x. + public fun log2_plus_32(x: FixedPoint32): FixedPoint32 { + let raw_value = (fixed_point32::get_raw_value(x) as u128); + math128::log2(raw_value) + } + + public fun ln_plus_32ln2(x: FixedPoint32): FixedPoint32 { + let raw_value = (fixed_point32::get_raw_value(x) as u128); + let x = (fixed_point32::get_raw_value(math128::log2(raw_value)) as u128); + fixed_point32::create_from_raw_value((x * LN2 >> 32 as u64)) + } + + /// Integer power of a fixed point number + public fun pow(x: FixedPoint32, n: u64): FixedPoint32 { + let raw_value = (fixed_point32::get_raw_value(x) as u128); + fixed_point32::create_from_raw_value((pow_raw(raw_value, (n as u128)) as u64)) + } + + /// Specialized function for x * y / z that omits intermediate shifting + public fun mul_div(x: FixedPoint32, y: FixedPoint32, z: FixedPoint32): FixedPoint32 { + let a = fixed_point32::get_raw_value(x); + let b = fixed_point32::get_raw_value(y); + let c = fixed_point32::get_raw_value(z); + fixed_point32::create_from_raw_value (math64::mul_div(a, b, c)) + } + + // Calculate e^x where x and the result are fixed point numbers + fun exp_raw(x: u128): u128 { + // exp(x / 2^32) = 2^(x / (2^32 * ln(2))) = 2^(floor(x / (2^32 * ln(2))) + frac(x / (2^32 * ln(2)))) + let shift_long = x / LN2; + assert!(shift_long <= 31, std::error::invalid_state(EOVERFLOW_EXP)); + let shift = (shift_long as u8); + let remainder = x % LN2; + // At this point we want to calculate 2^(remainder / ln2) << shift + // ln2 = 595528 * 4999 which means + let bigfactor = 595528; + let exponent = remainder / bigfactor; + let x = remainder % bigfactor; + // 2^(remainder / ln2) = (2^(1/4999))^exponent * exp(x / 2^32) + let roottwo = 4295562865; // fixed point representation of 2^(1/4999) + // This has an error of 5000 / 4 10^9 roughly 6 digits of precission + let power = pow_raw(roottwo, exponent); + let eps_correction = 1241009291; + power = power + ((power * eps_correction * exponent) >> 64); + // x is fixed point number smaller than 595528/2^32 < 0.00014 so we need only 2 tayler steps + // to get the 6 digits of precission + let taylor1 = (power * x) >> (32 - shift); + let taylor2 = (taylor1 * x) >> 32; + let taylor3 = (taylor2 * x) >> 32; + (power << shift) + taylor1 + taylor2 / 2 + taylor3 / 6 + } + + // Calculate x to the power of n, where x and the result are fixed point numbers. + fun pow_raw(x: u128, n: u128): u128 { + let res: u256 = 1 << 64; + x = x << 32; + while (n != 0) { + if (n & 1 != 0) { + res = (res * (x as u256)) >> 64; + }; + n = n >> 1; + x = ((((x as u256) * (x as u256)) >> 64) as u128); + }; + ((res >> 32) as u128) + } + + #[test] + public entry fun test_sqrt() { + // Sqrt is based on math128::sqrt and thus most of the testing is done there. + let fixed_base = 1 << 32; + let result = sqrt(fixed_point32::create_from_u64(1)); + assert!(fixed_point32::get_raw_value(result) == fixed_base, 0); + + let result = sqrt(fixed_point32::create_from_u64(2)); + assert_approx_the_same((fixed_point32::get_raw_value(result) as u128), 6074001000, 9); + } + + #[test] + public entry fun test_exp() { + let fixed_base = 1 << 32; + let result = exp_raw(0); + assert!(result == fixed_base, 0); + + let result = exp_raw(fixed_base); + let e = 11674931554; // e in 32 bit fixed point + assert_approx_the_same(result, e, 9); + + let result = exp_raw(10 * fixed_base); + let exp10 = 94602950235157; // e^10 in 32 bit fixed point + assert_approx_the_same(result, exp10, 9); + } + + #[test] + public entry fun test_pow() { + // We use the case of exp + let result = pow_raw(4295562865, 4999); + assert_approx_the_same(result, 1 << 33, 6); + } + + #[test_only] + /// For functions that approximate a value it's useful to test a value is close + /// to the most correct value up to last digit + fun assert_approx_the_same(x: u128, y: u128, precission: u128) { + if (x < y) { + let tmp = x; + x = y; + y = tmp; + }; + let mult = math128::pow(10, precission); + assert!((x - y) * mult < x, 0); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/math_fixed64.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/math_fixed64.move new file mode 100644 index 000000000..2369b6afe --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/math_fixed64.move @@ -0,0 +1,142 @@ +/// Standard math utilities missing in the Move Language. + +module aptos_std::math_fixed64 { + use aptos_std::fixed_point64; + use aptos_std::fixed_point64::FixedPoint64; + use aptos_std::math128; + + /// Abort code on overflow + const EOVERFLOW_EXP: u64 = 1; + + /// Natural log 2 in 32 bit fixed point + const LN2: u256 = 12786308645202655660; // ln(2) in fixed 64 representation + + /// Square root of fixed point number + public fun sqrt(x: FixedPoint64): FixedPoint64 { + let y = fixed_point64::get_raw_value(x); + let z = (math128::sqrt(y) << 32 as u256); + z = (z + ((y as u256) << 64) / z) >> 1; + fixed_point64::create_from_raw_value((z as u128)) + } + + /// Exponent function with a precission of 9 digits. + public fun exp(x: FixedPoint64): FixedPoint64 { + let raw_value = (fixed_point64::get_raw_value(x) as u256); + fixed_point64::create_from_raw_value((exp_raw(raw_value) as u128)) + } + + /// Because log2 is negative for values < 1 we instead return log2(x) + 64 which + /// is positive for all values of x. + public fun log2_plus_64(x: FixedPoint64): FixedPoint64 { + let raw_value = (fixed_point64::get_raw_value(x) as u128); + math128::log2_64(raw_value) + } + + public fun ln_plus_32ln2(x: FixedPoint64): FixedPoint64 { + let raw_value = fixed_point64::get_raw_value(x); + let x = (fixed_point64::get_raw_value(math128::log2_64(raw_value)) as u256); + fixed_point64::create_from_raw_value(((x * LN2) >> 64 as u128)) + } + + /// Integer power of a fixed point number + public fun pow(x: FixedPoint64, n: u64): FixedPoint64 { + let raw_value = (fixed_point64::get_raw_value(x) as u256); + fixed_point64::create_from_raw_value((pow_raw(raw_value, (n as u128)) as u128)) + } + + /// Specialized function for x * y / z that omits intermediate shifting + public fun mul_div(x: FixedPoint64, y: FixedPoint64, z: FixedPoint64): FixedPoint64 { + let a = fixed_point64::get_raw_value(x); + let b = fixed_point64::get_raw_value(y); + let c = fixed_point64::get_raw_value(z); + fixed_point64::create_from_raw_value (math128::mul_div(a, b, c)) + } + + // Calculate e^x where x and the result are fixed point numbers + fun exp_raw(x: u256): u256 { + // exp(x / 2^64) = 2^(x / (2^64 * ln(2))) = 2^(floor(x / (2^64 * ln(2))) + frac(x / (2^64 * ln(2)))) + let shift_long = x / LN2; + assert!(shift_long <= 63, std::error::invalid_state(EOVERFLOW_EXP)); + let shift = (shift_long as u8); + let remainder = x % LN2; + // At this point we want to calculate 2^(remainder / ln2) << shift + // ln2 = 580 * 22045359733108027 + let bigfactor = 22045359733108027; + let exponent = remainder / bigfactor; + let x = remainder % bigfactor; + // 2^(remainder / ln2) = (2^(1/580))^exponent * exp(x / 2^64) + let roottwo = 18468802611690918839; // fixed point representation of 2^(1/580) + // 2^(1/580) = roottwo(1 - eps), so the number we seek is roottwo^exponent (1 - eps * exponent) + let power = pow_raw(roottwo, (exponent as u128)); + let eps_correction = 219071715585908898; + power = power - ((power * eps_correction * exponent) >> 128); + // x is fixed point number smaller than bigfactor/2^64 < 0.0011 so we need only 5 tayler steps + // to get the 15 digits of precission + let taylor1 = (power * x) >> (64 - shift); + let taylor2 = (taylor1 * x) >> 64; + let taylor3 = (taylor2 * x) >> 64; + let taylor4 = (taylor3 * x) >> 64; + let taylor5 = (taylor4 * x) >> 64; + let taylor6 = (taylor5 * x) >> 64; + (power << shift) + taylor1 + taylor2 / 2 + taylor3 / 6 + taylor4 / 24 + taylor5 / 120 + taylor6 / 720 + } + + // Calculate x to the power of n, where x and the result are fixed point numbers. + fun pow_raw(x: u256, n: u128): u256 { + let res: u256 = 1 << 64; + while (n != 0) { + if (n & 1 != 0) { + res = (res * x) >> 64; + }; + n = n >> 1; + x = (x * x) >> 64; + }; + res + } + + #[test] + public entry fun test_sqrt() { + // Sqrt is based on math128::sqrt and thus most of the testing is done there. + let fixed_base = 1 << 64; + let result = sqrt(fixed_point64::create_from_u128(1)); + assert!(fixed_point64::get_raw_value(result) == fixed_base, 0); + + let result = sqrt(fixed_point64::create_from_u128(2)); + assert_approx_the_same((fixed_point64::get_raw_value(result) as u256), 26087635650665564424, 16); + } + + #[test] + public entry fun test_exp() { + let fixed_base = 1 << 64; + let result = exp_raw(0); + assert!(result == fixed_base, 0); + + let result = exp_raw(fixed_base); + let e = 50143449209799256682; // e in 32 bit fixed point + assert_approx_the_same(result, e, 16); + + let result = exp_raw(10 * fixed_base); + let exp10 = 406316577365116946489258; // e^10 in 32 bit fixed point + assert_approx_the_same(result, exp10, 16); + } + + #[test] + public entry fun test_pow() { + // We use the case of exp + let result = pow_raw(18468802611690918839, 580); + assert_approx_the_same(result, 1 << 65, 16); + } + + #[test_only] + /// For functions that approximate a value it's useful to test a value is close + /// to the most correct value up to last digit + fun assert_approx_the_same(x: u256, y: u256, precission: u128) { + if (x < y) { + let tmp = x; + x = y; + y = tmp; + }; + let mult = (math128::pow(10, precission) as u256); + assert!((x - y) * mult < x, 0); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/multi_ed25519.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/multi_ed25519.move new file mode 100644 index 000000000..f1f97bc63 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/multi_ed25519.move @@ -0,0 +1,482 @@ +/// Exports MultiEd25519 multi-signatures in Move. +/// This module has the exact same interface as the Ed25519 module. + +module aptos_std::multi_ed25519 { + use std::bcs; + use std::error; + use std::features; + use std::option::{Self, Option}; + use std::vector; + use aptos_std::ed25519; + + // + // Error codes + // + + /// Wrong number of bytes were given as input when deserializing an Ed25519 public key. + const E_WRONG_PUBKEY_SIZE: u64 = 1; + + /// Wrong number of bytes were given as input when deserializing an Ed25519 signature. + const E_WRONG_SIGNATURE_SIZE: u64 = 2; + + /// The threshold must be in the range `[1, n]`, where n is the total number of signers. + const E_INVALID_THRESHOLD_OR_NUMBER_OF_SIGNERS: u64 = 3; + + /// The native functions have not been rolled out yet. + const E_NATIVE_FUN_NOT_AVAILABLE: u64 = 4; + + // + // Constants + // + + /// The identifier of the MultiEd25519 signature scheme, which is used when deriving Aptos authentication keys by hashing + /// it together with an MultiEd25519 public key. + const SIGNATURE_SCHEME_ID: u8 = 1; + + /// The size of an individual Ed25519 public key, in bytes. + /// (A MultiEd25519 public key consists of several of these, plus the threshold.) + const INDIVIDUAL_PUBLIC_KEY_NUM_BYTES: u64 = 32; + + /// The size of an individual Ed25519 signature, in bytes. + /// (A MultiEd25519 signature consists of several of these, plus the signer bitmap.) + const INDIVIDUAL_SIGNATURE_NUM_BYTES: u64 = 64; + + /// When serializing a MultiEd25519 public key, the threshold k will be encoded using this many bytes. + const THRESHOLD_SIZE_BYTES: u64 = 1; + + /// When serializing a MultiEd25519 signature, the bitmap that indicates the signers will be encoded using this many + /// bytes. + const BITMAP_NUM_OF_BYTES: u64 = 4; + + /// Max number of ed25519 public keys allowed in multi-ed25519 keys + const MAX_NUMBER_OF_PUBLIC_KEYS: u64 = 32; + + // + // Structs + // + #[test_only] + struct SecretKey has drop { + bytes: vector, + } + + /// An *unvalidated*, k out of n MultiEd25519 public key. The `bytes` field contains (1) several chunks of + /// `ed25519::PUBLIC_KEY_NUM_BYTES` bytes, each encoding a Ed25519 PK, and (2) a single byte encoding the threshold k. + /// *Unvalidated* means there is no guarantee that the underlying PKs are valid elliptic curve points of non-small + /// order. + struct UnvalidatedPublicKey has copy, drop, store { + bytes: vector + } + + /// A *validated* k out of n MultiEd25519 public key. *Validated* means that all the underlying PKs will be + /// elliptic curve points that are NOT of small-order. It does not necessarily mean they will be prime-order points. + /// This struct encodes the public key exactly as `UnvalidatedPublicKey`. + /// + /// For now, this struct is not used in any verification functions, but it might be in the future. + struct ValidatedPublicKey has copy, drop, store { + bytes: vector + } + + /// A purported MultiEd25519 multi-signature that can be verified via `signature_verify_strict` or + /// `signature_verify_strict_t`. The `bytes` field contains (1) several chunks of `ed25519::SIGNATURE_NUM_BYTES` + /// bytes, each encoding a Ed25519 signature, and (2) a `BITMAP_NUM_OF_BYTES`-byte bitmap encoding the signer + /// identities. + struct Signature has copy, drop, store { + bytes: vector + } + + // + // Functions + // + + #[test_only] + public fun generate_keys(threshold: u8, n: u8): (SecretKey, ValidatedPublicKey) { + assert!(1 <= threshold && threshold <= n, error::invalid_argument(E_INVALID_THRESHOLD_OR_NUMBER_OF_SIGNERS)); + let (sk_bytes, pk_bytes) = generate_keys_internal(threshold, n); + let sk = SecretKey { + bytes: sk_bytes + }; + let pk = ValidatedPublicKey { + bytes: pk_bytes + }; + (sk, pk) + } + + #[test_only] + public fun sign_arbitrary_bytes(sk: &SecretKey, msg: vector) : Signature { + Signature { + bytes: sign_internal(sk.bytes, msg) + } + } + + #[test_only] + public fun sign_struct(sk: &SecretKey, data: T) : Signature { + let encoded = ed25519::new_signed_message(data); + Signature { + bytes: sign_internal(sk.bytes, bcs::to_bytes(&encoded)), + } + } + + /// Parses the input 32 bytes as an *unvalidated* MultiEd25519 public key. + /// + /// NOTE: This function could have also checked that the # of sub-PKs is > 0, but it did not. However, since such + /// invalid PKs are rejected during signature verification (see `bugfix_unvalidated_pk_from_zero_subpks`) they + /// will not cause problems. + /// + /// We could fix this API by adding a new one that checks the # of sub-PKs is > 0, but it is likely not a good idea + /// to reproduce the PK validation logic in Move. We should not have done so in the first place. Instead, we will + /// leave it as is and continue assuming `UnvalidatedPublicKey` objects could be invalid PKs that will safely be + /// rejected during signature verification. + public fun new_unvalidated_public_key_from_bytes(bytes: vector): UnvalidatedPublicKey { + let len = vector::length(&bytes); + let num_sub_pks = len / INDIVIDUAL_PUBLIC_KEY_NUM_BYTES; + + assert!(num_sub_pks <= MAX_NUMBER_OF_PUBLIC_KEYS, error::invalid_argument(E_WRONG_PUBKEY_SIZE)); + assert!(len % INDIVIDUAL_PUBLIC_KEY_NUM_BYTES == THRESHOLD_SIZE_BYTES, error::invalid_argument(E_WRONG_PUBKEY_SIZE)); + UnvalidatedPublicKey { bytes } + } + + /// DEPRECATED: Use `new_validated_public_key_from_bytes_v2` instead. See `public_key_validate_internal` comments. + /// + /// (Incorrectly) parses the input bytes as a *validated* MultiEd25519 public key. + public fun new_validated_public_key_from_bytes(bytes: vector): Option { + // Note that `public_key_validate_internal` will check that `vector::length(&bytes) / INDIVIDUAL_PUBLIC_KEY_NUM_BYTES <= MAX_NUMBER_OF_PUBLIC_KEYS`. + if (vector::length(&bytes) % INDIVIDUAL_PUBLIC_KEY_NUM_BYTES == THRESHOLD_SIZE_BYTES && + public_key_validate_internal(bytes)) { + option::some(ValidatedPublicKey { + bytes + }) + } else { + option::none() + } + } + + /// Parses the input bytes as a *validated* MultiEd25519 public key (see `public_key_validate_internal_v2`). + public fun new_validated_public_key_from_bytes_v2(bytes: vector): Option { + if (!features::multi_ed25519_pk_validate_v2_enabled()) { + abort(error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + if (public_key_validate_v2_internal(bytes)) { + option::some(ValidatedPublicKey { + bytes + }) + } else { + option::none() + } + } + + /// Parses the input bytes as a purported MultiEd25519 multi-signature. + public fun new_signature_from_bytes(bytes: vector): Signature { + assert!(vector::length(&bytes) % INDIVIDUAL_SIGNATURE_NUM_BYTES == BITMAP_NUM_OF_BYTES, error::invalid_argument(E_WRONG_SIGNATURE_SIZE)); + Signature { bytes } + } + + /// Converts a ValidatedPublicKey to an UnvalidatedPublicKey, which can be used in the strict verification APIs. + public fun public_key_to_unvalidated(pk: &ValidatedPublicKey): UnvalidatedPublicKey { + UnvalidatedPublicKey { + bytes: pk.bytes + } + } + + /// Moves a ValidatedPublicKey into an UnvalidatedPublicKey, which can be used in the strict verification APIs. + public fun public_key_into_unvalidated(pk: ValidatedPublicKey): UnvalidatedPublicKey { + UnvalidatedPublicKey { + bytes: pk.bytes + } + } + + /// Serializes an UnvalidatedPublicKey struct to 32-bytes. + public fun unvalidated_public_key_to_bytes(pk: &UnvalidatedPublicKey): vector { + pk.bytes + } + + /// Serializes a ValidatedPublicKey struct to 32-bytes. + public fun validated_public_key_to_bytes(pk: &ValidatedPublicKey): vector { + pk.bytes + } + + /// Serializes a Signature struct to 64-bytes. + public fun signature_to_bytes(sig: &Signature): vector { + sig.bytes + } + + /// DEPRECATED: Use `public_key_validate_v2` instead. See `public_key_validate_internal` comments. + /// + /// Takes in an *unvalidated* public key and attempts to validate it. + /// Returns `Some(ValidatedPublicKey)` if successful and `None` otherwise. + public fun public_key_validate(pk: &UnvalidatedPublicKey): Option { + new_validated_public_key_from_bytes(pk.bytes) + } + + /// Takes in an *unvalidated* public key and attempts to validate it. + /// Returns `Some(ValidatedPublicKey)` if successful and `None` otherwise. + public fun public_key_validate_v2(pk: &UnvalidatedPublicKey): Option { + new_validated_public_key_from_bytes_v2(pk.bytes) + } + + /// Verifies a purported MultiEd25519 `multisignature` under an *unvalidated* `public_key` on the specified `message`. + /// This call will validate the public key by checking it is NOT in the small subgroup. + public fun signature_verify_strict( + multisignature: &Signature, + public_key: &UnvalidatedPublicKey, + message: vector + ): bool { + signature_verify_strict_internal(multisignature.bytes, public_key.bytes, message) + } + + /// This function is used to verify a multi-signature on any BCS-serializable type T. For now, it is used to verify the + /// proof of private key ownership when rotating authentication keys. + public fun signature_verify_strict_t(multisignature: &Signature, public_key: &UnvalidatedPublicKey, data: T): bool { + let encoded = ed25519::new_signed_message(data); + + signature_verify_strict_internal(multisignature.bytes, public_key.bytes, bcs::to_bytes(&encoded)) + } + + /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + public fun unvalidated_public_key_to_authentication_key(pk: &UnvalidatedPublicKey): vector { + public_key_bytes_to_authentication_key(pk.bytes) + } + + /// Returns the number n of sub-PKs in an unvalidated t-out-of-n MultiEd25519 PK. + /// If this `UnvalidatedPublicKey` would pass validation in `public_key_validate`, then the returned # of sub-PKs + /// can be relied upon as correct. + /// + /// We provide this API as a cheaper alternative to calling `public_key_validate` and then `validated_public_key_num_sub_pks` + /// when the input `pk` is known to be valid. + public fun unvalidated_public_key_num_sub_pks(pk: &UnvalidatedPublicKey): u8 { + let len = vector::length(&pk.bytes); + + ((len / INDIVIDUAL_PUBLIC_KEY_NUM_BYTES) as u8) + } + + /// Returns the number t of sub-PKs in an unvalidated t-out-of-n MultiEd25519 PK (i.e., the threshold) or `None` + /// if `bytes` does not correctly encode such a PK. + public fun unvalidated_public_key_threshold(pk: &UnvalidatedPublicKey): Option { + check_and_get_threshold(pk.bytes) + } + + /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + public fun validated_public_key_to_authentication_key(pk: &ValidatedPublicKey): vector { + public_key_bytes_to_authentication_key(pk.bytes) + } + + /// Returns the number n of sub-PKs in a validated t-out-of-n MultiEd25519 PK. + /// Since the format of this PK has been validated, the returned # of sub-PKs is guaranteed to be correct. + public fun validated_public_key_num_sub_pks(pk: &ValidatedPublicKey): u8 { + let len = vector::length(&pk.bytes); + + ((len / INDIVIDUAL_PUBLIC_KEY_NUM_BYTES) as u8) + } + + /// Returns the number t of sub-PKs in a validated t-out-of-n MultiEd25519 PK (i.e., the threshold). + public fun validated_public_key_threshold(pk: &ValidatedPublicKey): u8 { + let len = vector::length(&pk.bytes); + let threshold_byte = *vector::borrow(&pk.bytes, len - 1); + + threshold_byte + } + + /// Checks that the serialized format of a t-out-of-n MultiEd25519 PK correctly encodes 1 <= n <= 32 sub-PKs. + /// (All `ValidatedPublicKey` objects are guaranteed to pass this check.) + /// Returns the threshold t <= n of the PK. + public fun check_and_get_threshold(bytes: vector): Option { + let len = vector::length(&bytes); + if (len == 0) { + return option::none() + }; + + let threshold_num_of_bytes = len % INDIVIDUAL_PUBLIC_KEY_NUM_BYTES; + let num_of_keys = len / INDIVIDUAL_PUBLIC_KEY_NUM_BYTES; + let threshold_byte = *vector::borrow(&bytes, len - 1); + + if (num_of_keys == 0 || num_of_keys > MAX_NUMBER_OF_PUBLIC_KEYS || threshold_num_of_bytes != 1) { + return option::none() + } else if (threshold_byte == 0 || threshold_byte > (num_of_keys as u8)) { + return option::none() + } else { + return option::some(threshold_byte) + } + } + + /// Derives the Aptos-specific authentication key of the given Ed25519 public key. + fun public_key_bytes_to_authentication_key(pk_bytes: vector): vector { + vector::push_back(&mut pk_bytes, SIGNATURE_SCHEME_ID); + std::hash::sha3_256(pk_bytes) + } + + // + // Native functions + // + + /// DEPRECATED: Use `public_key_validate_internal_v2` instead. This function was NOT correctly implemented: + /// + /// 1. It does not check that the # of sub public keys is > 0, which leads to invalid `ValidatedPublicKey` objects + /// against which no signature will verify, since `signature_verify_strict_internal` will reject such invalid PKs. + /// This is not a security issue, but a correctness issue. See `bugfix_validated_pk_from_zero_subpks`. + /// 2. It charges too much gas: if the first sub-PK is invalid, it will charge for verifying all remaining sub-PKs. + /// + /// DEPRECATES: + /// - new_validated_public_key_from_bytes + /// - public_key_validate + /// + /// Return `true` if the bytes in `public_key` can be parsed as a valid MultiEd25519 public key: i.e., all underlying + /// PKs pass point-on-curve and not-in-small-subgroup checks. + /// Returns `false` otherwise. + native fun public_key_validate_internal(bytes: vector): bool; + + /// Return `true` if the bytes in `public_key` can be parsed as a valid MultiEd25519 public key: i.e., all underlying + /// sub-PKs pass point-on-curve and not-in-small-subgroup checks. + /// Returns `false` otherwise. + native fun public_key_validate_v2_internal(bytes: vector): bool; + + /// Return true if the MultiEd25519 `multisignature` on `message` verifies against the MultiEd25519 `public_key`. + /// Returns `false` if either: + /// - The PKs in `public_key` do not all pass points-on-curve or not-in-small-subgroup checks, + /// - The signatures in `multisignature` do not all pass points-on-curve or not-in-small-subgroup checks, + /// - the `multisignature` on `message` does not verify. + native fun signature_verify_strict_internal( + multisignature: vector, + public_key: vector, + message: vector + ): bool; + + #[test_only] + native fun generate_keys_internal(threshold: u8, n: u8): (vector,vector); + + #[test_only] + native fun sign_internal(sk: vector, message: vector): vector; + + // + // Tests + // + + #[test_only] + struct TestMessage has copy, drop { + foo: vector, + bar: u64, + } + + #[test_only] + public fun maul_first_signature(sig: &mut Signature) { + let first_sig_byte = vector::borrow_mut(&mut sig.bytes, 0); + *first_sig_byte = *first_sig_byte ^ 0xff; + } + + + #[test(fx = @std)] + fun bugfix_validated_pk_from_zero_subpks(fx: signer) { + features::change_feature_flags_for_testing(&fx, vector[ features::multi_ed25519_pk_validate_v2_feature()], vector[]); + let bytes = vector[1u8]; + assert!(vector::length(&bytes) == 1, 1); + + // Try deserializing a MultiEd25519 `ValidatedPublicKey` with 0 Ed25519 sub-PKs and 1 threshold byte. + // This would ideally NOT succeed, but it currently does. Regardless, such invalid PKs will be safely dismissed + // during signature verification. + let some = new_validated_public_key_from_bytes(bytes); + assert!(option::is_none(&check_and_get_threshold(bytes)), 1); // ground truth + assert!(option::is_some(&some), 2); // incorrect + + // In contrast, the v2 API will fail deserializing, as it should. + let none = new_validated_public_key_from_bytes_v2(bytes); + assert!(option::is_none(&none), 3); + } + + #[test(fx = @std)] + fun test_validated_pk_without_threshold_byte(fx: signer) { + features::change_feature_flags_for_testing(&fx, vector[ features::multi_ed25519_pk_validate_v2_feature()], vector[]); + + let (_, subpk) = ed25519::generate_keys(); + let bytes = ed25519::validated_public_key_to_bytes(&subpk); + assert!(vector::length(&bytes) == INDIVIDUAL_PUBLIC_KEY_NUM_BYTES, 1); + + // Try deserializing a MultiEd25519 `ValidatedPublicKey` with 1 Ed25519 sub-PKs but no threshold byte, which + // will not succeed, + let none = new_validated_public_key_from_bytes(bytes); + assert!(option::is_none(&check_and_get_threshold(bytes)), 1); // ground truth + assert!(option::is_none(&none), 2); // correct + + // Similarly, the v2 API will also fail deserializing. + let none = new_validated_public_key_from_bytes_v2(bytes); + assert!(option::is_none(&none), 3); // also correct + } + + #[test(fx = @std)] + fun test_validated_pk_from_small_order_subpk(fx: signer) { + features::change_feature_flags_for_testing(&fx, vector[ features::multi_ed25519_pk_validate_v2_feature()], vector[]); + let torsion_point_with_threshold_1 = vector[ + 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 1, + ]; + + assert!(option::extract(&mut check_and_get_threshold(torsion_point_with_threshold_1)) == 1, 1); + + // Try deserializing a MultiEd25519 `ValidatedPublicKey` with 1 Ed25519 sub-PKs and 1 threshold byte, as it should, + // except the sub-PK is of small order. This should not succeed, + let none = new_validated_public_key_from_bytes(torsion_point_with_threshold_1); + assert!(option::is_none(&none), 2); + + // Similarly, the v2 API will also fail deserializing. + let none = new_validated_public_key_from_bytes_v2(torsion_point_with_threshold_1); + assert!(option::is_none(&none), 3); + } + + #[test] + fun test_gen_sign_verify() { + let thresholds = vector[1, 1, 2, 2, 3, 15,]; // the thresholds, implicitly encoded in the public keys + let party_counts = vector[1, 2, 2, 3, 10, 32,]; + let test_case_count = vector::length(&party_counts); + let test_case_idx = 0; + + while (test_case_idx < test_case_count) { + let threshold = *vector::borrow(&thresholds, test_case_idx); + let group_size = *vector::borrow(&party_counts, test_case_idx); + + let (sk, pk) = generate_keys(threshold, group_size); + assert!(validated_public_key_threshold(&pk) == threshold, 1); + assert!(validated_public_key_num_sub_pks(&pk) == group_size, 2); + assert!(public_key_validate_v2_internal(pk.bytes), 3); + + let upk = public_key_into_unvalidated(pk); + assert!(option::extract(&mut unvalidated_public_key_threshold(&upk)) == threshold, 4); + assert!(unvalidated_public_key_num_sub_pks(&upk) == group_size, 5); + + let msg1 = b"Hello Aptos!"; + let sig1 = sign_arbitrary_bytes(&sk, msg1); + assert!(signature_verify_strict(&sig1, &upk, msg1), 6); + + let obj2 = TestMessage { + foo: b"Hello Move!", + bar: 64, + }; + let sig2 = sign_struct(&sk, copy obj2); + assert!(signature_verify_strict_t(&sig2, &upk, copy obj2), 7); + + test_case_idx = test_case_idx + 1; + } + } + + #[test] + fun test_threshold_not_met_rejection() { + let (sk,pk) = generate_keys(4, 5); + assert!(validated_public_key_threshold(&pk) == 4, 1); + assert!(validated_public_key_num_sub_pks(&pk) == 5, 2); + assert!(public_key_validate_v2_internal(pk.bytes), 3); + + let upk = public_key_into_unvalidated(pk); + assert!(option::extract(&mut unvalidated_public_key_threshold(&upk)) == 4, 4); + assert!(unvalidated_public_key_num_sub_pks(&upk) == 5, 5); + + let msg1 = b"Hello Aptos!"; + let sig1 = sign_arbitrary_bytes(&sk, msg1); + maul_first_signature(&mut sig1); + assert!(!signature_verify_strict(&sig1, &upk, msg1), 6); + + let obj2 = TestMessage { + foo: b"Hello Move!", + bar: 64, + }; + let sig2 = sign_struct(&sk, copy obj2); + maul_first_signature(&mut sig2); + assert!(!signature_verify_strict_t(&sig2, &upk, copy obj2), 7); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/pool_u64.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/pool_u64.move new file mode 100644 index 000000000..f1aaea9fd --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/pool_u64.move @@ -0,0 +1,571 @@ +/// +/// Simple module for tracking and calculating shares of a pool of coins. The shares are worth more as the total coins in +/// the pool increases. New shareholder can buy more shares or redeem their existing shares. +/// +/// Example flow: +/// 1. Pool start outs empty. +/// 2. Shareholder A buys in with 1000 coins. A will receive 1000 shares in the pool. Pool now has 1000 total coins and +/// 1000 total shares. +/// 3. Pool appreciates in value from rewards and now has 2000 coins. A's 1000 shares are now worth 2000 coins. +/// 4. Shareholder B now buys in with 1000 coins. Since before the buy in, each existing share is worth 2 coins, B will +/// receive 500 shares in exchange for 1000 coins. Pool now has 1500 shares and 3000 coins. +/// 5. Pool appreciates in value from rewards and now has 6000 coins. +/// 6. A redeems 500 shares. Each share is worth 6000 / 1500 = 4. A receives 2000 coins. Pool has 4000 coins and 1000 +/// shares left. +/// +module aptos_std::pool_u64 { + use aptos_std::simple_map::{Self, SimpleMap}; + use std::error; + use std::vector; + + /// Shareholder not present in pool. + const ESHAREHOLDER_NOT_FOUND: u64 = 1; + /// There are too many shareholders in the pool. + const ETOO_MANY_SHAREHOLDERS: u64 = 2; + /// Cannot destroy non-empty pool. + const EPOOL_IS_NOT_EMPTY: u64 = 3; + /// Cannot redeem more shares than the shareholder has in the pool. + const EINSUFFICIENT_SHARES: u64 = 4; + /// Shareholder cannot have more than u64.max shares. + const ESHAREHOLDER_SHARES_OVERFLOW: u64 = 5; + /// Pool's total coins cannot exceed u64.max. + const EPOOL_TOTAL_COINS_OVERFLOW: u64 = 6; + /// Pool's total shares cannot exceed u64.max. + const EPOOL_TOTAL_SHARES_OVERFLOW: u64 = 7; + + const MAX_U64: u64 = 18446744073709551615; + + struct Pool has store { + shareholders_limit: u64, + total_coins: u64, + total_shares: u64, + shares: SimpleMap, + shareholders: vector
, + // Default to 1. This can be used to minimize rounding errors when computing shares and coins amount. + // However, users need to make sure the coins amount don't overflow when multiplied by the scaling factor. + scaling_factor: u64, + } + + /// Create a new pool. + public fun new(shareholders_limit: u64): Pool { + // Default to a scaling factor of 1 (effectively no scaling). + create_with_scaling_factor(shareholders_limit, 1) + } + + #[deprecated] + /// Deprecated. Use `new` instead. + /// Create a new pool. + public fun create(shareholders_limit: u64): Pool { + new(shareholders_limit) + } + + /// Create a new pool with custom `scaling_factor`. + public fun create_with_scaling_factor(shareholders_limit: u64, scaling_factor: u64): Pool { + Pool { + shareholders_limit, + total_coins: 0, + total_shares: 0, + shares: simple_map::create(), + shareholders: vector::empty
(), + scaling_factor, + } + } + + /// Destroy an empty pool. This will fail if the pool has any balance of coins. + public fun destroy_empty(pool: Pool) { + assert!(pool.total_coins == 0, error::invalid_state(EPOOL_IS_NOT_EMPTY)); + let Pool { + shareholders_limit: _, + total_coins: _, + total_shares: _, + shares: _, + shareholders: _, + scaling_factor: _, + } = pool; + } + + /// Return `pool`'s total balance of coins. + public fun total_coins(pool: &Pool): u64 { + pool.total_coins + } + + /// Return the total number of shares across all shareholders in `pool`. + public fun total_shares(pool: &Pool): u64 { + pool.total_shares + } + + /// Return true if `shareholder` is in `pool`. + public fun contains(pool: &Pool, shareholder: address): bool { + simple_map::contains_key(&pool.shares, &shareholder) + } + + /// Return the number of shares of `stakeholder` in `pool`. + public fun shares(pool: &Pool, shareholder: address): u64 { + if (contains(pool, shareholder)) { + *simple_map::borrow(&pool.shares, &shareholder) + } else { + 0 + } + } + + /// Return the balance in coins of `shareholder` in `pool.` + public fun balance(pool: &Pool, shareholder: address): u64 { + let num_shares = shares(pool, shareholder); + shares_to_amount(pool, num_shares) + } + + /// Return the list of shareholders in `pool`. + public fun shareholders(pool: &Pool): vector
{ + pool.shareholders + } + + /// Return the number of shareholders in `pool`. + public fun shareholders_count(pool: &Pool): u64 { + vector::length(&pool.shareholders) + } + + /// Update `pool`'s total balance of coins. + public fun update_total_coins(pool: &mut Pool, new_total_coins: u64) { + pool.total_coins = new_total_coins; + } + + /// Allow an existing or new shareholder to add their coins to the pool in exchange for new shares. + public fun buy_in(pool: &mut Pool, shareholder: address, coins_amount: u64): u64 { + if (coins_amount == 0) return 0; + + let new_shares = amount_to_shares(pool, coins_amount); + assert!(MAX_U64 - pool.total_coins >= coins_amount, error::invalid_argument(EPOOL_TOTAL_COINS_OVERFLOW)); + assert!(MAX_U64 - pool.total_shares >= new_shares, error::invalid_argument(EPOOL_TOTAL_COINS_OVERFLOW)); + + pool.total_coins = pool.total_coins + coins_amount; + pool.total_shares = pool.total_shares + new_shares; + add_shares(pool, shareholder, new_shares); + new_shares + } + + /// Add the number of shares directly for `shareholder` in `pool`. + /// This would dilute other shareholders if the pool's balance of coins didn't change. + fun add_shares(pool: &mut Pool, shareholder: address, new_shares: u64): u64 { + if (contains(pool, shareholder)) { + let existing_shares = simple_map::borrow_mut(&mut pool.shares, &shareholder); + let current_shares = *existing_shares; + assert!(MAX_U64 - current_shares >= new_shares, error::invalid_argument(ESHAREHOLDER_SHARES_OVERFLOW)); + + *existing_shares = current_shares + new_shares; + *existing_shares + } else if (new_shares > 0) { + assert!( + vector::length(&pool.shareholders) < pool.shareholders_limit, + error::invalid_state(ETOO_MANY_SHAREHOLDERS), + ); + + vector::push_back(&mut pool.shareholders, shareholder); + simple_map::add(&mut pool.shares, shareholder, new_shares); + new_shares + } else { + new_shares + } + } + + /// Allow `shareholder` to redeem their shares in `pool` for coins. + public fun redeem_shares(pool: &mut Pool, shareholder: address, shares_to_redeem: u64): u64 { + assert!(contains(pool, shareholder), error::invalid_argument(ESHAREHOLDER_NOT_FOUND)); + assert!(shares(pool, shareholder) >= shares_to_redeem, error::invalid_argument(EINSUFFICIENT_SHARES)); + + if (shares_to_redeem == 0) return 0; + + let redeemed_coins = shares_to_amount(pool, shares_to_redeem); + pool.total_coins = pool.total_coins - redeemed_coins; + pool.total_shares = pool.total_shares - shares_to_redeem; + deduct_shares(pool, shareholder, shares_to_redeem); + + redeemed_coins + } + + /// Transfer shares from `shareholder_1` to `shareholder_2`. + public fun transfer_shares( + pool: &mut Pool, + shareholder_1: address, + shareholder_2: address, + shares_to_transfer: u64, + ) { + assert!(contains(pool, shareholder_1), error::invalid_argument(ESHAREHOLDER_NOT_FOUND)); + assert!(shares(pool, shareholder_1) >= shares_to_transfer, error::invalid_argument(EINSUFFICIENT_SHARES)); + if (shares_to_transfer == 0) return; + + deduct_shares(pool, shareholder_1, shares_to_transfer); + add_shares(pool, shareholder_2, shares_to_transfer); + } + + /// Directly deduct `shareholder`'s number of shares in `pool` and return the number of remaining shares. + fun deduct_shares(pool: &mut Pool, shareholder: address, num_shares: u64): u64 { + assert!(contains(pool, shareholder), error::invalid_argument(ESHAREHOLDER_NOT_FOUND)); + assert!(shares(pool, shareholder) >= num_shares, error::invalid_argument(EINSUFFICIENT_SHARES)); + + let existing_shares = simple_map::borrow_mut(&mut pool.shares, &shareholder); + *existing_shares = *existing_shares - num_shares; + + // Remove the shareholder completely if they have no shares left. + let remaining_shares = *existing_shares; + if (remaining_shares == 0) { + let (_, shareholder_index) = vector::index_of(&pool.shareholders, &shareholder); + vector::remove(&mut pool.shareholders, shareholder_index); + simple_map::remove(&mut pool.shares, &shareholder); + }; + + remaining_shares + } + + /// Return the number of new shares `coins_amount` can buy in `pool`. + /// `amount` needs to big enough to avoid rounding number. + public fun amount_to_shares(pool: &Pool, coins_amount: u64): u64 { + amount_to_shares_with_total_coins(pool, coins_amount, pool.total_coins) + } + + /// Return the number of new shares `coins_amount` can buy in `pool` with a custom total coins number. + /// `amount` needs to big enough to avoid rounding number. + public fun amount_to_shares_with_total_coins(pool: &Pool, coins_amount: u64, total_coins: u64): u64 { + // No shares yet so amount is worth the same number of shares. + if (pool.total_coins == 0 || pool.total_shares == 0) { + // Multiply by scaling factor to minimize rounding errors during internal calculations for buy ins/redeems. + // This can overflow but scaling factor is expected to be chosen carefully so this would not overflow. + coins_amount * pool.scaling_factor + } else { + // Shares price = total_coins / total existing shares. + // New number of shares = new_amount / shares_price = new_amount * existing_shares / total_amount. + // We rearrange the calc and do multiplication first to avoid rounding errors. + multiply_then_divide(pool, coins_amount, pool.total_shares, total_coins) + } + } + + /// Return the number of coins `shares` are worth in `pool`. + /// `shares` needs to big enough to avoid rounding number. + public fun shares_to_amount(pool: &Pool, shares: u64): u64 { + shares_to_amount_with_total_coins(pool, shares, pool.total_coins) + } + + /// Return the number of coins `shares` are worth in `pool` with a custom total coins number. + /// `shares` needs to big enough to avoid rounding number. + public fun shares_to_amount_with_total_coins(pool: &Pool, shares: u64, total_coins: u64): u64 { + // No shares or coins yet so shares are worthless. + if (pool.total_coins == 0 || pool.total_shares == 0) { + 0 + } else { + // Shares price = total_coins / total existing shares. + // Shares worth = shares * shares price = shares * total_coins / total existing shares. + // We rearrange the calc and do multiplication first to avoid rounding errors. + multiply_then_divide(pool, shares, total_coins, pool.total_shares) + } + } + + public fun multiply_then_divide(_pool: &Pool, x: u64, y: u64, z: u64): u64 { + let result = (to_u128(x) * to_u128(y)) / to_u128(z); + (result as u64) + } + + fun to_u128(num: u64): u128 { + (num as u128) + } + + #[test_only] + public fun destroy_pool(pool: Pool) { + let Pool { + shareholders_limit: _, + total_coins: _, + total_shares: _, + shares: _, + shareholders: _, + scaling_factor: _, + } = pool; + } + + #[test] + public entry fun test_buy_in_and_redeem() { + let pool = new(5); + + // Shareholders 1 and 2 buy in first. + buy_in(&mut pool, @1, 1000); + buy_in(&mut pool, @2, 2000); + assert!(shareholders_count(&pool) == 2, 0); + assert!(total_coins(&pool) == 3000, 1); + assert!(total_shares(&pool) == 3000, 2); + assert!(shares(&pool, @1) == 1000, 3); + assert!(shares(&pool, @2) == 2000, 4); + assert!(balance(&pool, @1) == 1000, 5); + assert!(balance(&pool, @2) == 2000, 6); + + // Pool increases in value. + update_total_coins(&mut pool, 5000); + assert!(shares(&pool, @1) == 1000, 7); + assert!(shares(&pool, @2) == 2000, 8); + let expected_balance_1 = 1000 * 5000 / 3000; + assert!(balance(&pool, @1) == expected_balance_1, 9); + let expected_balance_2 = 2000 * 5000 / 3000; + assert!(balance(&pool, @2) == expected_balance_2, 10); + + // Shareholder 3 buys in into the 5000-coin pool with 1000 coins. There are 3000 existing shares. + let expected_shares = 1000 * 3000 / 5000; + buy_in(&mut pool, @3, 1000); + assert!(shares(&pool, @3) == expected_shares, 11); + assert!(balance(&pool, @3) == 1000, 12); + + // Pool increases more in value. + update_total_coins(&mut pool, 8000); + + // Shareholders 1 and 2 redeem. + let all_shares = 3000 + expected_shares; + assert!(total_shares(&pool) == all_shares, 13); + let expected_value_per_500_shares = 500 * 8000 / all_shares; + assert!(redeem_shares(&mut pool, @1, 500) == expected_value_per_500_shares, 14); + assert!(redeem_shares(&mut pool, @1, 500) == expected_value_per_500_shares, 15); + assert!(redeem_shares(&mut pool, @2, 2000) == expected_value_per_500_shares * 4, 16); + + // Due to a very small rounding error of 1, shareholder 3 actually has 1 more coin. + let shareholder_3_balance = expected_value_per_500_shares * 6 / 5 + 1; + assert!(balance(&pool, @3) == shareholder_3_balance, 17); + assert!(total_coins(&pool) == shareholder_3_balance, 18); + assert!(shareholders_count(&pool) == 1, 19); + let num_shares_3 = shares(&pool, @3); + assert!(redeem_shares(&mut pool, @3, num_shares_3) == shareholder_3_balance, 20); + + // Nothing left. + assert!(shareholders_count(&pool) == 0, 21); + destroy_empty(pool); + } + + #[test] + #[expected_failure(abort_code = 196611, location = Self)] + public entry fun test_destroy_empty_should_fail_if_not_empty() { + let pool = new(1); + update_total_coins(&mut pool, 100); + destroy_empty(pool); + } + + #[test] + public entry fun test_buy_in_and_redeem_large_numbers() { + let pool = new(2); + let half_max_u64 = MAX_U64 / 2; + let shares_1 = buy_in(&mut pool, @1, half_max_u64); + assert!(shares_1 == half_max_u64, 0); + let shares_2 = buy_in(&mut pool, @2, half_max_u64 + 1); + assert!(shares_2 == half_max_u64 + 1, 1); + assert!(total_shares(&pool) == MAX_U64, 2); + assert!(total_coins(&pool) == MAX_U64, 3); + assert!(redeem_shares(&mut pool, @1, shares_1) == half_max_u64, 4); + assert!(redeem_shares(&mut pool, @2, shares_2) == half_max_u64 + 1, 5); + destroy_empty(pool); + } + + #[test] + public entry fun test_buy_in_and_redeem_large_numbers_with_scaling_factor() { + let scaling_factor = 100; + let pool = create_with_scaling_factor(2, scaling_factor); + let coins_amount = MAX_U64 / 100; + let shares = buy_in(&mut pool, @1, coins_amount); + assert!(total_shares(&pool) == coins_amount * scaling_factor, 0); + assert!(total_coins(&pool) == coins_amount, 1); + assert!(redeem_shares(&mut pool, @1, shares) == coins_amount, 2); + destroy_empty(pool); + } + + #[test] + public entry fun test_buy_in_zero_amount() { + let pool = new(2); + buy_in(&mut pool, @1, 100); + assert!(buy_in(&mut pool, @2, 0) == 0, 0); + assert!(total_shares(&pool) == shares(&pool, @1), 1); + assert!(shareholders_count(&pool) == 1, 2); + destroy_pool(pool); + } + + #[test] + public entry fun test_buy_in_with_small_coins_amount() { + let pool = new(2); + // Shareholder 1 buys in with 1e17 coins. + buy_in(&mut pool, @1, 100000000000000000); + // Shareholder 2 buys in with a very small amount. + assert!(buy_in(&mut pool, @2, 1) == 1, 0); + // Pool's total coins increases by 20%. Shareholder 2 shouldn't see any actual balance increase as it gets + // rounded down. + let total_coins = total_coins(&pool); + update_total_coins(&mut pool, total_coins * 6 / 5); + // Minus 1 due to rounding error. + assert!(balance(&pool, @1) == 100000000000000000 * 6 / 5 - 1, 1); + assert!(balance(&pool, @2) == 1, 2); + destroy_pool(pool); + } + + #[test] + public entry fun test_add_zero_shares_should_not_add_shareholder() { + let pool = new(1); + update_total_coins(&mut pool, 1000); + assert!(add_shares(&mut pool, @1, 0) == 0, 0); + assert!(shareholders_count(&pool) == 0, 1); + destroy_pool(pool); + } + + #[test] + public entry fun test_add_zero_shares_returns_existing_number_of_shares() { + let pool = new(1); + update_total_coins(&mut pool, 1000); + add_shares(&mut pool, @1, 1); + assert!(shares(&pool, @1) == add_shares(&mut pool, @1, 0), 0); + destroy_pool(pool); + } + + #[test] + public entry fun test_add_shares_existing_shareholder() { + let pool = new(1); + update_total_coins(&mut pool, 1000); + add_shares(&mut pool, @1, 1); + add_shares(&mut pool, @1, 2); + assert!(shares(&mut pool, @1) == 3, 0); + destroy_pool(pool); + } + + #[test] + public entry fun test_add_shares_new_shareholder() { + let pool = new(2); + update_total_coins(&mut pool, 1000); + add_shares(&mut pool, @1, 1); + add_shares(&mut pool, @2, 2); + assert!(shares(&mut pool, @1) == 1, 0); + assert!(shares(&mut pool, @2) == 2, 1); + destroy_pool(pool); + } + + #[test] + #[expected_failure(abort_code = 196610, location = Self)] + public entry fun test_add_shares_should_enforce_shareholder_limit() { + let pool = new(2); + add_shares(&mut pool, @1, 1); + add_shares(&mut pool, @2, 2); + add_shares(&mut pool, @3, 2); + destroy_pool(pool); + } + + #[test] + public entry fun test_add_shares_should_work_after_reducing_shareholders_below_limit() { + let pool = new(3); + add_shares(&mut pool, @1, 1); + add_shares(&mut pool, @2, 2); + deduct_shares(&mut pool, @2, 2); + add_shares(&mut pool, @3, 3); + assert!(shares(&pool, @3) == 3, 0); + destroy_pool(pool); + } + + #[test] + #[expected_failure(abort_code = 65537, location = Self)] + public entry fun test_redeem_shares_non_existent_shareholder() { + let pool = new(1); + add_shares(&mut pool, @1, 1); + redeem_shares(&mut pool, @2, 1); + destroy_pool(pool); + } + + #[test] + #[expected_failure(abort_code = 65540, location = Self)] + public entry fun test_redeem_shares_insufficient_shares() { + let pool = new(1); + add_shares(&mut pool, @1, 1); + redeem_shares(&mut pool, @1, 2); + destroy_pool(pool); + } + + #[test] + public entry fun test_redeem_small_number_of_shares() { + let pool = new(2); + // 1e17 shares and coins. + buy_in(&mut pool, @1, 100000000000000000); + buy_in(&mut pool, @2, 100000000000000000); + assert!(redeem_shares(&mut pool, @1, 1) == 1, 0); + destroy_pool(pool); + } + + #[test] + public entry fun test_redeem_zero_shares() { + let pool = new(2); + buy_in(&mut pool, @1, 1); + assert!(redeem_shares(&mut pool, @1, 0) == 0, 0); + assert!(shares(&pool, @1) == 1, 1); + assert!(total_coins(&pool) == 1, 2); + assert!(total_shares(&pool) == 1, 3); + destroy_pool(pool); + } + + #[test] + #[expected_failure(abort_code = 65537, location = Self)] + public entry fun test_deduct_shares_non_existent_shareholder() { + let pool = new(1); + add_shares(&mut pool, @1, 1); + deduct_shares(&mut pool, @2, 1); + destroy_pool(pool); + } + + #[test] + #[expected_failure(abort_code = 65540, location = Self)] + public entry fun test_deduct_shares_insufficient_shares() { + let pool = new(1); + add_shares(&mut pool, @1, 1); + deduct_shares(&mut pool, @1, 2); + destroy_pool(pool); + } + + #[test] + public entry fun test_deduct_shares_remove_shareholder_with_no_shares() { + let pool = new(2); + add_shares(&mut pool, @1, 1); + add_shares(&mut pool, @2, 2); + assert!(shareholders_count(&pool) == 2, 0); + deduct_shares(&mut pool, @1, 1); + assert!(shareholders_count(&pool) == 1, 1); + destroy_pool(pool); + } + + #[test] + public entry fun test_transfer_shares() { + let pool = new(2); + add_shares(&mut pool, @1, 2); + add_shares(&mut pool, @2, 2); + assert!(shareholders_count(&pool) == 2, 0); + transfer_shares(&mut pool, @1, @2, 1); + assert!(shares(&pool, @1) == 1, 0); + assert!(shares(&pool, @2) == 3, 0); + destroy_pool(pool); + } + + #[test] + public entry fun test_amount_to_shares_empty_pool() { + let pool = new(1); + // No total shares and total coins. + assert!(amount_to_shares(&pool, 1000) == 1000, 0); + + // No total shares but some total coins. + update_total_coins(&mut pool, 1000); + assert!(amount_to_shares(&pool, 1000) == 1000, 1); + + // No total coins but some total shares. + update_total_coins(&mut pool, 0); + add_shares(&mut pool, @1, 100); + assert!(amount_to_shares(&pool, 1000) == 1000, 2); + destroy_pool(pool); + } + + #[test] + public entry fun test_shares_to_amount_empty_pool() { + let pool = new(1); + // No total shares and total coins. + assert!(shares_to_amount(&pool, 1000) == 0, 0); + + // No total shares but some total coins. + update_total_coins(&mut pool, 1000); + assert!(shares_to_amount(&pool, 1000) == 0, 1); + + // No total coins but some total shares. + update_total_coins(&mut pool, 0); + add_shares(&mut pool, @1, 100); + assert!(shares_to_amount(&pool, 1000) == 0, 2); + destroy_pool(pool); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/pool_u64_unbound.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/pool_u64_unbound.move new file mode 100644 index 000000000..c9ab78e3b --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/pool_u64_unbound.move @@ -0,0 +1,270 @@ +/// +/// Simple module for tracking and calculating shares of a pool of coins. The shares are worth more as the total coins in +/// the pool increases. New shareholder can buy more shares or redeem their existing shares. +/// +/// Example flow: +/// 1. Pool start outs empty. +/// 2. Shareholder A buys in with 1000 coins. A will receive 1000 shares in the pool. Pool now has 1000 total coins and +/// 1000 total shares. +/// 3. Pool appreciates in value from rewards and now has 2000 coins. A's 1000 shares are now worth 2000 coins. +/// 4. Shareholder B now buys in with 1000 coins. Since before the buy in, each existing share is worth 2 coins, B will +/// receive 500 shares in exchange for 1000 coins. Pool now has 1500 shares and 3000 coins. +/// 5. Pool appreciates in value from rewards and now has 6000 coins. +/// 6. A redeems 500 shares. Each share is worth 6000 / 1500 = 4. A receives 2000 coins. Pool has 4000 coins and 1000 +/// shares left. +/// +module aptos_std::pool_u64_unbound { + use aptos_std::table_with_length::{Self as table, TableWithLength as Table}; + use std::error; + + /// Shareholder not present in pool. + const ESHAREHOLDER_NOT_FOUND: u64 = 1; + /// There are too many shareholders in the pool. + const ETOO_MANY_SHAREHOLDERS: u64 = 2; + /// Cannot destroy non-empty pool. + const EPOOL_IS_NOT_EMPTY: u64 = 3; + /// Cannot redeem more shares than the shareholder has in the pool. + const EINSUFFICIENT_SHARES: u64 = 4; + /// Shareholder cannot have more than u64.max shares. + const ESHAREHOLDER_SHARES_OVERFLOW: u64 = 5; + /// Pool's total coins cannot exceed u64.max. + const EPOOL_TOTAL_COINS_OVERFLOW: u64 = 6; + /// Pool's total shares cannot exceed u64.max. + const EPOOL_TOTAL_SHARES_OVERFLOW: u64 = 7; + + const MAX_U64: u64 = 18446744073709551615; + + const MAX_U128: u128 = 340282366920938463463374607431768211455; + + struct Pool has store { + total_coins: u64, + total_shares: u128, + shares: Table, + // Default to 1. This can be used to minimize rounding errors when computing shares and coins amount. + // However, users need to make sure the coins amount don't overflow when multiplied by the scaling factor. + scaling_factor: u64, + } + + /// Create a new pool. + public fun new(): Pool { + // Default to a scaling factor of 1 (effectively no scaling). + create_with_scaling_factor(1) + } + + #[deprecated] + /// Deprecated. Use `new` instead. + /// Create a new pool. + public fun create(): Pool { + new() + } + + /// Create a new pool with custom `scaling_factor`. + public fun create_with_scaling_factor(scaling_factor: u64): Pool { + Pool { + total_coins: 0, + total_shares: 0, + shares: table::new(), + scaling_factor, + } + } + + /// Destroy an empty pool. This will fail if the pool has any balance of coins. + public fun destroy_empty(pool: Pool) { + assert!(pool.total_coins == 0, error::invalid_state(EPOOL_IS_NOT_EMPTY)); + let Pool { + total_coins: _, + total_shares: _, + shares, + scaling_factor: _, + } = pool; + table::destroy_empty(shares); + } + + /// Return `pool`'s total balance of coins. + public fun total_coins(pool: &Pool): u64 { + pool.total_coins + } + + /// Return the total number of shares across all shareholders in `pool`. + public fun total_shares(pool: &Pool): u128 { + pool.total_shares + } + + /// Return true if `shareholder` is in `pool`. + public fun contains(pool: &Pool, shareholder: address): bool { + table::contains(&pool.shares, shareholder) + } + + /// Return the number of shares of `stakeholder` in `pool`. + public fun shares(pool: &Pool, shareholder: address): u128 { + if (contains(pool, shareholder)) { + *table::borrow(&pool.shares, shareholder) + } else { + 0 + } + } + + /// Return the balance in coins of `shareholder` in `pool.` + public fun balance(pool: &Pool, shareholder: address): u64 { + let num_shares = shares(pool, shareholder); + shares_to_amount(pool, num_shares) + } + + /// Return the number of shareholders in `pool`. + public fun shareholders_count(pool: &Pool): u64 { + table::length(&pool.shares) + } + + /// Update `pool`'s total balance of coins. + public fun update_total_coins(pool: &mut Pool, new_total_coins: u64) { + pool.total_coins = new_total_coins; + } + + /// Allow an existing or new shareholder to add their coins to the pool in exchange for new shares. + public fun buy_in(pool: &mut Pool, shareholder: address, coins_amount: u64): u128 { + if (coins_amount == 0) return 0; + + let new_shares = amount_to_shares(pool, coins_amount); + assert!(MAX_U64 - pool.total_coins >= coins_amount, error::invalid_argument(EPOOL_TOTAL_COINS_OVERFLOW)); + assert!(MAX_U128 - pool.total_shares >= new_shares, error::invalid_argument(EPOOL_TOTAL_SHARES_OVERFLOW)); + + pool.total_coins = pool.total_coins + coins_amount; + pool.total_shares = pool.total_shares + new_shares; + add_shares(pool, shareholder, new_shares); + new_shares + } + + /// Add the number of shares directly for `shareholder` in `pool`. + /// This would dilute other shareholders if the pool's balance of coins didn't change. + fun add_shares(pool: &mut Pool, shareholder: address, new_shares: u128): u128 { + if (contains(pool, shareholder)) { + let existing_shares = table::borrow_mut(&mut pool.shares, shareholder); + let current_shares = *existing_shares; + assert!(MAX_U128 - current_shares >= new_shares, error::invalid_argument(ESHAREHOLDER_SHARES_OVERFLOW)); + + *existing_shares = current_shares + new_shares; + *existing_shares + } else if (new_shares > 0) { + table::add(&mut pool.shares, shareholder, new_shares); + new_shares + } else { + new_shares + } + } + + /// Allow `shareholder` to redeem their shares in `pool` for coins. + public fun redeem_shares(pool: &mut Pool, shareholder: address, shares_to_redeem: u128): u64 { + assert!(contains(pool, shareholder), error::invalid_argument(ESHAREHOLDER_NOT_FOUND)); + assert!(shares(pool, shareholder) >= shares_to_redeem, error::invalid_argument(EINSUFFICIENT_SHARES)); + + if (shares_to_redeem == 0) return 0; + + let redeemed_coins = shares_to_amount(pool, shares_to_redeem); + pool.total_coins = pool.total_coins - redeemed_coins; + pool.total_shares = pool.total_shares - shares_to_redeem; + deduct_shares(pool, shareholder, shares_to_redeem); + + redeemed_coins + } + + /// Transfer shares from `shareholder_1` to `shareholder_2`. + public fun transfer_shares( + pool: &mut Pool, + shareholder_1: address, + shareholder_2: address, + shares_to_transfer: u128, + ) { + assert!(contains(pool, shareholder_1), error::invalid_argument(ESHAREHOLDER_NOT_FOUND)); + assert!(shares(pool, shareholder_1) >= shares_to_transfer, error::invalid_argument(EINSUFFICIENT_SHARES)); + if (shares_to_transfer == 0) return; + + deduct_shares(pool, shareholder_1, shares_to_transfer); + add_shares(pool, shareholder_2, shares_to_transfer); + } + + /// Directly deduct `shareholder`'s number of shares in `pool` and return the number of remaining shares. + fun deduct_shares(pool: &mut Pool, shareholder: address, num_shares: u128): u128 { + assert!(contains(pool, shareholder), error::invalid_argument(ESHAREHOLDER_NOT_FOUND)); + assert!(shares(pool, shareholder) >= num_shares, error::invalid_argument(EINSUFFICIENT_SHARES)); + + let existing_shares = table::borrow_mut(&mut pool.shares, shareholder); + *existing_shares = *existing_shares - num_shares; + + // Remove the shareholder completely if they have no shares left. + let remaining_shares = *existing_shares; + if (remaining_shares == 0) { + table::remove(&mut pool.shares, shareholder); + }; + + remaining_shares + } + + /// Return the number of new shares `coins_amount` can buy in `pool`. + /// `amount` needs to big enough to avoid rounding number. + public fun amount_to_shares(pool: &Pool, coins_amount: u64): u128 { + amount_to_shares_with_total_coins(pool, coins_amount, pool.total_coins) + } + + /// Return the number of new shares `coins_amount` can buy in `pool` with a custom total coins number. + /// `amount` needs to big enough to avoid rounding number. + public fun amount_to_shares_with_total_coins(pool: &Pool, coins_amount: u64, total_coins: u64): u128 { + // No shares yet so amount is worth the same number of shares. + if (pool.total_coins == 0 || pool.total_shares == 0) { + // Multiply by scaling factor to minimize rounding errors during internal calculations for buy ins/redeems. + // This can overflow but scaling factor is expected to be chosen carefully so this would not overflow. + to_u128(coins_amount) * to_u128(pool.scaling_factor) + } else { + // Shares price = total_coins / total existing shares. + // New number of shares = new_amount / shares_price = new_amount * existing_shares / total_amount. + // We rearrange the calc and do multiplication first to avoid rounding errors. + multiply_then_divide(pool, to_u128(coins_amount), pool.total_shares, to_u128(total_coins)) + } + } + + /// Return the number of coins `shares` are worth in `pool`. + /// `shares` needs to big enough to avoid rounding number. + public fun shares_to_amount(pool: &Pool, shares: u128): u64 { + shares_to_amount_with_total_coins(pool, shares, pool.total_coins) + } + + /// Return the number of coins `shares` are worth in `pool` with a custom total coins number. + /// `shares` needs to big enough to avoid rounding number. + public fun shares_to_amount_with_total_coins(pool: &Pool, shares: u128, total_coins: u64): u64 { + // No shares or coins yet so shares are worthless. + if (pool.total_coins == 0 || pool.total_shares == 0) { + 0 + } else { + // Shares price = total_coins / total existing shares. + // Shares worth = shares * shares price = shares * total_coins / total existing shares. + // We rearrange the calc and do multiplication first to avoid rounding errors. + (multiply_then_divide(pool, shares, to_u128(total_coins), pool.total_shares) as u64) + } + } + + /// Return the number of coins `shares` are worth in `pool` with custom total coins and shares numbers. + public fun shares_to_amount_with_total_stats( + pool: &Pool, + shares: u128, + total_coins: u64, + total_shares: u128, + ): u64 { + if (pool.total_coins == 0 || total_shares == 0) { + 0 + } else { + (multiply_then_divide(pool, shares, to_u128(total_coins), total_shares) as u64) + } + } + + public fun multiply_then_divide(_pool: &Pool, x: u128, y: u128, z: u128): u128 { + let result = (to_u256(x) * to_u256(y)) / to_u256(z); + (result as u128) + } + + fun to_u128(num: u64): u128 { + (num as u128) + } + + fun to_u256(num: u128): u256 { + (num as u256) + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/ristretto255.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/ristretto255.move new file mode 100644 index 000000000..79905c578 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/ristretto255.move @@ -0,0 +1,1310 @@ +/// This module contains functions for Ristretto255 curve arithmetic, assuming addition as the group operation. +/// +/// The order of the Ristretto255 elliptic curve group is $\ell = 2^252 + 27742317777372353535851937790883648493$, same +/// as the order of the prime-order subgroup of Curve25519. +/// +/// This module provides two structs for encoding Ristretto elliptic curves to the developer: +/// +/// - First, a 32-byte-sized CompressedRistretto struct, which is used to persist points in storage. +/// +/// - Second, a larger, in-memory, RistrettoPoint struct, which is decompressable from a CompressedRistretto struct. This +/// larger struct can be used for fast arithmetic operations (additions, multiplications, etc.). The results can be saved +/// back into storage by compressing RistrettoPoint structs back to CompressedRistretto structs. +/// +/// This module also provides a Scalar struct for persisting scalars in storage and doing fast arithmetic on them. +/// +/// One invariant maintained by this module is that all CompressedRistretto structs store a canonically-encoded point, +/// which can always be decompressed into a valid point on the curve as a RistrettoPoint struct. Unfortunately, due to +/// limitations in our underlying curve25519-dalek elliptic curve library, this decompression will unnecessarily verify +/// the validity of the point and thus slightly decrease performance. +/// +/// Similarly, all Scalar structs store a canonically-encoded scalar, which can always be safely operated on using +/// arithmetic operations. +/// +/// In the future, we might support additional features: +/// +/// * For scalars: +/// - batch_invert() +/// +/// * For points: +/// - double() +/// + The challenge is that curve25519-dalek does NOT export double for Ristretto points (nor for Edwards) +/// +/// - double_and_compress_batch() +/// +/// - fixed-base, variable-time via optional_mixed_multiscalar_mul() in VartimePrecomputedMultiscalarMul +/// + This would require a storage-friendly RistrettoBasepointTable and an in-memory variant of it too +/// + Similar to the CompressedRistretto and RistrettoPoint structs in this module +/// + The challenge is that curve25519-dalek's RistrettoBasepointTable is not serializable + +module aptos_std::ristretto255 { + use std::features; + use std::option::Option; + + #[test_only] + use std::option; + + // + // Constants + // + + /// The order of the Ristretto255 group and its scalar field, in little-endian. + const ORDER_ELL: vector = x"edd3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010"; + + /// `ORDER_ELL` - 1: i.e., the "largest", reduced scalar in the field + const L_MINUS_ONE: vector = x"ecd3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010"; + + /// The maximum size in bytes of a canonically-encoded Scalar is 32 bytes. + const MAX_SCALAR_NUM_BYTES: u64 = 32u64; + + /// The maximum size in bits of a canonically-encoded Scalar is 256 bits. + const MAX_SCALAR_NUM_BITS: u64 = 256u64; + + /// The maximum size in bytes of a canonically-encoded Ristretto255 point is 32 bytes. + const MAX_POINT_NUM_BYTES: u64 = 32u64; + + /// The basepoint (generator) of the Ristretto255 group + const BASE_POINT: vector = x"e2f2ae0a6abc4e71a884a961c500515f58e30b6aa582dd8db6a65945e08d2d76"; + + /// The hash of the basepoint of the Ristretto255 group using SHA3_512 + const HASH_BASE_POINT: vector = x"8c9240b456a9e6dc65c377a1048d745f94a08cdb7f44cbcd7b46f34048871134"; + + // + // Reasons for error codes + // + + /// The number of scalars does not match the number of points. + const E_DIFFERENT_NUM_POINTS_AND_SCALARS: u64 = 1; + /// Expected more than zero points as input. + const E_ZERO_POINTS: u64 = 2; + /// Expected more than zero scalars as input. + const E_ZERO_SCALARS: u64 = 3; + /// Too many points have been created in the current transaction execution. + const E_TOO_MANY_POINTS_CREATED: u64 = 4; + /// The native function has not been deployed yet. + const E_NATIVE_FUN_NOT_AVAILABLE: u64 = 5; + + // + // Scalar and point structs + // + + /// This struct represents a scalar as a little-endian byte encoding of an integer in $\mathbb{Z}_\ell$, which is + /// stored in `data`. Here, \ell denotes the order of the scalar field (and the underlying elliptic curve group). + struct Scalar has copy, store, drop { + data: vector + } + + /// This struct represents a serialized point on the Ristretto255 curve, in 32 bytes. + /// This struct can be decompressed from storage into an in-memory RistrettoPoint, on which fast curve arithmetic + /// can be performed. + struct CompressedRistretto has copy, store, drop { + data: vector + } + + /// This struct represents an in-memory Ristretto255 point and supports fast curve arithmetic. + /// + /// An important invariant: There will never be two RistrettoPoint's constructed with the same handle. One can have + /// immutable references to the same RistrettoPoint, of course. + struct RistrettoPoint has drop { + handle: u64 + } + + // + // Functions for arithmetic on points + // + + /// Returns the identity point as a CompressedRistretto. + public fun point_identity_compressed(): CompressedRistretto { + CompressedRistretto { + data: x"0000000000000000000000000000000000000000000000000000000000000000" + } + } + + /// Returns the identity point as a CompressedRistretto. + public fun point_identity(): RistrettoPoint { + RistrettoPoint { + handle: point_identity_internal() + } + } + + /// Returns the basepoint (generator) of the Ristretto255 group as a compressed point + public fun basepoint_compressed(): CompressedRistretto { + CompressedRistretto { + data: BASE_POINT + } + } + + /// Returns the hash-to-point result of serializing the basepoint of the Ristretto255 group. + /// For use as the random value basepoint in Pedersen commitments + public fun hash_to_point_base(): RistrettoPoint { + let comp_res = CompressedRistretto { data: HASH_BASE_POINT }; + point_decompress(&comp_res) + } + + /// Returns the basepoint (generator) of the Ristretto255 group + public fun basepoint(): RistrettoPoint { + let (handle, _) = point_decompress_internal(BASE_POINT); + + RistrettoPoint { + handle + } + } + + /// Multiplies the basepoint (generator) of the Ristretto255 group by a scalar and returns the result. + /// This call is much faster than `point_mul(&basepoint(), &some_scalar)` because of precomputation tables. + public fun basepoint_mul(a: &Scalar): RistrettoPoint { + RistrettoPoint { + handle: basepoint_mul_internal(a.data) + } + } + + /// Creates a new CompressedRistretto point from a sequence of 32 bytes. If those bytes do not represent a valid + /// point, returns None. + public fun new_compressed_point_from_bytes(bytes: vector): Option { + if (point_is_canonical_internal(bytes)) { + std::option::some(CompressedRistretto { + data: bytes + }) + } else { + std::option::none() + } + } + + /// Creates a new RistrettoPoint from a sequence of 32 bytes. If those bytes do not represent a valid point, + /// returns None. + public fun new_point_from_bytes(bytes: vector): Option { + let (handle, is_canonical) = point_decompress_internal(bytes); + if (is_canonical) { + std::option::some(RistrettoPoint { handle }) + } else { + std::option::none() + } + } + + /// Given a compressed ristretto point `point`, returns the byte representation of that point + public fun compressed_point_to_bytes(point: CompressedRistretto): vector { + point.data + } + + /// DEPRECATED: Use the more clearly-named `new_point_from_sha2_512` + /// + /// Hashes the input to a uniformly-at-random RistrettoPoint via SHA512. + public fun new_point_from_sha512(sha2_512_input: vector): RistrettoPoint { + new_point_from_sha2_512(sha2_512_input) + } + + /// Hashes the input to a uniformly-at-random RistrettoPoint via SHA2-512. + public fun new_point_from_sha2_512(sha2_512_input: vector): RistrettoPoint { + RistrettoPoint { + handle: new_point_from_sha512_internal(sha2_512_input) + } + } + + /// Samples a uniformly-at-random RistrettoPoint given a sequence of 64 uniformly-at-random bytes. This function + /// can be used to build a collision-resistant hash function that maps 64-byte messages to RistrettoPoint's. + public fun new_point_from_64_uniform_bytes(bytes: vector): Option { + if (std::vector::length(&bytes) == 64) { + std::option::some(RistrettoPoint { + handle: new_point_from_64_uniform_bytes_internal(bytes) + }) + } else { + std::option::none() + } + } + + /// Decompresses a CompressedRistretto from storage into a RistrettoPoint which can be used for fast arithmetic. + public fun point_decompress(point: &CompressedRistretto): RistrettoPoint { + // NOTE: Our CompressedRistretto invariant assures us that every CompressedRistretto in storage is a valid + // RistrettoPoint + let (handle, _) = point_decompress_internal(point.data); + RistrettoPoint { handle } + } + + /// Clones a RistrettoPoint. + public fun point_clone(point: &RistrettoPoint): RistrettoPoint { + if(!features::bulletproofs_enabled()) { + abort(std::error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + RistrettoPoint { + handle: point_clone_internal(point.handle) + } + } + + /// Compresses a RistrettoPoint to a CompressedRistretto which can be put in storage. + public fun point_compress(point: &RistrettoPoint): CompressedRistretto { + CompressedRistretto { + data: point_compress_internal(point) + } + } + + /// Returns the sequence of bytes representin this Ristretto point. + /// To convert a RistrettoPoint 'p' to bytes, first compress it via `c = point_compress(&p)`, and then call this + /// function on `c`. + public fun point_to_bytes(point: &CompressedRistretto): vector { + point.data + } + + /// Returns a * point. + public fun point_mul(point: &RistrettoPoint, a: &Scalar): RistrettoPoint { + RistrettoPoint { + handle: point_mul_internal(point, a.data, false) + } + } + + /// Sets a *= point and returns 'a'. + public fun point_mul_assign(point: &mut RistrettoPoint, a: &Scalar): &mut RistrettoPoint { + point_mul_internal(point, a.data, true); + point + } + + /// Returns (a * a_base + b * base_point), where base_point is the Ristretto basepoint encoded in `BASE_POINT`. + public fun basepoint_double_mul(a: &Scalar, a_base: &RistrettoPoint, b: &Scalar): RistrettoPoint { + RistrettoPoint { + handle: basepoint_double_mul_internal(a.data, a_base, b.data) + } + } + + /// Returns a + b + public fun point_add(a: &RistrettoPoint, b: &RistrettoPoint): RistrettoPoint { + RistrettoPoint { + handle: point_add_internal(a, b, false) + } + } + + /// Sets a += b and returns 'a'. + public fun point_add_assign(a: &mut RistrettoPoint, b: &RistrettoPoint): &mut RistrettoPoint { + point_add_internal(a, b, true); + a + } + + /// Returns a - b + public fun point_sub(a: &RistrettoPoint, b: &RistrettoPoint): RistrettoPoint { + RistrettoPoint { + handle: point_sub_internal(a, b, false) + } + } + + /// Sets a -= b and returns 'a'. + public fun point_sub_assign(a: &mut RistrettoPoint, b: &RistrettoPoint): &mut RistrettoPoint { + point_sub_internal(a, b, true); + a + } + + /// Returns -a + public fun point_neg(a: &RistrettoPoint): RistrettoPoint { + RistrettoPoint { + handle: point_neg_internal(a, false) + } + } + + /// Sets a = -a, and returns 'a'. + public fun point_neg_assign(a: &mut RistrettoPoint): &mut RistrettoPoint { + point_neg_internal(a, true); + a + } + + /// Returns true if the two RistrettoPoints are the same points on the elliptic curve. + native public fun point_equals(g: &RistrettoPoint, h: &RistrettoPoint): bool; + + /// Computes a double-scalar multiplication, returning a_1 p_1 + a_2 p_2 + /// This function is much faster than computing each a_i p_i using `point_mul` and adding up the results using `point_add`. + public fun double_scalar_mul(scalar1: &Scalar, point1: &RistrettoPoint, scalar2: &Scalar, point2: &RistrettoPoint): RistrettoPoint { + if(!features::bulletproofs_enabled()) { + abort(std::error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + RistrettoPoint { + handle: double_scalar_mul_internal(point1.handle, point2.handle, scalar1.data, scalar2.data) + } + } + + /// Computes a multi-scalar multiplication, returning a_1 p_1 + a_2 p_2 + ... + a_n p_n. + /// This function is much faster than computing each a_i p_i using `point_mul` and adding up the results using `point_add`. + public fun multi_scalar_mul(points: &vector, scalars: &vector): RistrettoPoint { + assert!(!std::vector::is_empty(points), std::error::invalid_argument(E_ZERO_POINTS)); + assert!(!std::vector::is_empty(scalars), std::error::invalid_argument(E_ZERO_SCALARS)); + assert!(std::vector::length(points) == std::vector::length(scalars), std::error::invalid_argument(E_DIFFERENT_NUM_POINTS_AND_SCALARS)); + + RistrettoPoint { + handle: multi_scalar_mul_internal(points, scalars) + } + } + + // + // Functions for arithmetic on Scalars + // + + /// Given a sequence of 32 bytes, checks if they canonically-encode a Scalar and return it. + /// Otherwise, returns None. + public fun new_scalar_from_bytes(bytes: vector): Option { + if (scalar_is_canonical_internal(bytes)) { + std::option::some(Scalar { + data: bytes + }) + } else { + std::option::none() + } + } + + /// DEPRECATED: Use the more clearly-named `new_scalar_from_sha2_512` + /// + /// Hashes the input to a uniformly-at-random Scalar via SHA2-512 + public fun new_scalar_from_sha512(sha2_512_input: vector): Scalar { + new_scalar_from_sha2_512(sha2_512_input) + } + + /// Hashes the input to a uniformly-at-random Scalar via SHA2-512 + public fun new_scalar_from_sha2_512(sha2_512_input: vector): Scalar { + Scalar { + data: scalar_from_sha512_internal(sha2_512_input) + } + } + + /// Creates a Scalar from an u8. + public fun new_scalar_from_u8(byte: u8): Scalar { + let s = scalar_zero(); + let byte_zero = std::vector::borrow_mut(&mut s.data, 0); + *byte_zero = byte; + + s + } + + /// Creates a Scalar from an u32. + public fun new_scalar_from_u32(four_bytes: u32): Scalar { + Scalar { + data: scalar_from_u64_internal((four_bytes as u64)) + } + } + + /// Creates a Scalar from an u64. + public fun new_scalar_from_u64(eight_bytes: u64): Scalar { + Scalar { + data: scalar_from_u64_internal(eight_bytes) + } + } + + /// Creates a Scalar from an u128. + public fun new_scalar_from_u128(sixteen_bytes: u128): Scalar { + Scalar { + data: scalar_from_u128_internal(sixteen_bytes) + } + } + + /// Creates a Scalar from 32 bytes by reducing the little-endian-encoded number in those bytes modulo $\ell$. + public fun new_scalar_reduced_from_32_bytes(bytes: vector): Option { + if (std::vector::length(&bytes) == 32) { + std::option::some(Scalar { + data: scalar_reduced_from_32_bytes_internal(bytes) + }) + } else { + std::option::none() + } + } + + /// Samples a scalar uniformly-at-random given 64 uniform-at-random bytes as input by reducing the little-endian-encoded number + /// in those bytes modulo $\ell$. + public fun new_scalar_uniform_from_64_bytes(bytes: vector): Option { + if (std::vector::length(&bytes) == 64) { + std::option::some(Scalar { + data: scalar_uniform_from_64_bytes_internal(bytes) + }) + } else { + std::option::none() + } + } + + /// Returns 0 as a Scalar. + public fun scalar_zero(): Scalar { + Scalar { + data: x"0000000000000000000000000000000000000000000000000000000000000000" + } + } + + /// Returns true if the given Scalar equals 0. + public fun scalar_is_zero(s: &Scalar): bool { + s.data == x"0000000000000000000000000000000000000000000000000000000000000000" + } + + /// Returns 1 as a Scalar. + public fun scalar_one(): Scalar { + Scalar { + data: x"0100000000000000000000000000000000000000000000000000000000000000" + } + } + + /// Returns true if the given Scalar equals 1. + public fun scalar_is_one(s: &Scalar): bool { + s.data == x"0100000000000000000000000000000000000000000000000000000000000000" + } + + /// Returns true if the two scalars are equal. + public fun scalar_equals(lhs: &Scalar, rhs: &Scalar): bool { + lhs.data == rhs.data + } + + /// Returns the inverse s^{-1} mod \ell of a scalar s. + /// Returns None if s is zero. + public fun scalar_invert(s: &Scalar): Option { + if (scalar_is_zero(s)) { + std::option::none() + } else { + std::option::some(Scalar { + data: scalar_invert_internal(s.data) + }) + } + } + + /// Returns the product of the two scalars. + public fun scalar_mul(a: &Scalar, b: &Scalar): Scalar { + Scalar { + data: scalar_mul_internal(a.data, b.data) + } + } + + /// Computes the product of 'a' and 'b' and assigns the result to 'a'. + /// Returns 'a'. + public fun scalar_mul_assign(a: &mut Scalar, b: &Scalar): &mut Scalar { + a.data = scalar_mul(a, b).data; + a + } + + /// Returns the sum of the two scalars. + public fun scalar_add(a: &Scalar, b: &Scalar): Scalar { + Scalar { + data: scalar_add_internal(a.data, b.data) + } + } + + /// Computes the sum of 'a' and 'b' and assigns the result to 'a' + /// Returns 'a'. + public fun scalar_add_assign(a: &mut Scalar, b: &Scalar): &mut Scalar { + a.data = scalar_add(a, b).data; + a + } + + /// Returns the difference of the two scalars. + public fun scalar_sub(a: &Scalar, b: &Scalar): Scalar { + Scalar { + data: scalar_sub_internal(a.data, b.data) + } + } + + /// Subtracts 'b' from 'a' and assigns the result to 'a'. + /// Returns 'a'. + public fun scalar_sub_assign(a: &mut Scalar, b: &Scalar): &mut Scalar { + a.data = scalar_sub(a, b).data; + a + } + + /// Returns the negation of 'a': i.e., $(0 - a) \mod \ell$. + public fun scalar_neg(a: &Scalar): Scalar { + Scalar { + data: scalar_neg_internal(a.data) + } + } + + /// Replaces 'a' by its negation. + /// Returns 'a'. + public fun scalar_neg_assign(a: &mut Scalar): &mut Scalar { + a.data = scalar_neg(a).data; + a + } + + /// Returns the byte-representation of the scalar. + public fun scalar_to_bytes(s: &Scalar): vector { + s.data + } + + // + // Only used internally for implementing CompressedRistretto and RistrettoPoint + // + + // NOTE: This was supposed to be more clearly named with *_sha2_512_*. + native fun new_point_from_sha512_internal(sha2_512_input: vector): u64; + + native fun new_point_from_64_uniform_bytes_internal(bytes: vector): u64; + + native fun point_is_canonical_internal(bytes: vector): bool; + + native fun point_identity_internal(): u64; + + native fun point_decompress_internal(maybe_non_canonical_bytes: vector): (u64, bool); + + native fun point_clone_internal(point_handle: u64): u64; + native fun point_compress_internal(point: &RistrettoPoint): vector; + + native fun point_mul_internal(point: &RistrettoPoint, a: vector, in_place: bool): u64; + + native fun basepoint_mul_internal(a: vector): u64; + + native fun basepoint_double_mul_internal(a: vector, some_point: &RistrettoPoint, b: vector): u64; + + native fun point_add_internal(a: &RistrettoPoint, b: &RistrettoPoint, in_place: bool): u64; + + native fun point_sub_internal(a: &RistrettoPoint, b: &RistrettoPoint, in_place: bool): u64; + + native fun point_neg_internal(a: &RistrettoPoint, in_place: bool): u64; + + native fun double_scalar_mul_internal(point1: u64, point2: u64, scalar1: vector, scalar2: vector): u64; + + /// The generic arguments are needed to deal with some Move VM peculiarities which prevent us from borrowing the + /// points (or scalars) inside a &vector in Rust. + /// + /// WARNING: This function can only be called with P = RistrettoPoint and S = Scalar. + native fun multi_scalar_mul_internal(points: &vector

, scalars: &vector): u64; + + // + // Only used internally for implementing Scalar. + // + + native fun scalar_is_canonical_internal(s: vector): bool; + + native fun scalar_from_u64_internal(num: u64): vector; + + native fun scalar_from_u128_internal(num: u128): vector; + + native fun scalar_reduced_from_32_bytes_internal(bytes: vector): vector; + + native fun scalar_uniform_from_64_bytes_internal(bytes: vector): vector; + + native fun scalar_invert_internal(bytes: vector): vector; + + // NOTE: This was supposed to be more clearly named with *_sha2_512_*. + native fun scalar_from_sha512_internal(sha2_512_input: vector): vector; + + native fun scalar_mul_internal(a_bytes: vector, b_bytes: vector): vector; + + native fun scalar_add_internal(a_bytes: vector, b_bytes: vector): vector; + + native fun scalar_sub_internal(a_bytes: vector, b_bytes: vector): vector; + + native fun scalar_neg_internal(a_bytes: vector): vector; + + #[test_only] + native fun random_scalar_internal(): vector; + + // + // Test-only functions + // + + #[test_only] + public fun random_scalar(): Scalar { + Scalar { + data: random_scalar_internal() + } + } + + #[test_only] + public fun random_point(): RistrettoPoint { + let s = random_scalar(); + + basepoint_mul(&s) + } + + // + // Testing constants + // + + // The scalar 2 + #[test_only] + const TWO_SCALAR: vector = x"0200000000000000000000000000000000000000000000000000000000000000"; + + // Non-canonical scalar: the order \ell of the group + 1 + #[test_only] + const L_PLUS_ONE: vector = x"eed3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010"; + + // Non-canonical scalar: the order \ell of the group + 2 + #[test_only] + const L_PLUS_TWO: vector = x"efd3f55c1a631258d69cf7a2def9de1400000000000000000000000000000010"; + + // Some random scalar denoted by X + #[test_only] + const X_SCALAR: vector = x"4e5ab4345d4708845913b4641bc27d5252a585101bcc4244d449f4a879d9f204"; + + // X^{-1} = 1/X = 6859937278830797291664592131120606308688036382723378951768035303146619657244 + // 0x1CDC17FCE0E9A5BBD9247E56BB016347BBBA31EDD5A9BB96D50BCD7A3F962A0F + #[test_only] + const X_INV_SCALAR: vector = x"1cdc17fce0e9a5bbd9247e56bb016347bbba31edd5a9bb96d50bcd7a3f962a0f"; + + // Some random scalar Y = 2592331292931086675770238855846338635550719849568364935475441891787804997264 + #[test_only] + const Y_SCALAR: vector = x"907633fe1c4b66a4a28d2dd7678386c353d0de5455d4fc9de8ef7ac31f35bb05"; + + // X * Y = 5690045403673944803228348699031245560686958845067437804563560795922180092780 + #[test_only] + const X_TIMES_Y_SCALAR: vector = x"6c3374a1894f62210aaa2fe186a6f92ce0aa75c2779581c295fc08179a73940c"; + + // X + 2^256 * X \mod \ell + #[test_only] + const REDUCED_X_PLUS_2_TO_256_TIMES_X_SCALAR: vector = x"d89ab38bd279024745639ed817ad3f64cc005b32db9939f91c521fc564a5c008"; + + // sage: l = 2^252 + 27742317777372353535851937790883648493 + // sage: big = 2^256 - 1 + // sage: repr((big % l).digits(256)) + #[test_only] + const REDUCED_2_256_MINUS_1_SCALAR: vector = x"1c95988d7431ecd670cf7d73f45befc6feffffffffffffffffffffffffffff0f"; + + #[test_only] + const NON_CANONICAL_ALL_ONES: vector = x"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF"; + + #[test_only] + const A_SCALAR: vector = x"1a0e978a90f6622d3747023f8ad8264da758aa1b88e040d1589e7b7f2376ef09"; + + // Generated in curve25519-dalek via: + // ``` + // let mut hasher = sha2::Sha512::default(); + // hasher.update(b"bello!"); + // let s = Scalar::from_hash(hasher); + // println!("scalar: {:x?}", s.to_bytes()); + // ``` + #[test_only] + const B_SCALAR: vector = x"dbfd97afd38a06f0138d0527efb28ead5b7109b486465913bf3aa472a8ed4e0d"; + + #[test_only] + const A_TIMES_B_SCALAR: vector = x"2ab50e383d7c210f74d5387330735f18315112d10dfb98fcce1e2620c0c01402"; + + #[test_only] + const A_PLUS_B_SCALAR: vector = x"083839dd491e57c5743710c39a91d6e502cab3cf0e279ae417d91ff2cb633e07"; + + #[test_only] + /// A_SCALAR * BASE_POINT, computed by modifying a test in curve25519-dalek in src/edwards.rs to do: + /// ``` + /// let comp = RistrettoPoint(A_TIMES_BASEPOINT.decompress().unwrap()).compress(); + /// println!("hex: {:x?}", comp.to_bytes()); + /// ``` + const A_TIMES_BASE_POINT: vector = x"96d52d9262ee1e1aae79fbaee8c1d9068b0d01bf9a4579e618090c3d1088ae10"; + + #[test_only] + const A_POINT: vector = x"e87feda199d72b83de4f5b2d45d34805c57019c6c59c42cb70ee3d19aa996f75"; + #[test_only] + const B_POINT: vector = x"fa0b3624b081c62f364d0b2839dcc76d7c3ab0e27e31beb2b9ed766575f28e76"; + #[test_only] + const A_PLUS_B_POINT: vector = x"70cf3753475b9ff33e2f84413ed6b5052073bccc0a0a81789d3e5675dc258056"; + + // const NON_CANONICAL_LARGEST_ED25519_S: vector = x"f8ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f"; + // const CANONICAL_LARGEST_ED25519_S_PLUS_ONE: vector = x"7e344775474a7f9723b63a8be92ae76dffffffffffffffffffffffffffffff0f"; + // const CANONICAL_LARGEST_ED25519_S_MINUS_ONE: vector = x"7c344775474a7f9723b63a8be92ae76dffffffffffffffffffffffffffffff0f"; + + // + // Tests + // + + #[test] + fun test_point_decompression() { + let compressed = new_compressed_point_from_bytes(A_POINT); + assert!(std::option::is_some(&compressed), 1); + + let point = new_point_from_bytes(A_POINT); + assert!(std::option::is_some(&point), 1); + + let point = std::option::extract(&mut point); + let compressed = std::option::extract(&mut compressed); + let same_point = point_decompress(&compressed); + + assert!(point_equals(&point, &same_point), 1); + } + + #[test] + fun test_point_equals() { + let g = basepoint(); + let same_g = std::option::extract(&mut new_point_from_bytes(BASE_POINT)); + let ag = std::option::extract(&mut new_point_from_bytes(A_TIMES_BASE_POINT)); + + assert!(point_equals(&g, &same_g), 1); + assert!(!point_equals(&g, &ag), 1); + } + + #[test] + fun test_point_mul() { + // fetch g + let g = basepoint(); + // fetch a + let a = std::option::extract(&mut new_scalar_from_bytes(A_SCALAR)); + // fetch expected a*g + let ag = std::option::extract(&mut new_point_from_bytes(A_TIMES_BASE_POINT)); + + // compute a*g + let p = point_mul(&g, &a); + + // sanity-check the handles + assert!(g.handle == 0, 1); + assert!(ag.handle == 1, 1); + assert!(p.handle == 2, 1); + + assert!(!point_equals(&g, &ag), 1); // make sure input g remains unmodifed + assert!(point_equals(&p, &ag), 1); // make sure output a*g is correct + } + + #[test] + fun test_point_mul_assign() { + let g = basepoint(); + assert!(g.handle == 0, 1); + + let a = std::option::extract(&mut new_scalar_from_bytes(A_SCALAR)); + + let ag = std::option::extract(&mut new_point_from_bytes(A_TIMES_BASE_POINT)); + assert!(ag.handle == 1, 1); + assert!(!point_equals(&g, &ag), 1); + + { + // NOTE: new_g is just a mutable reference to g + let upd_g = point_mul_assign(&mut g, &a); + + // in a mul_assign the returned &mut RistrettoPoint reference should have the same handle as 'g' + assert!(upd_g.handle == 0, 1); + + assert!(point_equals(upd_g, &ag), 1); + }; + + assert!(point_equals(&g, &ag), 1); + } + + #[test] + fun test_point_add() { + // fetch a + let a = std::option::extract(&mut new_point_from_bytes(A_POINT)); + + // fetch b + let b = std::option::extract(&mut new_point_from_bytes(B_POINT)); + + // fetch expected a + b + let a_plus_b = std::option::extract(&mut new_point_from_bytes(A_PLUS_B_POINT)); + + // compute a*g + let result = point_add(&a, &b); + + assert!(!point_equals(&a, &b), 1); + + // sanity-check the handles + assert!(a.handle == 0, 1); + assert!(b.handle == 1, 1); + assert!(a_plus_b.handle == 2, 1); + assert!(result.handle == 3, 1); + + assert!(!point_equals(&a, &result), 1); // make sure input a remains unmodifed + assert!(!point_equals(&b, &result), 1); // make sure input b remains unmodifed + assert!(point_equals(&a_plus_b, &result), 1); // make sure output a+b is correct + } + + #[test] + fun test_point_add_assign_0_0() { + test_point_add_assign_internal(0, 0); + } + + #[test] + fun test_point_add_assign_1_0() { + test_point_add_assign_internal(1, 0); + } + + #[test] + fun test_point_add_assign_0_1() { + test_point_add_assign_internal(0, 1); + } + + #[test] + fun test_point_add_assign_3_7() { + test_point_add_assign_internal(3, 7); + } + + #[test_only] + fun test_point_add_assign_internal(before_a_gap: u64, before_b_gap: u64) { + // create extra RistrettoPoints here, so as to generate different PointStore layouts inside the native Rust implementation + let c = before_a_gap; + while (c > 0) { + let _ignore = std::option::extract(&mut new_point_from_bytes(BASE_POINT)); + + c = c - 1; + }; + + // fetch a + let a = std::option::extract(&mut new_point_from_bytes(A_POINT)); + + // create extra RistrettoPoints here, so as to generate different PointStore layouts inside the native Rust implementation + let c = before_b_gap; + while (c > 0) { + let _ignore = std::option::extract(&mut new_point_from_bytes(BASE_POINT)); + + c = c - 1; + }; + // fetch b + let b = std::option::extract(&mut new_point_from_bytes(B_POINT)); + + let a_plus_b = std::option::extract(&mut new_point_from_bytes(A_PLUS_B_POINT)); + + // sanity-check the handles + assert!(a.handle == before_a_gap, 1); + assert!(b.handle == 1 + before_a_gap + before_b_gap, 1); + assert!(a_plus_b.handle == 2 + before_a_gap + before_b_gap, 1); + + assert!(!point_equals(&a, &b), 1); + assert!(!point_equals(&a, &a_plus_b), 1); + + { + // NOTE: new_h is just a mutable reference to g + let upd_a = point_add_assign(&mut a, &b); + + // in a add_assign the returned &mut RistrettoPoint reference should have the same handle as 'a' + assert!(upd_a.handle == before_a_gap, 1); + + assert!(point_equals(upd_a, &a_plus_b), 1); + }; + + assert!(point_equals(&a, &a_plus_b), 1); + } + + #[test] + fun test_point_sub() { + // fetch a + let a = std::option::extract(&mut new_point_from_bytes(A_POINT)); + + // fetch b + let b = std::option::extract(&mut new_point_from_bytes(B_POINT)); + + // fetch expected a + b + let a_plus_b = std::option::extract(&mut new_point_from_bytes(A_PLUS_B_POINT)); + + // compute a*g + let result = point_sub(&a_plus_b, &b); + + assert!(!point_equals(&a, &b), 1); + + // sanity-check the handles + assert!(a.handle == 0, 1); + assert!(b.handle == 1, 1); + assert!(a_plus_b.handle == 2, 1); + assert!(result.handle == 3, 1); + + assert!(!point_equals(&a_plus_b, &result), 1); // make sure input a_plus_b remains unmodifed + assert!(!point_equals(&b, &result), 1); // make sure input b remains unmodifed + assert!(point_equals(&a, &result), 1); // make sure output 'a+b-b' is correct + } + + #[test] + fun test_point_neg() { + let a = std::option::extract(&mut new_point_from_bytes(A_POINT)); + + let neg_a = point_neg(&a); + + assert!(a.handle != neg_a.handle, 1); + assert!(!point_equals(&a, &neg_a), 1); + assert!(!point_equals(&point_add(&point_identity(), &a), &neg_a), 1); + assert!(point_equals(&point_add(&a, &neg_a), &point_identity()), 1); + + let handle = a.handle; + let neg_a_ref = point_neg_assign(&mut a); + assert!(handle == neg_a_ref.handle, 1); + assert!(point_equals(neg_a_ref, &neg_a), 1); + } + + #[test] + fun test_basepoint_mul() { + let a = Scalar { data: A_SCALAR }; + let basepoint = basepoint(); + let expected = point_mul(&basepoint, &a); + assert!(point_equals(&expected, &basepoint_mul(&a)), 1); + } + + #[test(fx = @std)] + fun test_basepoint_double_mul(fx: signer) { + features::change_feature_flags_for_testing(&fx, vector[ features::get_bulletproofs_feature() ], vector[]); + + let expected = option::extract(&mut new_point_from_bytes(x"be5d615d8b8f996723cdc6e1895b8b6d312cc75d1ffb0259873b99396a38c05a")); + + let a = Scalar { data: A_SCALAR }; + let a_point = option::extract(&mut new_point_from_bytes(A_POINT)); + let b = Scalar { data: B_SCALAR }; + let actual = basepoint_double_mul(&a, &a_point, &b); + + assert!(point_equals(&expected, &actual), 1); + + let expected = double_scalar_mul(&a, &a_point, &b, &basepoint()); + assert!(point_equals(&expected, &actual), 1); + } + + #[test] + #[expected_failure] + fun test_multi_scalar_mul_aborts_empty_scalars() { + multi_scalar_mul(&vector[ basepoint() ], &vector[]); + } + + #[test] + #[expected_failure] + fun test_multi_scalar_mul_aborts_empty_points() { + multi_scalar_mul(&vector[ ], &vector[ Scalar { data: A_SCALAR } ]); + } + + #[test] + #[expected_failure] + fun test_multi_scalar_mul_aborts_empty_all() { + multi_scalar_mul(&vector[ ], &vector[ ]); + } + + #[test] + #[expected_failure] + fun test_multi_scalar_mul_aborts_different_sizes() { + multi_scalar_mul(&vector[ basepoint() ], &vector[ Scalar { data: A_SCALAR }, Scalar { data: B_SCALAR } ]); + } + + #[test] + fun test_multi_scalar_mul_single() { + // Test single exp + let points = vector[ + basepoint(), + ]; + + let scalars = vector[ + Scalar { data: A_SCALAR }, + ]; + + let result = multi_scalar_mul(&points, &scalars); + let expected = std::option::extract(&mut new_point_from_bytes(A_TIMES_BASE_POINT)); + + assert!(point_equals(&result, &expected), 1); + } + + #[test] + fun test_multi_scalar_mul_double() { + // Test double exp + let points = vector[ + basepoint(), + basepoint(), + ]; + + let scalars = vector[ + Scalar { data: A_SCALAR }, + Scalar { data: B_SCALAR }, + ]; + + let result = multi_scalar_mul(&points, &scalars); + let expected = basepoint_double_mul( + std::vector::borrow(&scalars, 0), + &basepoint(), + std::vector::borrow(&scalars, 1)); + + assert!(point_equals(&result, &expected), 1); + } + + #[test] + fun test_multi_scalar_mul_many() { + let scalars = vector[ + new_scalar_from_sha2_512(b"1"), + new_scalar_from_sha2_512(b"2"), + new_scalar_from_sha2_512(b"3"), + new_scalar_from_sha2_512(b"4"), + new_scalar_from_sha2_512(b"5"), + ]; + + let points = vector[ + new_point_from_sha2_512(b"1"), + new_point_from_sha2_512(b"2"), + new_point_from_sha2_512(b"3"), + new_point_from_sha2_512(b"4"), + new_point_from_sha2_512(b"5"), + ]; + + let expected = std::option::extract(&mut new_point_from_bytes(x"c4a98fbe6bd0f315a0c150858aec8508be397443093e955ef982e299c1318928")); + let result = multi_scalar_mul(&points, &scalars); + + assert!(point_equals(&expected, &result), 1); + } + + #[test] + fun test_new_point_from_sha2_512() { + let msg = b"To really appreciate architecture, you may even need to commit a murder"; + let expected = option::extract(&mut new_point_from_bytes(x"baaa91eb43e5e2f12ffc96347e14bc458fdb1772b2232b08977ee61ea9f84e31")); + + assert!(point_equals(&expected, &new_point_from_sha2_512(msg)), 1); + } + + #[test] + fun test_new_point_from_64_uniform_bytes() { + let bytes_64 = x"baaa91eb43e5e2f12ffc96347e14bc458fdb1772b2232b08977ee61ea9f84e31e87feda199d72b83de4f5b2d45d34805c57019c6c59c42cb70ee3d19aa996f75"; + let expected = option::extract(&mut new_point_from_bytes(x"4a8e429f906478654232d7ae180ad60854754944ac67f38e20d8fa79e4b7d71e")); + + let point = option::extract(&mut new_point_from_64_uniform_bytes(bytes_64)); + assert!(point_equals(&expected, &point), 1); + } + + #[test] + fun test_scalar_basic_viability() { + // Test conversion from u8 + let two = Scalar { data: TWO_SCALAR }; + assert!(scalar_equals(&new_scalar_from_u8(2u8), &two), 1); + + // Test conversion from u64 + assert!(scalar_equals(&new_scalar_from_u64(2u64), &two), 1); + + // Test conversion from u128 + assert!(scalar_equals(&new_scalar_from_u128(2u128), &two), 1); + + // Test (0 - 1) % order = order - 1 + assert!(scalar_equals(&scalar_sub(&scalar_zero(), &scalar_one()), &Scalar { data: L_MINUS_ONE }), 1); + } + + #[test] + /// Tests deserializing a Scalar from a sequence of canonical bytes + fun test_scalar_from_canonical_bytes() { + // Too few bytes + assert!(std::option::is_none(&new_scalar_from_bytes(x"00")), 1); + + // 32 zero bytes are canonical + assert!(std::option::is_some(&new_scalar_from_bytes(x"0000000000000000000000000000000000000000000000000000000000000000")), 1); + + // Non-canonical because unreduced + assert!(std::option::is_none(&new_scalar_from_bytes(x"1010101010101010101010101010101010101010101010101010101010101010")), 1); + + // Canonical because \ell - 1 + assert!(std::option::is_some(&new_scalar_from_bytes(L_MINUS_ONE)), 1); + + // Non-canonical because \ell + assert!(std::option::is_none(&new_scalar_from_bytes(ORDER_ELL)), 1); + + // Non-canonical because \ell+1 + assert!(std::option::is_none(&new_scalar_from_bytes(L_PLUS_ONE)), 1); + + // Non-canonical because \ell+2 + assert!(std::option::is_none(&new_scalar_from_bytes(L_PLUS_TWO)), 1); + + // Non-canonical because high bit is set + let non_canonical_highbit = vector[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 128]; + let non_canonical_highbit_hex = x"0000000000000000000000000000000000000000000000000000000000000080"; + assert!(non_canonical_highbit == non_canonical_highbit_hex, 1); + assert!(std::option::is_none(&new_scalar_from_bytes(non_canonical_highbit)), 1); + } + + #[test] + fun test_scalar_zero() { + // 0 == 0 + assert!(scalar_is_zero(&scalar_zero()), 1); + assert!(scalar_is_zero(&new_scalar_from_u8(0u8)), 1); + + // 0 != 1 + assert!(scalar_is_zero(&scalar_one()) == false, 1); + + // Pick a random scalar by hashing from some "random" bytes + let s = new_scalar_from_sha2_512(x"deadbeef"); + + // Technically, there is a negligible probability (i.e., 1/2^\ell) that the hashed s is zero or one + assert!(scalar_is_zero(&s) == false, 1); + assert!(scalar_is_one(&s) == false, 1); + + // Multiply 0 with a random scalar and make sure you get zero + assert!(scalar_is_zero(&scalar_mul(&scalar_zero(), &s)), 1); + assert!(scalar_is_zero(&scalar_mul(&s, &scalar_zero())), 1); + } + + #[test] + fun test_scalar_one() { + // 1 == 1 + assert!(scalar_is_one(&scalar_one()), 1); + assert!(scalar_is_one(&new_scalar_from_u8(1u8)), 1); + + // 1 != 0 + assert!(scalar_is_one(&scalar_zero()) == false, 1); + + // Pick a random scalar by hashing from some "random" bytes + let s = new_scalar_from_sha2_512(x"deadbeef"); + let inv = scalar_invert(&s); + + // Technically, there is a negligible probability (i.e., 1/2^\ell) that s was zero and the call above returned None + assert!(std::option::is_some(&inv), 1); + + let inv = std::option::extract(&mut inv); + + // Multiply s with s^{-1} and make sure you get one + assert!(scalar_is_one(&scalar_mul(&s, &inv)), 1); + assert!(scalar_is_one(&scalar_mul(&inv, &s)), 1); + } + + #[test] + fun test_scalar_from_sha2_512() { + // Test a specific message hashes correctly to the field + let str: vector = vector[]; + std::vector::append(&mut str, b"To really appreciate architecture, you may even need to commit a murder."); + std::vector::append(&mut str, b"While the programs used for The Manhattan Transcripts are of the most extreme"); + std::vector::append(&mut str, b"nature, they also parallel the most common formula plot: the archetype of"); + std::vector::append(&mut str, b"murder. Other phantasms were occasionally used to underline the fact that"); + std::vector::append(&mut str, b"perhaps all architecture, rather than being about functional standards, is"); + std::vector::append(&mut str, b"about love and death."); + + let s = new_scalar_from_sha2_512(str); + + let expected: vector = vector[ + 21, 88, 208, 252, 63, 122, 210, 152, + 154, 38, 15, 23, 16, 167, 80, 150, + 192, 221, 77, 226, 62, 25, 224, 148, + 239, 48, 176, 10, 185, 69, 168, 11 + ]; + + assert!(s.data == expected, 1) + } + + #[test] + fun test_scalar_invert() { + // Cannot invert zero + assert!(std::option::is_none(&scalar_invert(&scalar_zero())), 1); + + // One's inverse is one + let one = scalar_invert(&scalar_one()); + assert!(std::option::is_some(&one), 1); + + let one = std::option::extract(&mut one); + assert!(scalar_is_one(&one), 1); + + // Test a random point X's inverse is correct + let x = Scalar { data: X_SCALAR }; + let xinv = scalar_invert(&x); + assert!(std::option::is_some(&xinv), 1); + + let xinv = std::option::extract(&mut xinv); + let xinv_expected = Scalar { data: X_INV_SCALAR }; + + assert!(scalar_equals(&xinv, &xinv_expected), 1) + } + + #[test] + fun test_scalar_neg() { + // -(-X) == X + let x = Scalar { data: X_SCALAR }; + + let x_neg = scalar_neg(&x); + let x_neg_neg = scalar_neg(&x_neg); + + assert!(scalar_equals(&x, &x_neg_neg), 1); + } + + #[test] + fun test_scalar_neg_assign() { + let x = Scalar { data: X_SCALAR }; + let x_copy = x; + + scalar_neg_assign(&mut x); + assert!(!scalar_equals(&x, &x_copy), 1); + scalar_neg_assign(&mut x); + assert!(scalar_equals(&x, &x_copy), 1); + + assert!(scalar_equals(scalar_neg_assign(scalar_neg_assign(&mut x)), &x_copy), 1); + } + + #[test] + fun test_scalar_mul() { + // X * 1 == X + let x = Scalar { data: X_SCALAR }; + assert!(scalar_equals(&x, &scalar_mul(&x, &scalar_one())), 1); + + // Test multiplication of two random scalars + let y = Scalar { data: Y_SCALAR }; + let x_times_y = Scalar { data: X_TIMES_Y_SCALAR }; + assert!(scalar_equals(&scalar_mul(&x, &y), &x_times_y), 1); + + // A * B + assert!(scalar_equals(&scalar_mul(&Scalar { data: A_SCALAR }, &Scalar { data: B_SCALAR }), &Scalar { data: A_TIMES_B_SCALAR }), 1); + } + + #[test] + fun test_scalar_mul_assign() { + let x = Scalar { data: X_SCALAR }; + let y = Scalar { data: Y_SCALAR }; + let x_times_y = Scalar { data: X_TIMES_Y_SCALAR }; + + scalar_mul_assign(&mut x, &y); + + assert!(scalar_equals(&x, &x_times_y), 1); + } + + #[test] + fun test_scalar_add() { + // Addition reduces: \ell-1 + 1 = \ell = 0 + let ell_minus_one = Scalar { data: L_MINUS_ONE }; + assert!(scalar_is_zero(&scalar_add(&ell_minus_one, &scalar_one())), 1); + + // 1 + 1 = 2 + let two = Scalar { data: TWO_SCALAR }; + assert!(scalar_equals(&scalar_add(&scalar_one(), &scalar_one()), &two), 1); + + // A + B + assert!(scalar_equals(&scalar_add(&Scalar { data: A_SCALAR }, &Scalar { data: B_SCALAR }), &Scalar { data: A_PLUS_B_SCALAR }), 1); + } + + #[test] + fun test_scalar_sub() { + // Subtraction reduces: 0 - 1 = \ell - 1 + let ell_minus_one = Scalar { data: L_MINUS_ONE }; + assert!(scalar_equals(&scalar_sub(&scalar_zero(), &scalar_one()), &ell_minus_one), 1); + + // 2 - 1 = 1 + let two = Scalar { data: TWO_SCALAR }; + assert!(scalar_is_one(&scalar_sub(&two, &scalar_one())), 1); + + // 1 - 2 = -1 = \ell - 1 + let ell_minus_one = Scalar { data: L_MINUS_ONE }; + assert!(scalar_equals(&scalar_sub(&scalar_one(), &two), &ell_minus_one), 1); + } + + #[test] + fun test_scalar_reduced_from_32_bytes() { + // \ell + 2 = 0 + 2 = 2 (modulo \ell) + let s = std::option::extract(&mut new_scalar_reduced_from_32_bytes(L_PLUS_TWO)); + let two = Scalar { data: TWO_SCALAR }; + assert!(scalar_equals(&s, &two), 1); + + // Reducing the all 1's bit vector yields $(2^256 - 1) \mod \ell$ + let biggest = std::option::extract(&mut new_scalar_reduced_from_32_bytes(NON_CANONICAL_ALL_ONES)); + assert!(scalar_equals(&biggest, &Scalar { data: REDUCED_2_256_MINUS_1_SCALAR }), 1); + } + + #[test] + fun test_scalar_from_64_uniform_bytes() { + // Test X + 2^256 * X reduces correctly + let x_plus_2_to_256_times_x: vector = vector[]; + + std::vector::append(&mut x_plus_2_to_256_times_x, X_SCALAR); + std::vector::append(&mut x_plus_2_to_256_times_x, X_SCALAR); + + let reduced = std::option::extract(&mut new_scalar_uniform_from_64_bytes(x_plus_2_to_256_times_x)); + let expected = Scalar { data: REDUCED_X_PLUS_2_TO_256_TIMES_X_SCALAR }; + assert!(scalar_equals(&reduced, &expected), 1) + } + + #[test] + fun test_scalar_to_bytes() { + // zero is canonical + assert!(scalar_is_canonical_internal(scalar_zero().data), 1); + + // ...but if we maul it and set the high bit to 1, it is non-canonical + let non_can = scalar_zero(); + let last_byte = std::vector::borrow_mut(&mut non_can.data, 31); + *last_byte = 128; + assert!(!scalar_is_canonical_internal(non_can.data), 1); + + // This test makes sure scalar_to_bytes does not return a mutable reference to a scalar's bits + let non_can = scalar_zero(); + let bytes = scalar_to_bytes(&scalar_zero()); + let last_byte = std::vector::borrow_mut(&mut bytes, 31); + *last_byte = 128; + assert!(scalar_is_canonical_internal(non_can.data), 1); + assert!(scalar_equals(&non_can, &scalar_zero()), 1); + } + + #[test] + fun test_num_points_within_limit() { + let limit = 10000; + let i = 0; + while (i < limit) { + point_identity(); + i = i + 1; + } + } + + #[test] + #[expected_failure(abort_code=0x090004, location=Self)] + fun test_num_points_limit_exceeded() { + let limit = 10001; + let i = 0; + while (i < limit) { + point_identity(); + i = i + 1; + } + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/ristretto255_bulletproofs.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/ristretto255_bulletproofs.move new file mode 100644 index 000000000..731ceabc7 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/ristretto255_bulletproofs.move @@ -0,0 +1,253 @@ +/// This module implements a Bulletproof range proof verifier on the Ristretto255 curve. +/// +/// A Bulletproof-based zero-knowledge range proof is a proof that a Pedersen commitment +/// $c = v G + r H$ commits to an $n$-bit value $v$ (i.e., $v \in [0, 2^n)$). Currently, this module only supports +/// $n \in \{8, 16, 32, 64\}$ for the number of bits. +module aptos_std::ristretto255_bulletproofs { + use std::error; + use std::features; + use aptos_std::ristretto255_pedersen as pedersen; + use aptos_std::ristretto255::{Self, RistrettoPoint}; + + // + // Constants + // + + /// The maximum range supported by the Bulletproofs library is $[0, 2^{64})$. + const MAX_RANGE_BITS : u64 = 64; + + // + // Error codes + // + + /// There was an error deserializing the range proof. + const E_DESERIALIZE_RANGE_PROOF: u64 = 1; + + /// The committed value given to the prover is too large. + const E_VALUE_OUTSIDE_RANGE: u64 = 2; + + /// The range proof system only supports proving ranges of type $[0, 2^b)$ where $b \in \{8, 16, 32, 64\}$. + const E_RANGE_NOT_SUPPORTED: u64 = 3; + + /// The native functions have not been rolled out yet. + const E_NATIVE_FUN_NOT_AVAILABLE: u64 = 4; + + // + // Structs + // + + /// Represents a zero-knowledge range proof that a value committed inside a Pedersen commitment lies in + /// `[0, 2^{MAX_RANGE_BITS})`. + struct RangeProof has copy, drop, store { + bytes: vector + } + + // + // Public functions + // + + /// Returns the maximum # of bits that the range proof system can verify proofs for. + public fun get_max_range_bits(): u64 { + MAX_RANGE_BITS + } + + /// Deserializes a range proof from a sequence of bytes. The serialization format is the same as the format in + /// the zkcrypto's `bulletproofs` library (https://docs.rs/bulletproofs/4.0.0/bulletproofs/struct.RangeProof.html#method.from_bytes). + public fun range_proof_from_bytes(bytes: vector): RangeProof { + RangeProof { + bytes + } + } + + /// Returns the byte-representation of a range proof. + public fun range_proof_to_bytes(proof: &RangeProof): vector { + proof.bytes + } + + /// Verifies a zero-knowledge range proof that the value `v` committed in `com` (under the default Bulletproofs + /// commitment key; see `pedersen::new_commitment_for_bulletproof`) satisfies $v \in [0, 2^b)$. Only works + /// for $b \in \{8, 16, 32, 64\}$. Additionally, checks that the prover used `dst` as the domain-separation + /// tag (DST). + /// + /// WARNING: The DST check is VERY important for security as it prevents proofs computed for one application + /// (a.k.a., a _domain_) with `dst_1` from verifying in a different application with `dst_2 != dst_1`. + public fun verify_range_proof_pedersen(com: &pedersen::Commitment, proof: &RangeProof, num_bits: u64, dst: vector): bool { + assert!(features::bulletproofs_enabled(), error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)); + + verify_range_proof_internal( + ristretto255::point_to_bytes(&pedersen::commitment_as_compressed_point(com)), + &ristretto255::basepoint(), &ristretto255::hash_to_point_base(), + proof.bytes, + num_bits, + dst + ) + } + + /// Verifies a zero-knowledge range proof that the value `v` committed in `com` (as v * val_base + r * rand_base, + /// for some randomness `r`) satisfies `v` in `[0, 2^num_bits)`. Only works for `num_bits` in `{8, 16, 32, 64}`. + public fun verify_range_proof( + com: &RistrettoPoint, + val_base: &RistrettoPoint, rand_base: &RistrettoPoint, + proof: &RangeProof, num_bits: u64, dst: vector): bool + { + assert!(features::bulletproofs_enabled(), error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)); + + verify_range_proof_internal( + ristretto255::point_to_bytes(&ristretto255::point_compress(com)), + val_base, rand_base, + proof.bytes, num_bits, dst + ) + } + + #[test_only] + /// Computes a range proof for the Pedersen commitment to 'val' with randomness 'r', under the default Bulletproofs + /// commitment key; see `pedersen::new_commitment_for_bulletproof`. Returns the said commitment too. + /// Only works for `num_bits` in `{8, 16, 32, 64}`. + public fun prove_range_pedersen(val: &Scalar, r: &Scalar, num_bits: u64, dst: vector): (RangeProof, pedersen::Commitment) { + let (bytes, compressed_comm) = prove_range_internal(scalar_to_bytes(val), scalar_to_bytes(r), num_bits, dst, &ristretto255::basepoint(), &ristretto255::hash_to_point_base()); + let point = ristretto255::new_compressed_point_from_bytes(compressed_comm); + let point = &std::option::extract(&mut point); + + ( + RangeProof { bytes }, + pedersen::commitment_from_compressed(point) + ) + } + + // + // Native functions + // + + /// Aborts with `error::invalid_argument(E_DESERIALIZE_RANGE_PROOF)` if `proof` is not a valid serialization of a + /// range proof. + /// Aborts with `error::invalid_argument(E_RANGE_NOT_SUPPORTED)` if an unsupported `num_bits` is provided. + native fun verify_range_proof_internal( + com: vector, + val_base: &RistrettoPoint, + rand_base: &RistrettoPoint, + proof: vector, + num_bits: u64, + dst: vector): bool; + + #[test_only] + /// Returns a tuple consisting of (1) a range proof for 'val' committed with randomness 'r' under the default Bulletproofs + /// commitment key and (2) the commitment itself. + /// + /// Aborts with `error::invalid_argument(E_RANGE_NOT_SUPPORTED)` if an unsupported `num_bits` is provided. + /// Aborts with `error::invalid_argument(E_VALUE_OUTSIDE_RANGE)` if an `val_base` is not `num_bits` wide. + native fun prove_range_internal( + val: vector, + r: vector, + num_bits: u64, + dst: vector, + val_base: &RistrettoPoint, + rand_base: &RistrettoPoint): (vector, vector); + + // + // Testing + // + + #[test_only] + use aptos_std::ristretto255::{Scalar, scalar_to_bytes, point_equals}; + + #[test_only] + const A_DST: vector = b"AptosBulletproofs"; + #[test_only] + const A_VALUE: vector = x"870c2fa1b2e9ac45000000000000000000000000000000000000000000000000"; // i.e., 5020644638028926087u64 + #[test_only] + const A_BLINDER: vector = x"e7c7b42b75503bfc7b1932783786d227ebf88f79da752b68f6b865a9c179640c"; + // Pedersen commitment to A_VALUE with randomness A_BLINDER + #[test_only] + const A_COMM: vector = x"0a665260a4e42e575882c2cdcb3d0febd6cf168834f6de1e9e61e7b2e53dbf14"; + // Range proof for A_COMM using domain-separation tag in A_DST, and MAX_RANGE_BITS + #[test_only] + const A_RANGE_PROOF_PEDERSEN: vector = x"d8d422d3fb9511d1942b78e3ec1a8c82fe1c01a0a690c55a4761e7e825633a753cca816667d2cbb716fe04a9c199cad748c2d4e59de4ed04fedf5f04f4341a74ae75b63c1997fd65d5fb3a8c03ad8771abe2c0a4f65d19496c11d948d6809503eac4d996f2c6be4e64ebe2df31102c96f106695bdf489dc9290c93b4d4b5411fb6298d0c33afa57e2e1948c38ef567268a661e7b1c099272e29591e717930a06a2c6e0e2d56aedea3078fd59334634f1a4543069865409eba074278f191039083102a9a0621791a9be09212a847e22061e083d7a712b05bca7274b25e4cb1201c679c4957f0842d7661fa1d3f5456a651e89112628b456026f8ad3a7abeaba3fec8031ec8b0392c0aa6c96205f7b21b0c2d6b5d064bd5bd1a1d91c41625d910688fa0dca35ec0f0e31a45792f8d6a330be970a22e1e0773111a083de893c89419ee7de97295978de90bcdf873a2826746809e64f9143417dbed09fa1c124e673febfed65c137cc45fabda963c96b64645802d1440cba5e58717e539f55f3321ab0c0f60410fba70070c5db500fee874265a343a2a59773fd150bcae09321a5166062e176e2e76bef0e3dd1a9250bcb7f4c971c10f0b24eb2a94e009b72c1fc21ee4267881e27b4edba8bed627ddf37e0c53cd425bc279d0c50d154d136503e54882e9541820d6394bd52ca2b438fd8c517f186fec0649c4846c4e43ce845d80e503dee157ce55392188039a7efc78719107ab989db8d9363b9dfc1946f01a84dbca5e742ed5f30b07ac61cf17ce2cf2c6a49d799ed3968a63a3ccb90d9a0e50960d959f17f202dd5cf0f2c375a8a702e063d339e48c0227e7cf710157f63f13136d8c3076c672ea2c1028fc1825366a145a4311de6c2cc46d3144ae3d2bc5808819b9817be3fce1664ecb60f74733e75e97ca8e567d1b81bdd4c56c7a340ba00"; + + #[test(fx = @std)] + #[expected_failure(abort_code = 0x010003, location = Self)] + fun test_unsupported_ranges(fx: signer) { + features::change_feature_flags_for_testing(&fx, vector[ features::get_bulletproofs_feature() ], vector[]); + + let comm = ristretto255::new_point_from_bytes(A_COMM); + let comm = std::option::extract(&mut comm); + let comm = pedersen::commitment_from_point(comm); + + assert!(verify_range_proof_pedersen( + &comm, + &range_proof_from_bytes(A_RANGE_PROOF_PEDERSEN), 10, A_DST), 1); + } + + #[test(fx = @std)] + fun test_prover(fx: signer) { + features::change_feature_flags_for_testing(&fx, vector[ features::get_bulletproofs_feature() ], vector[]); + + let v = ristretto255::new_scalar_from_u64(59); + let r = ristretto255::new_scalar_from_bytes(A_BLINDER); + let r = std::option::extract(&mut r); + let num_bits = 8; + + let (proof, comm) = prove_range_pedersen(&v, &r, num_bits, A_DST); + + assert!(verify_range_proof_pedersen(&comm, &proof, 64, A_DST) == false, 1); + assert!(verify_range_proof_pedersen(&comm, &proof, 32, A_DST) == false, 1); + assert!(verify_range_proof_pedersen(&comm, &proof, 16, A_DST) == false, 1); + assert!(verify_range_proof_pedersen(&comm, &proof, num_bits, A_DST), 1); + } + + #[test(fx = @std)] + #[expected_failure(abort_code = 0x010001, location = Self)] + fun test_empty_range_proof(fx: signer) { + features::change_feature_flags_for_testing(&fx, vector[ features::get_bulletproofs_feature() ], vector[]); + + let proof = &range_proof_from_bytes(vector[ ]); + let num_bits = 64; + let com = pedersen::new_commitment_for_bulletproof( + &ristretto255::scalar_one(), + &ristretto255::new_scalar_from_sha2_512(b"hello random world") + ); + + // This will fail with error::invalid_argument(E_DESERIALIZE_RANGE_PROOF) + verify_range_proof_pedersen(&com, proof, num_bits, A_DST); + } + + #[test(fx = @std)] + fun test_valid_range_proof_verifies_against_comm(fx: signer) { + features::change_feature_flags_for_testing(&fx, vector[ features::get_bulletproofs_feature() ], vector[]); + + let value = ristretto255::new_scalar_from_bytes(A_VALUE); + let value = std::option::extract(&mut value); + + let blinder = ristretto255::new_scalar_from_bytes(A_BLINDER); + let blinder = std::option::extract(&mut blinder); + + let comm = pedersen::new_commitment_for_bulletproof(&value, &blinder); + + let expected_comm = std::option::extract(&mut ristretto255::new_point_from_bytes(A_COMM)); + assert!(point_equals(pedersen::commitment_as_point(&comm), &expected_comm), 1); + + assert!(verify_range_proof_pedersen( + &comm, + &range_proof_from_bytes(A_RANGE_PROOF_PEDERSEN), MAX_RANGE_BITS, A_DST), 1); + } + + #[test(fx = @std)] + fun test_invalid_range_proof_fails_verification(fx: signer) { + features::change_feature_flags_for_testing(&fx, vector[ features::get_bulletproofs_feature() ], vector[]); + + let comm = ristretto255::new_point_from_bytes(A_COMM); + let comm = std::option::extract(&mut comm); + let comm = pedersen::commitment_from_point(comm); + + // Take a valid proof... + let range_proof_invalid = A_RANGE_PROOF_PEDERSEN; + + // ...and modify a byte in the middle of the proof + let pos = std::vector::length(&range_proof_invalid) / 2; + let byte = std::vector::borrow_mut(&mut range_proof_invalid, pos); + *byte = *byte + 1; + + assert!(verify_range_proof_pedersen( + &comm, + &range_proof_from_bytes(range_proof_invalid), MAX_RANGE_BITS, A_DST) == false, 1); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/ristretto255_elgamal.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/ristretto255_elgamal.move new file mode 100644 index 000000000..a6912e7b1 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/ristretto255_elgamal.move @@ -0,0 +1,234 @@ +/// This module implements an ElGamal encryption API, over the Ristretto255 curve, that can be used with the +/// Bulletproofs module. +/// +/// An ElGamal *ciphertext* is an encryption of a value `v` under a basepoint `G` and public key `Y = sk * G`, where `sk` +/// is the corresponding secret key, is `(v * G + r * Y, r * G)`, for a random scalar `r`. +/// +/// Note that we place the value `v` "in the exponent" of `G` so that ciphertexts are additively homomorphic: i.e., so +/// that `Enc_Y(v, r) + Enc_Y(v', r') = Enc_Y(v + v', r + r')` where `v, v'` are plaintext messages, `Y` is a public key and `r, r'` +/// are the randomness of the ciphertexts. + +module aptos_std::ristretto255_elgamal { + use aptos_std::ristretto255::{Self, RistrettoPoint, Scalar, CompressedRistretto, point_compress}; + use std::option::Option; + use std::vector; + + // + // Structs + // + + /// An ElGamal ciphertext. + struct Ciphertext has drop { + left: RistrettoPoint, // v * G + r * Y + right: RistrettoPoint, // r * G + } + + /// A compressed ElGamal ciphertext. + struct CompressedCiphertext has store, copy, drop { + left: CompressedRistretto, + right: CompressedRistretto, + } + + /// An ElGamal public key. + struct CompressedPubkey has store, copy, drop { + point: CompressedRistretto, + } + + // + // Public functions + // + + /// Creates a new public key from a serialized Ristretto255 point. + public fun new_pubkey_from_bytes(bytes: vector): Option { + let point = ristretto255::new_compressed_point_from_bytes(bytes); + if (std::option::is_some(&mut point)) { + let pk = CompressedPubkey { + point: std::option::extract(&mut point) + }; + std::option::some(pk) + } else { + std::option::none() + } + } + + /// Given an ElGamal public key `pubkey`, returns the byte representation of that public key. + public fun pubkey_to_bytes(pubkey: &CompressedPubkey): vector { + ristretto255::compressed_point_to_bytes(pubkey.point) + } + + /// Given a public key `pubkey`, returns the underlying `RistrettoPoint` representing that key. + public fun pubkey_to_point(pubkey: &CompressedPubkey): RistrettoPoint { + ristretto255::point_decompress(&pubkey.point) + } + + /// Given a public key, returns the underlying `CompressedRistretto` point representing that key. + public fun pubkey_to_compressed_point(pubkey: &CompressedPubkey): CompressedRistretto { + pubkey.point + } + + /// Creates a new ciphertext from two serialized Ristretto255 points: the first 32 bytes store `r * G` while the + /// next 32 bytes store `v * G + r * Y`, where `Y` is the public key. + public fun new_ciphertext_from_bytes(bytes: vector): Option { + if(vector::length(&bytes) != 64) { + return std::option::none() + }; + + let bytes_right = vector::trim(&mut bytes, 32); + + let left_point = ristretto255::new_point_from_bytes(bytes); + let right_point = ristretto255::new_point_from_bytes(bytes_right); + + if (std::option::is_some(&mut left_point) && std::option::is_some(&mut right_point)) { + std::option::some(Ciphertext { + left: std::option::extract(&mut left_point), + right: std::option::extract(&mut right_point) + }) + } else { + std::option::none() + } + } + + /// Creates a new ciphertext `(val * G + 0 * Y, 0 * G) = (val * G, 0 * G)` where `G` is the Ristretto255 basepoint + /// and the randomness is set to zero. + public fun new_ciphertext_no_randomness(val: &Scalar): Ciphertext { + Ciphertext { + left: ristretto255::basepoint_mul(val), + right: ristretto255::point_identity(), + } + } + + /// Moves a pair of Ristretto points into an ElGamal ciphertext. + public fun ciphertext_from_points(left: RistrettoPoint, right: RistrettoPoint): Ciphertext { + Ciphertext { + left, + right, + } + } + + /// Moves a pair of `CompressedRistretto` points into an ElGamal ciphertext. + public fun ciphertext_from_compressed_points(left: CompressedRistretto, right: CompressedRistretto): CompressedCiphertext { + CompressedCiphertext { + left, + right, + } + } + + /// Given a ciphertext `ct`, serializes that ciphertext into bytes. + public fun ciphertext_to_bytes(ct: &Ciphertext): vector { + let bytes_left = ristretto255::point_to_bytes(&ristretto255::point_compress(&ct.left)); + let bytes_right = ristretto255::point_to_bytes(&ristretto255::point_compress(&ct.right)); + let bytes = vector::empty(); + vector::append(&mut bytes, bytes_left); + vector::append(&mut bytes, bytes_right); + bytes + } + + /// Moves the ciphertext into a pair of `RistrettoPoint`'s. + public fun ciphertext_into_points(c: Ciphertext): (RistrettoPoint, RistrettoPoint) { + let Ciphertext { left, right } = c; + (left, right) + } + + /// Returns the pair of `RistrettoPoint`'s representing the ciphertext. + public fun ciphertext_as_points(c: &Ciphertext): (&RistrettoPoint, &RistrettoPoint) { + (&c.left, &c.right) + } + + /// Creates a new compressed ciphertext from a decompressed ciphertext. + public fun compress_ciphertext(ct: &Ciphertext): CompressedCiphertext { + CompressedCiphertext { + left: point_compress(&ct.left), + right: point_compress(&ct.right), + } + } + + /// Creates a new decompressed ciphertext from a compressed ciphertext. + public fun decompress_ciphertext(ct: &CompressedCiphertext): Ciphertext { + Ciphertext { + left: ristretto255::point_decompress(&ct.left), + right: ristretto255::point_decompress(&ct.right), + } + } + + /// Homomorphically combines two ciphertexts `lhs` and `rhs` as `lhs + rhs`. + /// Useful for re-randomizing the ciphertext or updating the committed value. + public fun ciphertext_add(lhs: &Ciphertext, rhs: &Ciphertext): Ciphertext { + Ciphertext { + left: ristretto255::point_add(&lhs.left, &rhs.left), + right: ristretto255::point_add(&lhs.right, &rhs.right), + } + } + + /// Like `ciphertext_add` but assigns `lhs = lhs + rhs`. + public fun ciphertext_add_assign(lhs: &mut Ciphertext, rhs: &Ciphertext) { + ristretto255::point_add_assign(&mut lhs.left, &rhs.left); + ristretto255::point_add_assign(&mut lhs.right, &rhs.right); + } + + /// Homomorphically combines two ciphertexts `lhs` and `rhs` as `lhs - rhs`. + /// Useful for re-randomizing the ciphertext or updating the committed value. + public fun ciphertext_sub(lhs: &Ciphertext, rhs: &Ciphertext): Ciphertext { + Ciphertext { + left: ristretto255::point_sub(&lhs.left, &rhs.left), + right: ristretto255::point_sub(&lhs.right, &rhs.right), + } + } + + /// Like `ciphertext_add` but assigns `lhs = lhs - rhs`. + public fun ciphertext_sub_assign(lhs: &mut Ciphertext, rhs: &Ciphertext) { + ristretto255::point_sub_assign(&mut lhs.left, &rhs.left); + ristretto255::point_sub_assign(&mut lhs.right, &rhs.right); + } + + /// Creates a copy of this ciphertext. + public fun ciphertext_clone(c: &Ciphertext): Ciphertext { + Ciphertext { + left: ristretto255::point_clone(&c.left), + right: ristretto255::point_clone(&c.right), + } + } + + /// Returns true if the two ciphertexts are identical: i.e., same value and same randomness. + public fun ciphertext_equals(lhs: &Ciphertext, rhs: &Ciphertext): bool { + ristretto255::point_equals(&lhs.left, &rhs.left) && + ristretto255::point_equals(&lhs.right, &rhs.right) + } + + /// Returns the `RistrettoPoint` in the ciphertext which contains the encrypted value in the exponent. + public fun get_value_component(ct: &Ciphertext): &RistrettoPoint { + &ct.left + } + + // + // Test-only functions + // + + #[test_only] + /// Given an ElGamal secret key `sk`, returns the corresponding ElGamal public key as `sk * G`. + public fun pubkey_from_secret_key(sk: &Scalar): CompressedPubkey { + let point = ristretto255::basepoint_mul(sk); + CompressedPubkey { + point: point_compress(&point) + } + } + + #[test_only] + /// Returns a ciphertext (v * point + r * pubkey, r * point) where `point` is *any* Ristretto255 point, + /// `pubkey` is the public key and `r` is the randomness. + public fun new_ciphertext(v: &Scalar, point: &RistrettoPoint, r: &Scalar, pubkey: &CompressedPubkey): Ciphertext { + Ciphertext { + left: ristretto255::double_scalar_mul(v, point, r, &pubkey_to_point(pubkey)), + right: ristretto255::point_mul(point, r), + } + } + + #[test_only] + /// Returns a ciphertext (v * basepoint + r * pubkey, r * basepoint) where `basepoint` is the Ristretto255 basepoint + /// `pubkey` is the public key and `r` is the randomness. + public fun new_ciphertext_with_basepoint(v: &Scalar, r: &Scalar, pubkey: &CompressedPubkey): Ciphertext { + Ciphertext { + left: ristretto255::basepoint_double_mul(r, &pubkey_to_point(pubkey), v), + right: ristretto255::basepoint_mul(r), + } + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/ristretto255_pedersen.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/ristretto255_pedersen.move new file mode 100644 index 000000000..7a49a0404 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/ristretto255_pedersen.move @@ -0,0 +1,158 @@ +/// This module implements a Pedersen commitment API, over the Ristretto255 curve, that can be used with the +/// Bulletproofs module. +/// +/// A Pedersen commitment to a value `v` under _commitment key_ `(g, h)` is `v * g + r * h`, for a random scalar `r`. + +module aptos_std::ristretto255_pedersen { + use aptos_std::ristretto255::{Self, RistrettoPoint, Scalar, CompressedRistretto, point_compress}; + use std::option::Option; + + // + // Constants + // + + /// The default Pedersen randomness base `h` used in our underlying Bulletproofs library. + /// This is obtained by hashing the compressed Ristretto255 basepoint using SHA3-512 (not SHA2-512). + const BULLETPROOF_DEFAULT_PEDERSEN_RAND_BASE : vector = x"8c9240b456a9e6dc65c377a1048d745f94a08cdb7f44cbcd7b46f34048871134"; + + // + // Structs + // + + /// A Pedersen commitment to some value with some randomness. + struct Commitment has drop { + point: RistrettoPoint, + } + + // + // Public functions + // + + /// Creates a new public key from a serialized Ristretto255 point. + public fun new_commitment_from_bytes(bytes: vector): Option { + let point = ristretto255::new_point_from_bytes(bytes); + if (std::option::is_some(&mut point)) { + let comm = Commitment { + point: std::option::extract(&mut point) + }; + std::option::some(comm) + } else { + std::option::none() + } + } + + /// Returns a commitment as a serialized byte array + public fun commitment_to_bytes(comm: &Commitment): vector { + ristretto255::point_to_bytes(&ristretto255::point_compress(&comm.point)) + } + + /// Moves a Ristretto point into a Pedersen commitment. + public fun commitment_from_point(point: RistrettoPoint): Commitment { + Commitment { + point + } + } + + /// Deserializes a commitment from a compressed Ristretto point. + public fun commitment_from_compressed(point: &CompressedRistretto): Commitment { + Commitment { + point: ristretto255::point_decompress(point) + } + } + + /// Returns a commitment `v * val_base + r * rand_base` where `(val_base, rand_base)` is the commitment key. + public fun new_commitment(v: &Scalar, val_base: &RistrettoPoint, r: &Scalar, rand_base: &RistrettoPoint): Commitment { + Commitment { + point: ristretto255::double_scalar_mul(v, val_base, r, rand_base) + } + } + + /// Returns a commitment `v * G + r * rand_base` where `G` is the Ristretto255 basepoint. + public fun new_commitment_with_basepoint(v: &Scalar, r: &Scalar, rand_base: &RistrettoPoint): Commitment { + Commitment { + point: ristretto255::basepoint_double_mul(r, rand_base, v) + } + } + + /// Returns a commitment `v * G + r * H` where `G` is the Ristretto255 basepoint and `H` is the default randomness + /// base used in the Bulletproofs library (i.e., `BULLETPROOF_DEFAULT_PEDERSEN_RAND_BASE`). + public fun new_commitment_for_bulletproof(v: &Scalar, r: &Scalar): Commitment { + let rand_base = ristretto255::new_point_from_bytes(BULLETPROOF_DEFAULT_PEDERSEN_RAND_BASE); + let rand_base = std::option::extract(&mut rand_base); + + Commitment { + point: ristretto255::basepoint_double_mul(r, &rand_base, v) + } + } + + /// Homomorphically combines two commitments `lhs` and `rhs` as `lhs + rhs`. + /// Useful for re-randomizing the commitment or updating the committed value. + public fun commitment_add(lhs: &Commitment, rhs: &Commitment): Commitment { + Commitment { + point: ristretto255::point_add(&lhs.point, &rhs.point) + } + } + + /// Like `commitment_add` but assigns `lhs = lhs + rhs`. + public fun commitment_add_assign(lhs: &mut Commitment, rhs: &Commitment) { + ristretto255::point_add_assign(&mut lhs.point, &rhs.point); + } + + /// Homomorphically combines two commitments `lhs` and `rhs` as `lhs - rhs`. + /// Useful for re-randomizing the commitment or updating the committed value. + public fun commitment_sub(lhs: &Commitment, rhs: &Commitment): Commitment { + Commitment { + point: ristretto255::point_sub(&lhs.point, &rhs.point) + } + } + + /// Like `commitment_add` but assigns `lhs = lhs - rhs`. + public fun commitment_sub_assign(lhs: &mut Commitment, rhs: &Commitment) { + ristretto255::point_sub_assign(&mut lhs.point, &rhs.point); + } + + /// Creates a copy of this commitment. + public fun commitment_clone(c: &Commitment): Commitment { + Commitment { + point: ristretto255::point_clone(&c.point) + } + } + + /// Returns true if the two commitments are identical: i.e., same value and same randomness. + public fun commitment_equals(lhs: &Commitment, rhs: &Commitment): bool { + ristretto255::point_equals(&lhs.point, &rhs.point) + } + + /// Returns the underlying elliptic curve point representing the commitment as an in-memory `RistrettoPoint`. + public fun commitment_as_point(c: &Commitment): &RistrettoPoint { + &c.point + } + + /// Returns the Pedersen commitment as a `CompressedRistretto` point. + public fun commitment_as_compressed_point(c: &Commitment): CompressedRistretto { + point_compress(&c.point) + } + + /// Moves the Commitment into a CompressedRistretto point. + public fun commitment_into_point(c: Commitment): RistrettoPoint { + let Commitment { point } = c; + point + } + + /// Moves the Commitment into a `CompressedRistretto` point. + public fun commitment_into_compressed_point(c: Commitment): CompressedRistretto { + point_compress(&c.point) + } + + /// Returns the randomness base compatible with the Bulletproofs module. + /// + /// Recal that a Bulletproof range proof attests, in zero-knowledge, that a value `v` inside a Pedersen commitment + /// `v * g + r * h` is sufficiently "small" (e.g., is 32-bits wide). Here, `h` is referred to as the + /// "randomness base" of the commitment scheme. + /// + /// Bulletproof has a default choice for `g` and `h` and this function returns the default `h` as used in the + /// Bulletproofs Move module. + public fun randomness_base_for_bulletproof(): RistrettoPoint { + std::option::extract(&mut ristretto255::new_point_from_bytes(BULLETPROOF_DEFAULT_PEDERSEN_RAND_BASE)) + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/secp256k1.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/secp256k1.move new file mode 100644 index 000000000..8acf9368e --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/secp256k1.move @@ -0,0 +1,114 @@ +/// This module implements ECDSA signatures based on the prime-order secp256k1 ellptic curve (i.e., cofactor is 1). + +module aptos_std::secp256k1 { + use std::option::Option; + + /// An error occurred while deserializing, for example due to wrong input size. + const E_DESERIALIZE: u64 = 1; // This code must be the same, if ever returned from the native Rust implementation. + + /// The size of a secp256k1-based ECDSA public key, in bytes. + const RAW_PUBLIC_KEY_NUM_BYTES: u64 = 64; + //const COMPRESSED_PUBLIC_KEY_SIZE: u64 = 33; + + /// The size of a secp256k1-based ECDSA signature, in bytes. + const SIGNATURE_NUM_BYTES: u64 = 64; + + /// A 64-byte ECDSA public key. + struct ECDSARawPublicKey has copy, drop, store { + bytes: vector + } + + /// A 64-byte ECDSA signature. + struct ECDSASignature has copy, drop, store { + bytes: vector + } + + /// Constructs an ECDSASignature struct from the given 64 bytes. + public fun ecdsa_signature_from_bytes(bytes: vector): ECDSASignature { + assert!(std::vector::length(&bytes) == SIGNATURE_NUM_BYTES, std::error::invalid_argument(E_DESERIALIZE)); + ECDSASignature { bytes } + } + + /// Constructs an ECDSARawPublicKey struct, given a 64-byte raw representation. + public fun ecdsa_raw_public_key_from_64_bytes(bytes: vector): ECDSARawPublicKey { + assert!(std::vector::length(&bytes) == RAW_PUBLIC_KEY_NUM_BYTES, std::error::invalid_argument(E_DESERIALIZE)); + ECDSARawPublicKey { bytes } + } + + /// Serializes an ECDSARawPublicKey struct to 64-bytes. + public fun ecdsa_raw_public_key_to_bytes(pk: &ECDSARawPublicKey): vector { + pk.bytes + } + + /// Serializes an ECDSASignature struct to 64-bytes. + public fun ecdsa_signature_to_bytes(sig: &ECDSASignature): vector { + sig.bytes + } + + /// Recovers the signer's raw (64-byte) public key from a secp256k1 ECDSA `signature` given the `recovery_id` and the signed + /// `message` (32 byte digest). + /// + /// Note that an invalid signature, or a signature from a different message, will result in the recovery of an + /// incorrect public key. This recovery algorithm can only be used to check validity of a signature if the signer's + /// public key (or its hash) is known beforehand. + public fun ecdsa_recover( + message: vector, + recovery_id: u8, + signature: &ECDSASignature, + ): Option { + let (pk, success) = ecdsa_recover_internal(message, recovery_id, signature.bytes); + if (success) { + std::option::some(ecdsa_raw_public_key_from_64_bytes(pk)) + } else { + std::option::none() + } + } + + // + // Native functions + // + + /// Returns `(public_key, true)` if `signature` verifies on `message` under the recovered `public_key` + /// and returns `([], false)` otherwise. + native fun ecdsa_recover_internal( + message: vector, + recovery_id: u8, + signature: vector + ): (vector, bool); + + // + // Tests + // + + #[test] + /// Test on a valid secp256k1 ECDSA signature created using sk = x"0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + fun test_ecdsa_recover() { + use std::hash; + + let pk = ecdsa_recover( + hash::sha2_256(b"test aptos secp256k1"), + 0, + &ECDSASignature { bytes: x"f7ad936da03f948c14c542020e3c5f4e02aaacd1f20427c11aa6e2fbf8776477646bba0e1a37f9e7c777c423a1d2849baafd7ff6a9930814a43c3f80d59db56f" }, + ); + assert!(std::option::is_some(&pk), 1); + assert!(std::option::extract(&mut pk).bytes == x"4646ae5047316b4230d0086c8acec687f00b1cd9d1dc634f6cb358ac0a9a8ffffe77b4dd0a4bfb95851f3b7355c781dd60f8418fc8a65d14907aff47c903a559", 1); + + // Flipped bits; Signature stays valid + let pk = ecdsa_recover( + hash::sha2_256(b"test aptos secp256k1"), + 0, + // NOTE: A '7' was flipped to an 'f' here + &ECDSASignature { bytes: x"f7ad936da03f948c14c542020e3c5f4e02aaacd1f20427c11aa6e2fbf8776477646bba0e1a37f9e7c7f7c423a1d2849baafd7ff6a9930814a43c3f80d59db56f" }, + ); + assert!(std::option::is_some(&pk), 1); + assert!(std::option::extract(&mut pk).bytes != x"4646ae5047316b4230d0086c8acec687f00b1cd9d1dc634f6cb358ac0a9a8ffffe77b4dd0a4bfb95851f3b7355c781dd60f8418fc8a65d14907aff47c903a559", 1); + + // Flipped bits; Signature becomes invalid + let pk = ecdsa_recover( + hash::sha2_256(b"test aptos secp256k1"), + 0, + &ECDSASignature { bytes: x"ffad936da03f948c14c542020e3c5f4e02aaacd1f20427c11aa6e2fbf8776477646bba0e1a37f9e7c7f7c423a1d2849baafd7ff6a9930814a43c3f80d59db56f" }, + ); + assert!(std::option::is_none(&pk), 1); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/simple_map.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/simple_map.move new file mode 100644 index 000000000..98ae46cf6 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/simple_map.move @@ -0,0 +1,319 @@ +/// This module provides a solution for unsorted maps, that is it has the properties that +/// 1) Keys point to Values +/// 2) Each Key must be unique +/// 3) A Key can be found within O(N) time +/// 4) The keys are unsorted. +/// 5) Adds and removals take O(N) time +module aptos_std::simple_map { + use std::error; + use std::option; + use std::vector; + + /// Map key already exists + const EKEY_ALREADY_EXISTS: u64 = 1; + /// Map key is not found + const EKEY_NOT_FOUND: u64 = 2; + + struct SimpleMap has copy, drop, store { + data: vector>, + } + + struct Element has copy, drop, store { + key: Key, + value: Value, + } + + public fun length(map: &SimpleMap): u64 { + vector::length(&map.data) + } + + /// Create an empty SimpleMap. + public fun new(): SimpleMap { + SimpleMap { + data: vector::empty(), + } + } + + /// Create a SimpleMap from a vector of keys and values. The keys must be unique. + public fun new_from( + keys: vector, + values: vector, + ): SimpleMap { + let map = new(); + add_all(&mut map, keys, values); + map + } + + #[deprecated] + /// Create an empty SimpleMap. + /// This function is deprecated, use `new` instead. + public fun create(): SimpleMap { + new() + } + + public fun borrow( + map: &SimpleMap, + key: &Key, + ): &Value { + let maybe_idx = find(map, key); + assert!(option::is_some(&maybe_idx), error::invalid_argument(EKEY_NOT_FOUND)); + let idx = option::extract(&mut maybe_idx); + &vector::borrow(&map.data, idx).value + } + + public fun borrow_mut( + map: &mut SimpleMap, + key: &Key, + ): &mut Value { + let maybe_idx = find(map, key); + assert!(option::is_some(&maybe_idx), error::invalid_argument(EKEY_NOT_FOUND)); + let idx = option::extract(&mut maybe_idx); + &mut vector::borrow_mut(&mut map.data, idx).value + } + + public fun contains_key( + map: &SimpleMap, + key: &Key, + ): bool { + let maybe_idx = find(map, key); + option::is_some(&maybe_idx) + } + + public fun destroy_empty(map: SimpleMap) { + let SimpleMap { data } = map; + vector::destroy_empty(data); + } + + /// Add a key/value pair to the map. The key must not already exist. + public fun add( + map: &mut SimpleMap, + key: Key, + value: Value, + ) { + let maybe_idx = find(map, &key); + assert!(option::is_none(&maybe_idx), error::invalid_argument(EKEY_ALREADY_EXISTS)); + + vector::push_back(&mut map.data, Element { key, value }); + } + + /// Add multiple key/value pairs to the map. The keys must not already exist. + public fun add_all( + map: &mut SimpleMap, + keys: vector, + values: vector, + ) { + vector::zip(keys, values, |key, value| { + add(map, key, value); + }); + } + + /// Insert key/value pair or update an existing key to a new value + public fun upsert( + map: &mut SimpleMap, + key: Key, + value: Value + ): (std::option::Option, std::option::Option) { + let data = &mut map.data; + let len = vector::length(data); + let i = 0; + while (i < len) { + let element = vector::borrow(data, i); + if (&element.key == &key) { + vector::push_back(data, Element { key, value }); + vector::swap(data, i, len); + let Element { key, value } = vector::pop_back(data); + return (std::option::some(key), std::option::some(value)) + }; + i = i + 1; + }; + vector::push_back(&mut map.data, Element { key, value }); + (std::option::none(), std::option::none()) + } + + /// Return all keys in the map. This requires keys to be copyable. + public fun keys(map: &SimpleMap): vector { + vector::map_ref(&map.data, |e| { + let e: &Element = e; + e.key + }) + } + + /// Return all values in the map. This requires values to be copyable. + public fun values(map: &SimpleMap): vector { + vector::map_ref(&map.data, |e| { + let e: &Element = e; + e.value + }) + } + + /// Transform the map into two vectors with the keys and values respectively + /// Primarily used to destroy a map + public fun to_vec_pair( + map: SimpleMap): (vector, vector) { + let keys: vector = vector::empty(); + let values: vector = vector::empty(); + let SimpleMap { data } = map; + vector::for_each(data, |e| { + let Element { key, value } = e; + vector::push_back(&mut keys, key); + vector::push_back(&mut values, value); + }); + (keys, values) + } + + /// For maps that cannot be dropped this is a utility to destroy them + /// using lambdas to destroy the individual keys and values. + public inline fun destroy( + map: SimpleMap, + dk: |Key|, + dv: |Value| + ) { + let (keys, values) = to_vec_pair(map); + vector::destroy(keys, |_k| dk(_k)); + vector::destroy(values, |_v| dv(_v)); + } + + /// Remove a key/value pair from the map. The key must exist. + public fun remove( + map: &mut SimpleMap, + key: &Key, + ): (Key, Value) { + let maybe_idx = find(map, key); + assert!(option::is_some(&maybe_idx), error::invalid_argument(EKEY_NOT_FOUND)); + let placement = option::extract(&mut maybe_idx); + let Element { key, value } = vector::swap_remove(&mut map.data, placement); + (key, value) + } + + fun find( + map: &SimpleMap, + key: &Key, + ): option::Option { + let leng = vector::length(&map.data); + let i = 0; + while (i < leng) { + let element = vector::borrow(&map.data, i); + if (&element.key == key) { + return option::some(i) + }; + i = i + 1; + }; + option::none() + } + + #[test] + public fun test_add_remove_many() { + let map = create(); + + assert!(length(&map) == 0, 0); + assert!(!contains_key(&map, &3), 1); + add(&mut map, 3, 1); + assert!(length(&map) == 1, 2); + assert!(contains_key(&map, &3), 3); + assert!(borrow(&map, &3) == &1, 4); + *borrow_mut(&mut map, &3) = 2; + assert!(borrow(&map, &3) == &2, 5); + + assert!(!contains_key(&map, &2), 6); + add(&mut map, 2, 5); + assert!(length(&map) == 2, 7); + assert!(contains_key(&map, &2), 8); + assert!(borrow(&map, &2) == &5, 9); + *borrow_mut(&mut map, &2) = 9; + assert!(borrow(&map, &2) == &9, 10); + + remove(&mut map, &2); + assert!(length(&map) == 1, 11); + assert!(!contains_key(&map, &2), 12); + assert!(borrow(&map, &3) == &2, 13); + + remove(&mut map, &3); + assert!(length(&map) == 0, 14); + assert!(!contains_key(&map, &3), 15); + + destroy_empty(map); + } + + #[test] + public fun test_add_all() { + let map = create(); + + assert!(length(&map) == 0, 0); + add_all(&mut map, vector[1, 2, 3], vector[10, 20, 30]); + assert!(length(&map) == 3, 1); + assert!(borrow(&map, &1) == &10, 2); + assert!(borrow(&map, &2) == &20, 3); + assert!(borrow(&map, &3) == &30, 4); + + remove(&mut map, &1); + remove(&mut map, &2); + remove(&mut map, &3); + destroy_empty(map); + } + + #[test] + public fun test_keys() { + let map = create(); + assert!(keys(&map) == vector[], 0); + add(&mut map, 2, 1); + add(&mut map, 3, 1); + + assert!(keys(&map) == vector[2, 3], 0); + } + + #[test] + public fun test_values() { + let map = create(); + assert!(values(&map) == vector[], 0); + add(&mut map, 2, 1); + add(&mut map, 3, 2); + + assert!(values(&map) == vector[1, 2], 0); + } + + #[test] + #[expected_failure] + public fun test_add_twice() { + let map = create(); + add(&mut map, 3, 1); + add(&mut map, 3, 1); + + remove(&mut map, &3); + destroy_empty(map); + } + + #[test] + #[expected_failure] + public fun test_remove_twice() { + let map = create(); + add(&mut map, 3, 1); + remove(&mut map, &3); + remove(&mut map, &3); + + destroy_empty(map); + } + + #[test] + public fun test_upsert_test() { + let map = create(); + // test adding 3 elements using upsert + upsert(&mut map, 1, 1); + upsert(&mut map, 2, 2); + upsert(&mut map, 3, 3); + + assert!(length(&map) == 3, 0); + assert!(contains_key(&map, &1), 1); + assert!(contains_key(&map, &2), 2); + assert!(contains_key(&map, &3), 3); + assert!(borrow(&map, &1) == &1, 4); + assert!(borrow(&map, &2) == &2, 5); + assert!(borrow(&map, &3) == &3, 6); + + // change mapping 1->1 to 1->4 + upsert(&mut map, 1, 4); + + assert!(length(&map) == 3, 7); + assert!(contains_key(&map, &1), 8); + assert!(borrow(&map, &1) == &4, 9); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/smart_table.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/smart_table.move new file mode 100644 index 000000000..60a9565d0 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/smart_table.move @@ -0,0 +1,769 @@ +/// A smart table implementation based on linear hashing. (https://en.wikipedia.org/wiki/Linear_hashing) +/// Compare to Table, it uses less storage slots but has higher chance of collision, a trade-off between space and time. +/// Compare to other dynamic hashing implementation, linear hashing splits one bucket a time instead of doubling buckets +/// when expanding to avoid unexpected gas cost. +/// SmartTable uses faster hash function SipHash instead of cryptographically secure hash functions like sha3-256 since +/// it tolerates collisions. +module aptos_std::smart_table { + use std::error; + use std::vector; + use aptos_std::aptos_hash::sip_hash_from_value; + use aptos_std::table_with_length::{Self, TableWithLength}; + use aptos_std::type_info::size_of_val; + use aptos_std::math64::max; + use aptos_std::simple_map::SimpleMap; + use aptos_std::simple_map; + use std::option::{Self, Option}; + + /// Key not found in the smart table + const ENOT_FOUND: u64 = 1; + /// Smart table capacity must be larger than 0 + const EZERO_CAPACITY: u64 = 2; + /// Cannot destroy non-empty hashmap + const ENOT_EMPTY: u64 = 3; + /// Key already exists + const EALREADY_EXIST: u64 = 4; + /// Invalid load threshold percent to trigger split. + const EINVALID_LOAD_THRESHOLD_PERCENT: u64 = 5; + /// Invalid target bucket size. + const EINVALID_TARGET_BUCKET_SIZE: u64 = 6; + /// Invalid target bucket size. + const EEXCEED_MAX_BUCKET_SIZE: u64 = 7; + /// Invalid bucket index. + const EINVALID_BUCKET_INDEX: u64 = 8; + /// Invalid vector index within a bucket. + const EINVALID_VECTOR_INDEX: u64 = 9; + + /// SmartTable entry contains both the key and value. + struct Entry has copy, drop, store { + hash: u64, + key: K, + value: V, + } + + struct SmartTable has store { + buckets: TableWithLength>>, + num_buckets: u64, + // number of bits to represent num_buckets + level: u8, + // total number of items + size: u64, + // Split will be triggered when target load threshold in percentage is reached when adding a new entry. + split_load_threshold: u8, + // The target size of each bucket, which is NOT enforced so oversized buckets can exist. + target_bucket_size: u64, + } + + /// Create an empty SmartTable with default configurations. + public fun new(): SmartTable { + new_with_config(0, 0, 0) + } + + /// Create an empty SmartTable with customized configurations. + /// `num_initial_buckets`: The number of buckets on initialization. 0 means using default value. + /// `split_load_threshold`: The percent number which once reached, split will be triggered. 0 means using default + /// value. + /// `target_bucket_size`: The target number of entries per bucket, though not guaranteed. 0 means not set and will + /// dynamically assgined by the contract code. + public fun new_with_config( + num_initial_buckets: u64, + split_load_threshold: u8, + target_bucket_size: u64 + ): SmartTable { + assert!(split_load_threshold <= 100, error::invalid_argument(EINVALID_LOAD_THRESHOLD_PERCENT)); + let buckets = table_with_length::new(); + table_with_length::add(&mut buckets, 0, vector::empty()); + let table = SmartTable { + buckets, + num_buckets: 1, + level: 0, + size: 0, + // The default split load threshold is 75%. + split_load_threshold: if (split_load_threshold == 0) { 75 } else { split_load_threshold }, + target_bucket_size, + }; + // The default number of initial buckets is 2. + if (num_initial_buckets == 0) { + num_initial_buckets = 2; + }; + while (num_initial_buckets > 1) { + num_initial_buckets = num_initial_buckets - 1; + split_one_bucket(&mut table); + }; + table + } + + /// Destroy empty table. + /// Aborts if it's not empty. + public fun destroy_empty(table: SmartTable) { + assert!(table.size == 0, error::invalid_argument(ENOT_EMPTY)); + let i = 0; + while (i < table.num_buckets) { + vector::destroy_empty(table_with_length::remove(&mut table.buckets, i)); + i = i + 1; + }; + let SmartTable { buckets, num_buckets: _, level: _, size: _, split_load_threshold: _, target_bucket_size: _ } = table; + table_with_length::destroy_empty(buckets); + } + + /// Destroy a table completely when V has `drop`. + public fun destroy(table: SmartTable) { + clear(&mut table); + destroy_empty(table); + } + + /// Clear a table completely when T has `drop`. + public fun clear(table: &mut SmartTable) { + *table_with_length::borrow_mut(&mut table.buckets, 0) = vector::empty(); + let i = 1; + while (i < table.num_buckets) { + table_with_length::remove(&mut table.buckets, i); + i = i + 1; + }; + table.num_buckets = 1; + table.level = 0; + table.size = 0; + } + + /// Add (key, value) pair in the hash map, it may grow one bucket if current load factor exceeds the threshold. + /// Note it may not split the actual overflowed bucket. Instead, it was determined by `num_buckets` and `level`. + /// For standard linear hash algorithm, it is stored as a variable but `num_buckets` here could be leveraged. + /// Abort if `key` already exists. + /// Note: This method may occasionally cost much more gas when triggering bucket split. + public fun add(table: &mut SmartTable, key: K, value: V) { + let hash = sip_hash_from_value(&key); + let index = bucket_index(table.level, table.num_buckets, hash); + let bucket = table_with_length::borrow_mut(&mut table.buckets, index); + // We set a per-bucket limit here with a upper bound (10000) that nobody should normally reach. + assert!(vector::length(bucket) <= 10000, error::permission_denied(EEXCEED_MAX_BUCKET_SIZE)); + assert!(vector::all(bucket, | entry | { + let e: &Entry = entry; + &e.key != &key + }), error::invalid_argument(EALREADY_EXIST)); + let e = Entry { hash, key, value }; + if (table.target_bucket_size == 0) { + let estimated_entry_size = max(size_of_val(&e), 1); + table.target_bucket_size = max(1024 /* free_write_quota */ / estimated_entry_size, 1); + }; + vector::push_back(bucket, e); + table.size = table.size + 1; + + if (load_factor(table) >= (table.split_load_threshold as u64)) { + split_one_bucket(table); + } + } + + /// Add multiple key/value pairs to the smart table. The keys must not already exist. + public fun add_all(table: &mut SmartTable, keys: vector, values: vector) { + vector::zip(keys, values, |key, value| { add(table, key, value); }); + } + + inline fun unzip_entries(entries: &vector>): (vector, vector) { + let keys = vector[]; + let values = vector[]; + vector::for_each_ref(entries, |e|{ + let entry: &Entry = e; + vector::push_back(&mut keys, entry.key); + vector::push_back(&mut values, entry.value); + }); + (keys, values) + } + + /// Convert a smart table to a simple_map, which is supposed to be called mostly by view functions to get an atomic + /// view of the whole table. + /// Disclaimer: This function may be costly as the smart table may be huge in size. Use it at your own discretion. + public fun to_simple_map( + table: &SmartTable, + ): SimpleMap { + let i = 0; + let res = simple_map::new(); + while (i < table.num_buckets) { + let (keys, values) = unzip_entries(table_with_length::borrow(&table.buckets, i)); + simple_map::add_all(&mut res, keys, values); + i = i + 1; + }; + res + } + + /// Get all keys in a smart table. + /// + /// For a large enough smart table this function will fail due to execution gas limits, and + /// `keys_paginated` should be used instead. + public fun keys( + table_ref: &SmartTable + ): vector { + let (keys, _, _) = keys_paginated(table_ref, 0, 0, length(table_ref)); + keys + } + + /// Get keys from a smart table, paginated. + /// + /// This function can be used to paginate all keys in a large smart table outside of runtime, + /// e.g. through chained view function calls. The maximum `num_keys_to_get` before hitting gas + /// limits depends on the data types in the smart table. + /// + /// When starting pagination, pass `starting_bucket_index` = `starting_vector_index` = 0. + /// + /// The function will then return a vector of keys, an optional bucket index, and an optional + /// vector index. The unpacked return indices can then be used as inputs to another pagination + /// call, which will return a vector of more keys. This process can be repeated until the + /// returned bucket index and vector index value options are both none, which means that + /// pagination is complete. For an example, see `test_keys()`. + public fun keys_paginated( + table_ref: &SmartTable, + starting_bucket_index: u64, + starting_vector_index: u64, + num_keys_to_get: u64, + ): ( + vector, + Option, + Option, + ) { + let num_buckets = table_ref.num_buckets; + let buckets_ref = &table_ref.buckets; + assert!(starting_bucket_index < num_buckets, EINVALID_BUCKET_INDEX); + let bucket_ref = table_with_length::borrow(buckets_ref, starting_bucket_index); + let bucket_length = vector::length(bucket_ref); + assert!( + // In the general case, starting vector index should never be equal to bucket length + // because then iteration will attempt to borrow a vector element that is out of bounds. + // However starting vector index can be equal to bucket length in the special case of + // starting iteration at the beginning of an empty bucket since buckets are never + // destroyed, only emptied. + starting_vector_index < bucket_length || starting_vector_index == 0, + EINVALID_VECTOR_INDEX + ); + let keys = vector[]; + if (num_keys_to_get == 0) return + (keys, option::some(starting_bucket_index), option::some(starting_vector_index)); + for (bucket_index in starting_bucket_index..num_buckets) { + bucket_ref = table_with_length::borrow(buckets_ref, bucket_index); + bucket_length = vector::length(bucket_ref); + for (vector_index in starting_vector_index..bucket_length) { + vector::push_back(&mut keys, vector::borrow(bucket_ref, vector_index).key); + num_keys_to_get = num_keys_to_get - 1; + if (num_keys_to_get == 0) { + vector_index = vector_index + 1; + return if (vector_index == bucket_length) { + bucket_index = bucket_index + 1; + if (bucket_index < num_buckets) { + (keys, option::some(bucket_index), option::some(0)) + } else { + (keys, option::none(), option::none()) + } + } else { + (keys, option::some(bucket_index), option::some(vector_index)) + } + }; + }; + starting_vector_index = 0; // Start parsing the next bucket at vector index 0. + }; + (keys, option::none(), option::none()) + } + + /// Decide which is the next bucket to split and split it into two with the elements inside the bucket. + fun split_one_bucket(table: &mut SmartTable) { + let new_bucket_index = table.num_buckets; + // the next bucket to split is num_bucket without the most significant bit. + let to_split = new_bucket_index ^ (1 << table.level); + table.num_buckets = new_bucket_index + 1; + // if the whole level is splitted once, bump the level. + if (to_split + 1 == 1 << table.level) { + table.level = table.level + 1; + }; + let old_bucket = table_with_length::borrow_mut(&mut table.buckets, to_split); + // partition the bucket, [0..p) stays in old bucket, [p..len) goes to new bucket + let p = vector::partition(old_bucket, |e| { + let entry: &Entry = e; // Explicit type to satisfy compiler + bucket_index(table.level, table.num_buckets, entry.hash) != new_bucket_index + }); + let new_bucket = vector::trim_reverse(old_bucket, p); + table_with_length::add(&mut table.buckets, new_bucket_index, new_bucket); + } + + /// Return the expected bucket index to find the hash. + /// Basically, it use different base `1 << level` vs `1 << (level + 1)` in modulo operation based on the target + /// bucket index compared to the index of the next bucket to split. + fun bucket_index(level: u8, num_buckets: u64, hash: u64): u64 { + let index = hash % (1 << (level + 1)); + if (index < num_buckets) { + // in existing bucket + index + } else { + // in unsplitted bucket + index % (1 << level) + } + } + + /// Acquire an immutable reference to the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun borrow(table: &SmartTable, key: K): &V { + let index = bucket_index(table.level, table.num_buckets, sip_hash_from_value(&key)); + let bucket = table_with_length::borrow(&table.buckets, index); + let i = 0; + let len = vector::length(bucket); + while (i < len) { + let entry = vector::borrow(bucket, i); + if (&entry.key == &key) { + return &entry.value + }; + i = i + 1; + }; + abort error::invalid_argument(ENOT_FOUND) + } + + /// Acquire an immutable reference to the value which `key` maps to. + /// Returns specified default value if there is no entry for `key`. + public fun borrow_with_default(table: &SmartTable, key: K, default: &V): &V { + if (!contains(table, copy key)) { + default + } else { + borrow(table, copy key) + } + } + + /// Acquire a mutable reference to the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun borrow_mut(table: &mut SmartTable, key: K): &mut V { + let index = bucket_index(table.level, table.num_buckets, sip_hash_from_value(&key)); + let bucket = table_with_length::borrow_mut(&mut table.buckets, index); + let i = 0; + let len = vector::length(bucket); + while (i < len) { + let entry = vector::borrow_mut(bucket, i); + if (&entry.key == &key) { + return &mut entry.value + }; + i = i + 1; + }; + abort error::invalid_argument(ENOT_FOUND) + } + + /// Acquire a mutable reference to the value which `key` maps to. + /// Insert the pair (`key`, `default`) first if there is no entry for `key`. + public fun borrow_mut_with_default( + table: &mut SmartTable, + key: K, + default: V + ): &mut V { + if (!contains(table, copy key)) { + add(table, copy key, default) + }; + borrow_mut(table, key) + } + + /// Returns true iff `table` contains an entry for `key`. + public fun contains(table: &SmartTable, key: K): bool { + let hash = sip_hash_from_value(&key); + let index = bucket_index(table.level, table.num_buckets, hash); + let bucket = table_with_length::borrow(&table.buckets, index); + vector::any(bucket, | entry | { + let e: &Entry = entry; + e.hash == hash && &e.key == &key + }) + } + + /// Remove from `table` and return the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun remove(table: &mut SmartTable, key: K): V { + let index = bucket_index(table.level, table.num_buckets, sip_hash_from_value(&key)); + let bucket = table_with_length::borrow_mut(&mut table.buckets, index); + let i = 0; + let len = vector::length(bucket); + while (i < len) { + let entry = vector::borrow(bucket, i); + if (&entry.key == &key) { + let Entry { hash: _, key: _, value } = vector::swap_remove(bucket, i); + table.size = table.size - 1; + return value + }; + i = i + 1; + }; + abort error::invalid_argument(ENOT_FOUND) + } + + /// Insert the pair (`key`, `value`) if there is no entry for `key`. + /// update the value of the entry for `key` to `value` otherwise + public fun upsert(table: &mut SmartTable, key: K, value: V) { + if (!contains(table, copy key)) { + add(table, copy key, value) + } else { + let ref = borrow_mut(table, key); + *ref = value; + }; + } + + /// Returns the length of the table, i.e. the number of entries. + public fun length(table: &SmartTable): u64 { + table.size + } + + /// Return the load factor of the hashtable. + public fun load_factor(table: &SmartTable): u64 { + table.size * 100 / table.num_buckets / table.target_bucket_size + } + + /// Update `split_load_threshold`. + public fun update_split_load_threshold(table: &mut SmartTable, split_load_threshold: u8) { + assert!( + split_load_threshold <= 100 && split_load_threshold > 0, + error::invalid_argument(EINVALID_LOAD_THRESHOLD_PERCENT) + ); + table.split_load_threshold = split_load_threshold; + } + + /// Update `target_bucket_size`. + public fun update_target_bucket_size(table: &mut SmartTable, target_bucket_size: u64) { + assert!(target_bucket_size > 0, error::invalid_argument(EINVALID_TARGET_BUCKET_SIZE)); + table.target_bucket_size = target_bucket_size; + } + + /// Apply the function to a reference of each key-value pair in the table. + public inline fun for_each_ref(table: &SmartTable, f: |&K, &V|) { + let i = 0; + while (i < aptos_std::smart_table::num_buckets(table)) { + vector::for_each_ref( + aptos_std::table_with_length::borrow(aptos_std::smart_table::borrow_buckets(table), i), + |elem| { + let (key, value) = aptos_std::smart_table::borrow_kv(elem); + f(key, value) + } + ); + i = i + 1; + } + } + + /// Apply the function to a mutable reference of each key-value pair in the table. + public inline fun for_each_mut(table: &mut SmartTable, f: |&K, &mut V|) { + let i = 0; + while (i < aptos_std::smart_table::num_buckets(table)) { + vector::for_each_mut( + table_with_length::borrow_mut(aptos_std::smart_table::borrow_buckets_mut(table), i), + |elem| { + let (key, value) = aptos_std::smart_table::borrow_kv_mut(elem); + f(key, value) + } + ); + i = i + 1; + }; + } + + /// Map the function over the references of key-value pairs in the table without modifying it. + public inline fun map_ref( + table: &SmartTable, + f: |&V1|V2 + ): SmartTable { + let new_table = new(); + for_each_ref(table, |key, value| add(&mut new_table, *key, f(value))); + new_table + } + + /// Return true if any key-value pair in the table satisfies the predicate. + public inline fun any( + table: &SmartTable, + p: |&K, &V|bool + ): bool { + let found = false; + let i = 0; + while (i < aptos_std::smart_table::num_buckets(table)) { + found = vector::any(table_with_length::borrow(aptos_std::smart_table::borrow_buckets(table), i), |elem| { + let (key, value) = aptos_std::smart_table::borrow_kv(elem); + p(key, value) + }); + if (found) break; + i = i + 1; + }; + found + } + + // Helper functions to circumvent the scope issue of inline functions. + public fun borrow_kv(e: &Entry): (&K, &V) { + (&e.key, &e.value) + } + + public fun borrow_kv_mut(e: &mut Entry): (&mut K, &mut V) { + (&mut e.key, &mut e.value) + } + + public fun num_buckets(table: &SmartTable): u64 { + table.num_buckets + } + + public fun borrow_buckets(table: &SmartTable): &TableWithLength>> { + &table.buckets + } + + public fun borrow_buckets_mut(table: &mut SmartTable): &mut TableWithLength>> { + &mut table.buckets + } + + + #[test] + fun smart_table_test() { + let table = new(); + let i = 0; + while (i < 200) { + add(&mut table, i, i); + i = i + 1; + }; + assert!(length(&table) == 200, 0); + i = 0; + while (i < 200) { + *borrow_mut(&mut table, i) = i * 2; + assert!(*borrow(&table, i) == i * 2, 0); + i = i + 1; + }; + i = 0; + assert!(table.num_buckets > 5, table.num_buckets); + while (i < 200) { + assert!(contains(&table, i), 0); + assert!(remove(&mut table, i) == i * 2, 0); + i = i + 1; + }; + destroy_empty(table); + } + + #[test] + fun smart_table_split_test() { + let table: SmartTable = new_with_config(1, 100, 1); + let i = 1; + let level = 0; + while (i <= 256) { + assert!(table.num_buckets == i, 0); + assert!(table.level == level, i); + add(&mut table, i, i); + i = i + 1; + if (i == 1 << (level + 1)) { + level = level + 1; + }; + }; + let i = 1; + while (i <= 256) { + assert!(*borrow(&table, i) == i, 0); + i = i + 1; + }; + assert!(table.num_buckets == 257, table.num_buckets); + assert!(load_factor(&table) == 99, 0); + assert!(length(&table) == 256, 0); + destroy(table); + } + + #[test] + fun smart_table_update_configs() { + let table = new(); + let i = 0; + while (i < 200) { + add(&mut table, i, i); + i = i + 1; + }; + assert!(length(&table) == 200, 0); + update_target_bucket_size(&mut table, 10); + update_split_load_threshold(&mut table, 50); + while (i < 400) { + add(&mut table, i, i); + i = i + 1; + }; + assert!(length(&table) == 400, 0); + i = 0; + while (i < 400) { + assert!(contains(&table, i), 0); + assert!(remove(&mut table, i) == i, 0); + i = i + 1; + }; + destroy_empty(table); + } + + #[test] + public fun smart_table_add_all_test() { + let table: SmartTable = new_with_config(1, 100, 2); + assert!(length(&table) == 0, 0); + add_all(&mut table, vector[1, 2, 3, 4, 5, 6, 7], vector[1, 2, 3, 4, 5, 6, 7]); + assert!(length(&table) == 7, 1); + let i = 1; + while (i < 8) { + assert!(*borrow(&table, i) == i, 0); + i = i + 1; + }; + i = i - 1; + while (i > 0) { + remove(&mut table, i); + i = i - 1; + }; + destroy_empty(table); + } + + #[test] + public fun smart_table_to_simple_map_test() { + let table = new(); + let i = 0; + while (i < 200) { + add(&mut table, i, i); + i = i + 1; + }; + let map = to_simple_map(&table); + assert!(simple_map::length(&map) == 200, 0); + destroy(table); + } + + #[test] + public fun smart_table_clear_test() { + let table = new(); + let i = 0u64; + while (i < 200) { + add(&mut table, i, i); + i = i + 1; + }; + clear(&mut table); + let i = 0; + while (i < 200) { + add(&mut table, i, i); + i = i + 1; + }; + assert!(table.size == 200, 0); + destroy(table); + } + + #[test] + fun test_keys() { + let i = 0; + let table = new(); + let expected_keys = vector[]; + let keys = keys(&table); + assert!(vector::is_empty(&keys), 0); + let starting_bucket_index = 0; + let starting_vector_index = 0; + let (keys, starting_bucket_index_r, starting_vector_index_r) = keys_paginated( + &table, + starting_bucket_index, + starting_vector_index, + 0 + ); + assert!(starting_bucket_index_r == option::some(starting_bucket_index), 0); + assert!(starting_vector_index_r == option::some(starting_vector_index), 0); + assert!(vector::is_empty(&keys), 0); + while (i < 100) { + add(&mut table, i, 0); + vector::push_back(&mut expected_keys, i); + i = i + 1; + }; + let keys = keys(&table); + assert!(vector::length(&keys) == vector::length(&expected_keys), 0); + vector::for_each_ref(&keys, |e_ref| { + assert!(vector::contains(&expected_keys, e_ref), 0); + }); + let keys = vector[]; + let starting_bucket_index = 0; + let starting_vector_index = 0; + let returned_keys = vector[]; + vector::length(&returned_keys); // To eliminate erroneous compiler "unused" warning + loop { + (returned_keys, starting_bucket_index_r, starting_vector_index_r) = keys_paginated( + &table, + starting_bucket_index, + starting_vector_index, + 15 + ); + vector::append(&mut keys, returned_keys); + if ( + starting_bucket_index_r == option::none() || + starting_vector_index_r == option::none() + ) break; + starting_bucket_index = option::destroy_some(starting_bucket_index_r); + starting_vector_index = option::destroy_some(starting_vector_index_r); + }; + assert!(vector::length(&keys) == vector::length(&expected_keys), 0); + vector::for_each_ref(&keys, |e_ref| { + assert!(vector::contains(&expected_keys, e_ref), 0); + }); + destroy(table); + table = new(); + add(&mut table, 1, 0); + add(&mut table, 2, 0); + (keys, starting_bucket_index_r, starting_vector_index_r) = keys_paginated(&table, 0, 0, 1); + (returned_keys, starting_bucket_index_r, starting_vector_index_r) = keys_paginated( + &table, + option::destroy_some(starting_bucket_index_r), + option::destroy_some(starting_vector_index_r), + 1, + ); + vector::append(&mut keys, returned_keys); + assert!(keys == vector[1, 2] || keys == vector[2, 1], 0); + assert!(starting_bucket_index_r == option::none(), 0); + assert!(starting_vector_index_r == option::none(), 0); + (keys, starting_bucket_index_r, starting_vector_index_r) = keys_paginated(&table, 0, 0, 0); + assert!(keys == vector[], 0); + assert!(starting_bucket_index_r == option::some(0), 0); + assert!(starting_vector_index_r == option::some(0), 0); + destroy(table); + } + + #[test] + fun test_keys_corner_cases() { + let table = new(); + let expected_keys = vector[]; + for (i in 0..100) { + add(&mut table, i, 0); + vector::push_back(&mut expected_keys, i); + }; + let (keys, starting_bucket_index_r, starting_vector_index_r) = + keys_paginated(&table, 0, 0, 5); // Both indices 0. + assert!(vector::length(&keys) == 5, 0); + vector::for_each_ref(&keys, |e_ref| { + assert!(vector::contains(&expected_keys, e_ref), 0); + }); + let starting_bucket_index = option::destroy_some(starting_bucket_index_r); + let starting_vector_index = option::destroy_some(starting_vector_index_r); + (keys, starting_bucket_index_r, starting_vector_index_r) = keys_paginated( + &table, + starting_bucket_index, + starting_vector_index, + 0, // Number of keys 0. + ); + assert!(keys == vector[], 0); + assert!(starting_bucket_index_r == option::some(starting_bucket_index), 0); + assert!(starting_vector_index_r == option::some(starting_vector_index), 0); + (keys, starting_bucket_index_r, starting_vector_index_r) = keys_paginated( + &table, + starting_bucket_index, + 0, // Vector index 0. + 50, + ); + assert!(vector::length(&keys) == 50, 0); + vector::for_each_ref(&keys, |e_ref| { + assert!(vector::contains(&expected_keys, e_ref), 0); + }); + let starting_bucket_index = option::destroy_some(starting_bucket_index_r); + assert!(starting_bucket_index > 0, 0); + assert!(option::is_some(&starting_vector_index_r), 0); + (keys, starting_bucket_index_r, starting_vector_index_r) = keys_paginated( + &table, + 0, // Bucket index 0. + 1, + 50, + ); + assert!(vector::length(&keys) == 50, 0); + vector::for_each_ref(&keys, |e_ref| { + assert!(vector::contains(&expected_keys, e_ref), 0); + }); + assert!(option::is_some(&starting_bucket_index_r), 0); + assert!(option::is_some(&starting_vector_index_r), 0); + destroy(table); + } + + #[test, expected_failure(abort_code = EINVALID_BUCKET_INDEX)] + fun test_keys_invalid_bucket_index() { + let table = new(); + add(&mut table, 1, 0); + let num_buckets = table.num_buckets; + keys_paginated(&table, num_buckets + 1, 0, 1); + destroy(table); + } + + #[test, expected_failure(abort_code = EINVALID_VECTOR_INDEX)] + fun test_keys_invalid_vector_index() { + let table = new(); + add(&mut table, 1, 0); + keys_paginated(&table, 0, 1, 1); + destroy(table); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/smart_vector.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/smart_vector.move new file mode 100644 index 000000000..10f3c816b --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/smart_vector.move @@ -0,0 +1,766 @@ +module aptos_std::smart_vector { + use std::error; + use std::vector; + use aptos_std::big_vector::{Self, BigVector}; + use aptos_std::math64::max; + use aptos_std::type_info::size_of_val; + use std::option::{Self, Option}; + + /// Vector index is out of bounds + const EINDEX_OUT_OF_BOUNDS: u64 = 1; + /// Cannot destroy a non-empty vector + const EVECTOR_NOT_EMPTY: u64 = 2; + /// Cannot pop back from an empty vector + const EVECTOR_EMPTY: u64 = 3; + /// bucket_size cannot be 0 + const EZERO_BUCKET_SIZE: u64 = 4; + /// The length of the smart vectors are not equal. + const ESMART_VECTORS_LENGTH_MISMATCH: u64 = 0x20005; + + /// A Scalable vector implementation based on tables, Ts are grouped into buckets with `bucket_size`. + /// The option wrapping BigVector saves space in the metadata associated with BigVector when smart_vector is + /// so small that inline_vec vector can hold all the data. + struct SmartVector has store { + inline_vec: vector, + big_vec: Option>, + inline_capacity: Option, + bucket_size: Option, + } + + /// Regular Vector API + + /// Create an empty vector using default logic to estimate `inline_capacity` and `bucket_size`, which may be + /// inaccurate. + /// This is exactly the same as empty() but is more standardized as all other data structures have new(). + public fun new(): SmartVector { + empty() + } + + #[deprecated] + /// Create an empty vector using default logic to estimate `inline_capacity` and `bucket_size`, which may be + /// inaccurate. + public fun empty(): SmartVector { + SmartVector { + inline_vec: vector[], + big_vec: option::none(), + inline_capacity: option::none(), + bucket_size: option::none(), + } + } + + /// Create an empty vector with customized config. + /// When inline_capacity = 0, SmartVector degrades to a wrapper of BigVector. + public fun empty_with_config(inline_capacity: u64, bucket_size: u64): SmartVector { + assert!(bucket_size > 0, error::invalid_argument(EZERO_BUCKET_SIZE)); + SmartVector { + inline_vec: vector[], + big_vec: option::none(), + inline_capacity: option::some(inline_capacity), + bucket_size: option::some(bucket_size), + } + } + + /// Create a vector of length 1 containing the passed in T. + public fun singleton(element: T): SmartVector { + let v = empty(); + push_back(&mut v, element); + v + } + + /// Destroy the vector `v`. + /// Aborts if `v` is not empty. + public fun destroy_empty(v: SmartVector) { + assert!(is_empty(&v), error::invalid_argument(EVECTOR_NOT_EMPTY)); + let SmartVector { inline_vec, big_vec, inline_capacity: _, bucket_size: _ } = v; + vector::destroy_empty(inline_vec); + option::destroy_none(big_vec); + } + + /// Destroy a vector completely when T has `drop`. + public fun destroy(v: SmartVector) { + clear(&mut v); + destroy_empty(v); + } + + /// Clear a vector completely when T has `drop`. + public fun clear(v: &mut SmartVector) { + v.inline_vec = vector[]; + if (option::is_some(&v.big_vec)) { + big_vector::destroy(option::extract(&mut v.big_vec)); + } + } + + /// Acquire an immutable reference to the `i`th T of the vector `v`. + /// Aborts if `i` is out of bounds. + public fun borrow(v: &SmartVector, i: u64): &T { + assert!(i < length(v), error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let inline_len = vector::length(&v.inline_vec); + if (i < inline_len) { + vector::borrow(&v.inline_vec, i) + } else { + big_vector::borrow(option::borrow(&v.big_vec), i - inline_len) + } + } + + /// Return a mutable reference to the `i`th T in the vector `v`. + /// Aborts if `i` is out of bounds. + public fun borrow_mut(v: &mut SmartVector, i: u64): &mut T { + assert!(i < length(v), error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let inline_len = vector::length(&v.inline_vec); + if (i < inline_len) { + vector::borrow_mut(&mut v.inline_vec, i) + } else { + big_vector::borrow_mut(option::borrow_mut(&mut v.big_vec), i - inline_len) + } + } + + /// Empty and destroy the other vector, and push each of the Ts in the other vector onto the lhs vector in the + /// same order as they occurred in other. + /// Disclaimer: This function may be costly. Use it at your own discretion. + public fun append(lhs: &mut SmartVector, other: SmartVector) { + let other_len = length(&other); + let half_other_len = other_len / 2; + let i = 0; + while (i < half_other_len) { + push_back(lhs, swap_remove(&mut other, i)); + i = i + 1; + }; + while (i < other_len) { + push_back(lhs, pop_back(&mut other)); + i = i + 1; + }; + destroy_empty(other); + } + + /// Add multiple values to the vector at once. + public fun add_all(v: &mut SmartVector, vals: vector) { + vector::for_each(vals, |val| { push_back(v, val); }) + } + + /// Convert a smart vector to a native vector, which is supposed to be called mostly by view functions to get an + /// atomic view of the whole vector. + /// Disclaimer: This function may be costly as the smart vector may be huge in size. Use it at your own discretion. + public fun to_vector(v: &SmartVector): vector { + let res = v.inline_vec; + if (option::is_some(&v.big_vec)) { + let big_vec = option::borrow(&v.big_vec); + vector::append(&mut res, big_vector::to_vector(big_vec)); + }; + res + } + + /// Add T `val` to the end of the vector `v`. It grows the buckets when the current buckets are full. + /// This operation will cost more gas when it adds new bucket. + public fun push_back(v: &mut SmartVector, val: T) { + let len = length(v); + let inline_len = vector::length(&v.inline_vec); + if (len == inline_len) { + let bucket_size = if (option::is_some(&v.inline_capacity)) { + if (len < *option::borrow(&v.inline_capacity)) { + vector::push_back(&mut v.inline_vec, val); + return + }; + *option::borrow(&v.bucket_size) + } else { + let val_size = size_of_val(&val); + if (val_size * (inline_len + 1) < 150 /* magic number */) { + vector::push_back(&mut v.inline_vec, val); + return + }; + let estimated_avg_size = max((size_of_val(&v.inline_vec) + val_size) / (inline_len + 1), 1); + max(1024 /* free_write_quota */ / estimated_avg_size, 1) + }; + option::fill(&mut v.big_vec, big_vector::empty(bucket_size)); + }; + big_vector::push_back(option::borrow_mut(&mut v.big_vec), val); + } + + /// Pop an T from the end of vector `v`. It does shrink the buckets if they're empty. + /// Aborts if `v` is empty. + public fun pop_back(v: &mut SmartVector): T { + assert!(!is_empty(v), error::invalid_state(EVECTOR_EMPTY)); + let big_vec_wrapper = &mut v.big_vec; + if (option::is_some(big_vec_wrapper)) { + let big_vec = option::extract(big_vec_wrapper); + let val = big_vector::pop_back(&mut big_vec); + if (big_vector::is_empty(&big_vec)) { + big_vector::destroy_empty(big_vec) + } else { + option::fill(big_vec_wrapper, big_vec); + }; + val + } else { + vector::pop_back(&mut v.inline_vec) + } + } + + /// Remove the T at index i in the vector v and return the owned value that was previously stored at i in v. + /// All Ts occurring at indices greater than i will be shifted down by 1. Will abort if i is out of bounds. + /// Disclaimer: This function may be costly. Use it at your own discretion. + public fun remove(v: &mut SmartVector, i: u64): T { + let len = length(v); + assert!(i < len, error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let inline_len = vector::length(&v.inline_vec); + if (i < inline_len) { + vector::remove(&mut v.inline_vec, i) + } else { + let big_vec_wrapper = &mut v.big_vec; + let big_vec = option::extract(big_vec_wrapper); + let val = big_vector::remove(&mut big_vec, i - inline_len); + if (big_vector::is_empty(&big_vec)) { + big_vector::destroy_empty(big_vec) + } else { + option::fill(big_vec_wrapper, big_vec); + }; + val + } + } + + /// Swap the `i`th T of the vector `v` with the last T and then pop the vector. + /// This is O(1), but does not preserve ordering of Ts in the vector. + /// Aborts if `i` is out of bounds. + public fun swap_remove(v: &mut SmartVector, i: u64): T { + let len = length(v); + assert!(i < len, error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let inline_len = vector::length(&v.inline_vec); + let big_vec_wrapper = &mut v.big_vec; + let inline_vec = &mut v.inline_vec; + if (i >= inline_len) { + let big_vec = option::extract(big_vec_wrapper); + let val = big_vector::swap_remove(&mut big_vec, i - inline_len); + if (big_vector::is_empty(&big_vec)) { + big_vector::destroy_empty(big_vec) + } else { + option::fill(big_vec_wrapper, big_vec); + }; + val + } else { + if (inline_len < len) { + let big_vec = option::extract(big_vec_wrapper); + let last_from_big_vec = big_vector::pop_back(&mut big_vec); + if (big_vector::is_empty(&big_vec)) { + big_vector::destroy_empty(big_vec) + } else { + option::fill(big_vec_wrapper, big_vec); + }; + vector::push_back(inline_vec, last_from_big_vec); + }; + vector::swap_remove(inline_vec, i) + } + } + + /// Swap the Ts at the i'th and j'th indices in the vector v. Will abort if either of i or j are out of bounds + /// for v. + public fun swap(v: &mut SmartVector, i: u64, j: u64) { + if (i > j) { + return swap(v, j, i) + }; + let len = length(v); + assert!(j < len, error::invalid_argument(EINDEX_OUT_OF_BOUNDS)); + let inline_len = vector::length(&v.inline_vec); + if (i >= inline_len) { + big_vector::swap(option::borrow_mut(&mut v.big_vec), i - inline_len, j - inline_len); + } else if (j < inline_len) { + vector::swap(&mut v.inline_vec, i, j); + } else { + let big_vec = option::borrow_mut(&mut v.big_vec); + let inline_vec = &mut v.inline_vec; + let element_i = vector::swap_remove(inline_vec, i); + let element_j = big_vector::swap_remove(big_vec, j - inline_len); + vector::push_back(inline_vec, element_j); + vector::swap(inline_vec, i, inline_len - 1); + big_vector::push_back(big_vec, element_i); + big_vector::swap(big_vec, j - inline_len, len - inline_len - 1); + } + } + + /// Reverse the order of the Ts in the vector v in-place. + /// Disclaimer: This function may be costly. Use it at your own discretion. + public fun reverse(v: &mut SmartVector) { + let inline_len = vector::length(&v.inline_vec); + let i = 0; + let new_inline_vec = vector[]; + // Push the last `inline_len` Ts into a temp vector. + while (i < inline_len) { + vector::push_back(&mut new_inline_vec, pop_back(v)); + i = i + 1; + }; + vector::reverse(&mut new_inline_vec); + // Reverse the big_vector left if exists. + if (option::is_some(&v.big_vec)) { + big_vector::reverse(option::borrow_mut(&mut v.big_vec)); + }; + // Mem::swap the two vectors. + let temp_vec = vector[]; + while (!vector::is_empty(&mut v.inline_vec)) { + vector::push_back(&mut temp_vec, vector::pop_back(&mut v.inline_vec)); + }; + vector::reverse(&mut temp_vec); + while (!vector::is_empty(&mut new_inline_vec)) { + vector::push_back(&mut v.inline_vec, vector::pop_back(&mut new_inline_vec)); + }; + vector::destroy_empty(new_inline_vec); + // Push the rest Ts originally left in inline_vector back to the end of the smart vector. + while (!vector::is_empty(&mut temp_vec)) { + push_back(v, vector::pop_back(&mut temp_vec)); + }; + vector::destroy_empty(temp_vec); + } + + /// Return `(true, i)` if `val` is in the vector `v` at index `i`. + /// Otherwise, returns `(false, 0)`. + /// Disclaimer: This function may be costly. Use it at your own discretion. + public fun index_of(v: &SmartVector, val: &T): (bool, u64) { + let (found, i) = vector::index_of(&v.inline_vec, val); + if (found) { + (true, i) + } else if (option::is_some(&v.big_vec)) { + let (found, i) = big_vector::index_of(option::borrow(&v.big_vec), val); + (found, i + vector::length(&v.inline_vec)) + } else { + (false, 0) + } + } + + /// Return true if `val` is in the vector `v`. + /// Disclaimer: This function may be costly. Use it at your own discretion. + public fun contains(v: &SmartVector, val: &T): bool { + if (is_empty(v)) return false; + let (exist, _) = index_of(v, val); + exist + } + + /// Return the length of the vector. + public fun length(v: &SmartVector): u64 { + vector::length(&v.inline_vec) + if (option::is_none(&v.big_vec)) { + 0 + } else { + big_vector::length(option::borrow(&v.big_vec)) + } + } + + /// Return `true` if the vector `v` has no Ts and `false` otherwise. + public fun is_empty(v: &SmartVector): bool { + length(v) == 0 + } + + /// Apply the function to each T in the vector, consuming it. + public inline fun for_each(v: SmartVector, f: |T|) { + aptos_std::smart_vector::reverse(&mut v); // We need to reverse the vector to consume it efficiently + aptos_std::smart_vector::for_each_reverse(v, |e| f(e)); + } + + /// Apply the function to each T in the vector, consuming it. + public inline fun for_each_reverse(v: SmartVector, f: |T|) { + let len = aptos_std::smart_vector::length(&v); + while (len > 0) { + f(aptos_std::smart_vector::pop_back(&mut v)); + len = len - 1; + }; + aptos_std::smart_vector::destroy_empty(v) + } + + /// Apply the function to a reference of each T in the vector. + public inline fun for_each_ref(v: &SmartVector, f: |&T|) { + let i = 0; + let len = aptos_std::smart_vector::length(v); + while (i < len) { + f(aptos_std::smart_vector::borrow(v, i)); + i = i + 1 + } + } + + /// Apply the function to a mutable reference to each T in the vector. + public inline fun for_each_mut(v: &mut SmartVector, f: |&mut T|) { + let i = 0; + let len = aptos_std::smart_vector::length(v); + while (i < len) { + f(aptos_std::smart_vector::borrow_mut(v, i)); + i = i + 1 + } + } + + /// Apply the function to a reference of each T in the vector with its index. + public inline fun enumerate_ref(v: &SmartVector, f: |u64, &T|) { + let i = 0; + let len = aptos_std::smart_vector::length(v); + while (i < len) { + f(i, aptos_std::smart_vector::borrow(v, i)); + i = i + 1; + }; + } + + /// Apply the function to a mutable reference of each T in the vector with its index. + public inline fun enumerate_mut(v: &mut SmartVector, f: |u64, &mut T|) { + let i = 0; + let len = length(v); + while (i < len) { + f(i, borrow_mut(v, i)); + i = i + 1; + }; + } + + /// Fold the function over the Ts. For example, `fold(vector[1,2,3], 0, f)` will execute + /// `f(f(f(0, 1), 2), 3)` + public inline fun fold( + v: SmartVector, + init: Accumulator, + f: |Accumulator, T|Accumulator + ): Accumulator { + let accu = init; + aptos_std::smart_vector::for_each(v, |elem| accu = f(accu, elem)); + accu + } + + /// Fold right like fold above but working right to left. For example, `fold(vector[1,2,3], 0, f)` will execute + /// `f(1, f(2, f(3, 0)))` + public inline fun foldr( + v: SmartVector, + init: Accumulator, + f: |T, Accumulator|Accumulator + ): Accumulator { + let accu = init; + aptos_std::smart_vector::for_each_reverse(v, |elem| accu = f(elem, accu)); + accu + } + + /// Map the function over the references of the Ts of the vector, producing a new vector without modifying the + /// original vector. + public inline fun map_ref( + v: &SmartVector, + f: |&T1|T2 + ): SmartVector { + let result = aptos_std::smart_vector::new(); + aptos_std::smart_vector::for_each_ref(v, |elem| aptos_std::smart_vector::push_back(&mut result, f(elem))); + result + } + + /// Map the function over the Ts of the vector, producing a new vector. + public inline fun map( + v: SmartVector, + f: |T1|T2 + ): SmartVector { + let result = aptos_std::smart_vector::new(); + aptos_std::smart_vector::for_each(v, |elem| push_back(&mut result, f(elem))); + result + } + + /// Filter the vector using the boolean function, removing all Ts for which `p(e)` is not true. + public inline fun filter( + v: SmartVector, + p: |&T|bool + ): SmartVector { + let result = aptos_std::smart_vector::new(); + aptos_std::smart_vector::for_each(v, |elem| { + if (p(&elem)) aptos_std::smart_vector::push_back(&mut result, elem); + }); + result + } + + public inline fun zip(v1: SmartVector, v2: SmartVector, f: |T1, T2|) { + // We need to reverse the vectors to consume it efficiently + aptos_std::smart_vector::reverse(&mut v1); + aptos_std::smart_vector::reverse(&mut v2); + aptos_std::smart_vector::zip_reverse(v1, v2, |e1, e2| f(e1, e2)); + } + + /// Apply the function to each pair of elements in the two given vectors in the reverse order, consuming them. + /// This errors out if the vectors are not of the same length. + public inline fun zip_reverse( + v1: SmartVector, + v2: SmartVector, + f: |T1, T2|, + ) { + let len = aptos_std::smart_vector::length(&v1); + // We can't use the constant ESMART_VECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(len == aptos_std::smart_vector::length(&v2), 0x20005); + while (len > 0) { + f(aptos_std::smart_vector::pop_back(&mut v1), aptos_std::smart_vector::pop_back(&mut v2)); + len = len - 1; + }; + aptos_std::smart_vector::destroy_empty(v1); + aptos_std::smart_vector::destroy_empty(v2); + } + + /// Apply the function to the references of each pair of elements in the two given vectors. + /// This errors out if the vectors are not of the same length. + public inline fun zip_ref( + v1: &SmartVector, + v2: &SmartVector, + f: |&T1, &T2|, + ) { + let len = aptos_std::smart_vector::length(v1); + // We can't use the constant ESMART_VECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(len == aptos_std::smart_vector::length(v2), 0x20005); + let i = 0; + while (i < len) { + f(aptos_std::smart_vector::borrow(v1, i), aptos_std::smart_vector::borrow(v2, i)); + i = i + 1 + } + } + + /// Apply the function to mutable references to each pair of elements in the two given vectors. + /// This errors out if the vectors are not of the same length. + public inline fun zip_mut( + v1: &mut SmartVector, + v2: &mut SmartVector, + f: |&mut T1, &mut T2|, + ) { + let i = 0; + let len = aptos_std::smart_vector::length(v1); + // We can't use the constant ESMART_VECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(len == aptos_std::smart_vector::length(v2), 0x20005); + while (i < len) { + f(aptos_std::smart_vector::borrow_mut(v1, i), aptos_std::smart_vector::borrow_mut(v2, i)); + i = i + 1 + } + } + + /// Map the function over the element pairs of the two vectors, producing a new vector. + public inline fun zip_map( + v1: SmartVector, + v2: SmartVector, + f: |T1, T2|NewT + ): SmartVector { + // We can't use the constant ESMART_VECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(aptos_std::smart_vector::length(&v1) == aptos_std::smart_vector::length(&v2), 0x20005); + + let result = aptos_std::smart_vector::new(); + aptos_std::smart_vector::zip(v1, v2, |e1, e2| push_back(&mut result, f(e1, e2))); + result + } + + /// Map the function over the references of the element pairs of two vectors, producing a new vector from the return + /// values without modifying the original vectors. + public inline fun zip_map_ref( + v1: &SmartVector, + v2: &SmartVector, + f: |&T1, &T2|NewT + ): SmartVector { + // We can't use the constant ESMART_VECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(aptos_std::smart_vector::length(v1) == aptos_std::smart_vector::length(v2), 0x20005); + + let result = aptos_std::smart_vector::new(); + aptos_std::smart_vector::zip_ref(v1, v2, |e1, e2| push_back(&mut result, f(e1, e2))); + result + } + + #[test] + fun smart_vector_test() { + let v = empty(); + let i = 0; + while (i < 100) { + push_back(&mut v, i); + i = i + 1; + }; + let j = 0; + while (j < 100) { + let val = borrow(&v, j); + assert!(*val == j, 0); + j = j + 1; + }; + while (i > 0) { + i = i - 1; + let (exist, index) = index_of(&v, &i); + let j = pop_back(&mut v); + assert!(exist, 0); + assert!(index == i, 0); + assert!(j == i, 0); + }; + while (i < 100) { + push_back(&mut v, i); + i = i + 1; + }; + let last_index = length(&v) - 1; + assert!(swap_remove(&mut v, last_index) == 99, 0); + assert!(swap_remove(&mut v, 0) == 0, 0); + while (length(&v) > 0) { + // the vector is always [N, 1, 2, ... N-1] with repetitive swap_remove(&mut v, 0) + let expected = length(&v); + let val = swap_remove(&mut v, 0); + assert!(val == expected, 0); + }; + destroy_empty(v); + } + + #[test] + fun smart_vector_append_edge_case_test() { + let v1 = empty(); + let v2 = singleton(1u64); + let v3 = empty(); + let v4 = empty(); + append(&mut v3, v4); + assert!(length(&v3) == 0, 0); + append(&mut v2, v3); + assert!(length(&v2) == 1, 0); + append(&mut v1, v2); + assert!(length(&v1) == 1, 0); + destroy(v1); + } + + #[test] + fun smart_vector_append_test() { + let v1 = empty(); + let v2 = empty(); + let i = 0; + while (i < 7) { + push_back(&mut v1, i); + i = i + 1; + }; + while (i < 25) { + push_back(&mut v2, i); + i = i + 1; + }; + append(&mut v1, v2); + assert!(length(&v1) == 25, 0); + i = 0; + while (i < 25) { + assert!(*borrow(&v1, i) == i, 0); + i = i + 1; + }; + destroy(v1); + } + + #[test] + fun smart_vector_remove_test() { + let v = empty(); + let i = 0u64; + while (i < 101) { + push_back(&mut v, i); + i = i + 1; + }; + let inline_len = vector::length(&v.inline_vec); + remove(&mut v, 100); + remove(&mut v, 90); + remove(&mut v, 80); + remove(&mut v, 70); + remove(&mut v, 60); + remove(&mut v, 50); + remove(&mut v, 40); + remove(&mut v, 30); + remove(&mut v, 20); + assert!(vector::length(&v.inline_vec) == inline_len, 0); + remove(&mut v, 10); + assert!(vector::length(&v.inline_vec) + 1 == inline_len, 0); + remove(&mut v, 0); + assert!(vector::length(&v.inline_vec) + 2 == inline_len, 0); + assert!(length(&v) == 90, 0); + + let index = 0; + i = 0; + while (i < 101) { + if (i % 10 != 0) { + assert!(*borrow(&v, index) == i, 0); + index = index + 1; + }; + i = i + 1; + }; + destroy(v); + } + + #[test] + fun smart_vector_reverse_test() { + let v = empty(); + let i = 0u64; + while (i < 10) { + push_back(&mut v, i); + i = i + 1; + }; + reverse(&mut v); + let k = 0; + while (k < 10) { + assert!(*vector::borrow(&v.inline_vec, k) == 9 - k, 0); + k = k + 1; + }; + while (i < 100) { + push_back(&mut v, i); + i = i + 1; + }; + while (!vector::is_empty(&v.inline_vec)) { + remove(&mut v, 0); + }; + reverse(&mut v); + i = 0; + let len = length(&v); + while (i + 1 < len) { + assert!( + *big_vector::borrow(option::borrow(&v.big_vec), i) == *big_vector::borrow( + option::borrow(&v.big_vec), + i + 1 + ) + 1, + 0 + ); + i = i + 1; + }; + destroy(v); + } + + #[test] + fun smart_vector_add_all_test() { + let v = empty_with_config(1, 2); + add_all(&mut v, vector[1, 2, 3, 4, 5, 6]); + assert!(length(&v) == 6, 0); + let i = 0; + while (i < 6) { + assert!(*borrow(&v, i) == i + 1, 0); + i = i + 1; + }; + destroy(v); + } + + #[test] + fun smart_vector_to_vector_test() { + let v1 = empty_with_config(7, 11); + let i = 0; + while (i < 100) { + push_back(&mut v1, i); + i = i + 1; + }; + let v2 = to_vector(&v1); + let j = 0; + while (j < 100) { + assert!(*vector::borrow(&v2, j) == j, 0); + j = j + 1; + }; + destroy(v1); + } + + #[test] + fun smart_vector_swap_test() { + let v = empty(); + let i = 0; + while (i < 101) { + push_back(&mut v, i); + i = i + 1; + }; + i = 0; + while (i < 51) { + swap(&mut v, i, 100 - i); + i = i + 1; + }; + i = 0; + while (i < 101) { + assert!(*borrow(&v, i) == 100 - i, 0); + i = i + 1; + }; + destroy(v); + } + + #[test] + fun smart_vector_index_of_test() { + let v = empty(); + let i = 0; + while (i < 100) { + push_back(&mut v, i); + let (found, idx) = index_of(&mut v, &i); + assert!(found && idx == i, 0); + i = i + 1; + }; + destroy(v); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/string_utils.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/string_utils.move new file mode 100644 index 000000000..10fbfd884 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/string_utils.move @@ -0,0 +1,148 @@ +/// A module for formatting move values as strings. +module aptos_std::string_utils { + use std::string::String; + + /// The number of values in the list does not match the number of "{}" in the format string. + const EARGS_MISMATCH: u64 = 1; + /// The format string is not valid. + const EINVALID_FORMAT: u64 = 2; + /// Formatting is not possible because the value contains delayed fields such as aggregators. + const EUNABLE_TO_FORMAT_DELAYED_FIELD: u64 = 3; + + /// Format a move value as a human readable string, + /// eg. `to_string(&1u64) == "1"`, `to_string(&false) == "false"`, `to_string(&@0x1) == "@0x1"`. + /// For vectors and structs the format is similar to rust, eg. + /// `to_string(&cons(1,2)) == "Cons { car: 1, cdr: 2 }"` and `to_string(&vector[1, 2, 3]) == "[ 1, 2, 3 ]"` + /// For vectors of u8 the output is hex encoded, eg. `to_string(&vector[1u8, 2u8, 3u8]) == "0x010203"` + /// For std::string::String the output is the string itself including quotes, eg. + /// `to_string(&std::string::utf8(b"My string")) == "\"My string\""` + public fun to_string(s: &T): String { + native_format(s, false, false, true, false) + } + + /// Format addresses as 64 zero-padded hexadecimals. + public fun to_string_with_canonical_addresses(s: &T): String { + native_format(s, false, true, true, false) + } + + /// Format emitting integers with types ie. 6u8 or 128u32. + public fun to_string_with_integer_types(s: &T): String { + native_format(s, false, true, true, false) + } + + /// Format vectors and structs with newlines and indentation. + public fun debug_string(s: &T): String { + native_format(s, true, false, false, false) + } + + /// Formatting with a rust-like format string, eg. `format2(&b"a = {}, b = {}", 1, 2) == "a = 1, b = 2"`. + public fun format1(fmt: &vector, a: T0): String { + native_format_list(fmt, &list1(a)) + } + public fun format2(fmt: &vector, a: T0, b: T1): String { + native_format_list(fmt, &list2(a, b)) + } + public fun format3(fmt: &vector, a: T0, b: T1, c: T2): String { + native_format_list(fmt, &list3(a, b, c)) + } + public fun format4(fmt: &vector, a: T0, b: T1, c: T2, d: T3): String { + native_format_list(fmt, &list4(a, b, c, d)) + } + + // Helper struct to allow passing a generic heterogeneous list of values to native_format_list. + struct Cons has copy, drop, store { + car: T, + cdr: N, + } + + struct NIL has copy, drop, store {} + + // Create a pair of values. + fun cons(car: T, cdr: N): Cons { Cons { car, cdr } } + + // Create a nil value. + fun nil(): NIL { NIL {} } + + // Create a list of values. + inline fun list1(a: T0): Cons { cons(a, nil()) } + inline fun list2(a: T0, b: T1): Cons> { cons(a, list1(b)) } + inline fun list3(a: T0, b: T1, c: T2): Cons>> { cons(a, list2(b, c)) } + inline fun list4(a: T0, b: T1, c: T2, d: T3): Cons>>> { cons(a, list3(b, c, d)) } + + // Native functions + native fun native_format(s: &T, type_tag: bool, canonicalize: bool, single_line: bool, include_int_types: bool): String; + native fun native_format_list(fmt: &vector, val: &T): String; + + #[test] + fun test_format() { + assert!(to_string(&1u64) == std::string::utf8(b"1"), 1); + assert!(to_string(&false) == std::string::utf8(b"false"), 2); + assert!(to_string(&1u256) == std::string::utf8(b"1"), 3); + assert!(to_string(&vector[1, 2, 3]) == std::string::utf8(b"[ 1, 2, 3 ]"), 4); + assert!(to_string(&cons(std::string::utf8(b"My string"),2)) == std::string::utf8(b"Cons { car: \"My string\", cdr: 2 }"), 5); + assert!(to_string(&std::option::none()) == std::string::utf8(b"None"), 6); + assert!(to_string(&std::option::some(1)) == std::string::utf8(b"Some(1)"), 7); + } + + #[test] + fun test_format_list() { + let s = format3(&b"a = {} b = {} c = {}", 1, 2, std::string::utf8(b"My string")); + assert!(s == std::string::utf8(b"a = 1 b = 2 c = \"My string\""), 1); + } + + #[test] + #[expected_failure(abort_code = EARGS_MISMATCH)] + fun test_format_list_to_many_vals() { + format4(&b"a = {} b = {} c = {}", 1, 2, 3, 4); + } + + #[test] + #[expected_failure(abort_code = EARGS_MISMATCH)] + fun test_format_list_not_enough_vals() { + format2(&b"a = {} b = {} c = {}", 1, 2); + } + + #[test] + #[expected_failure(abort_code = EARGS_MISMATCH)] + fun test_format_list_not_valid_nil() { + let l = cons(1, cons(2, cons(3, 4))); + native_format_list(&b"a = {} b = {} c = {}", &l); + } + + /// #[test_only] + struct FakeCons has copy, drop, store { + car: T, + cdr: N, + } + + #[test] + #[expected_failure(abort_code = EARGS_MISMATCH)] + fun test_format_list_not_valid_list() { + let l = cons(1, FakeCons { car: 2, cdr: cons(3, nil())}); + native_format_list(&b"a = {} b = {} c = {}", &l); + } + + #[test] + #[expected_failure(abort_code = EINVALID_FORMAT)] + fun test_format_unclosed_braces() { + format3(&b"a = {} b = {} c = {", 1, 2 ,3); + } + + #[test] + #[expected_failure(abort_code = EINVALID_FORMAT)] + fun test_format_unclosed_braces_2() { + format3(&b"a = {} b = { c = {}", 1, 2, 3); + } + + #[test] + #[expected_failure(abort_code = EINVALID_FORMAT)] + fun test_format_unopened_braces() { + format3(&b"a = } b = {} c = {}", 1, 2, 3); + } + + #[test] + fun test_format_escape_braces_works() { + let s = format3(&b"{{a = {} b = {} c = {}}}", 1, 2, 3); + assert!(s == std::string::utf8(b"{a = 1 b = 2 c = 3}"), 1); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/table.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/table.move new file mode 100644 index 000000000..dbc85209d --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/table.move @@ -0,0 +1,152 @@ +/// Type of large-scale storage tables. +/// source: https://github.com/move-language/move/blob/1b6b7513dcc1a5c866f178ca5c1e74beb2ce181e/language/extensions/move-table-extension/sources/Table.move#L1 +/// +/// It implements the Table type which supports individual table items to be represented by +/// separate global state items. The number of items and a unique handle are tracked on the table +/// struct itself, while the operations are implemented as native functions. No traversal is provided. + +module aptos_std::table { + friend aptos_std::table_with_length; + + /// Type of tables + struct Table has store { + handle: address, + } + + /// Create a new Table. + public fun new(): Table { + Table { + handle: new_table_handle(), + } + } + + /// Add a new entry to the table. Aborts if an entry for this + /// key already exists. The entry itself is not stored in the + /// table, and cannot be discovered from it. + public fun add(table: &mut Table, key: K, val: V) { + add_box>(table, key, Box { val }) + } + + /// Acquire an immutable reference to the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun borrow(table: &Table, key: K): &V { + &borrow_box>(table, key).val + } + + /// Acquire an immutable reference to the value which `key` maps to. + /// Returns specified default value if there is no entry for `key`. + public fun borrow_with_default(table: &Table, key: K, default: &V): &V { + if (!contains(table, copy key)) { + default + } else { + borrow(table, copy key) + } + } + + /// Acquire a mutable reference to the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun borrow_mut(table: &mut Table, key: K): &mut V { + &mut borrow_box_mut>(table, key).val + } + + /// Acquire a mutable reference to the value which `key` maps to. + /// Insert the pair (`key`, `default`) first if there is no entry for `key`. + public fun borrow_mut_with_default(table: &mut Table, key: K, default: V): &mut V { + if (!contains(table, copy key)) { + add(table, copy key, default) + }; + borrow_mut(table, key) + } + + /// Insert the pair (`key`, `value`) if there is no entry for `key`. + /// update the value of the entry for `key` to `value` otherwise + public fun upsert(table: &mut Table, key: K, value: V) { + if (!contains(table, copy key)) { + add(table, copy key, value) + } else { + let ref = borrow_mut(table, key); + *ref = value; + }; + } + + /// Remove from `table` and return the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun remove(table: &mut Table, key: K): V { + let Box { val } = remove_box>(table, key); + val + } + + /// Returns true iff `table` contains an entry for `key`. + public fun contains(table: &Table, key: K): bool { + contains_box>(table, key) + } + + #[test_only] + /// Testing only: allows to drop a table even if it is not empty. + public fun drop_unchecked(table: Table) { + drop_unchecked_box>(table) + } + + public(friend) fun destroy(table: Table) { + destroy_empty_box>(&table); + drop_unchecked_box>(table) + } + + #[test_only] + struct TableHolder has key { + t: Table + } + + #[test(account = @0x1)] + fun test_upsert(account: signer) { + let t = new(); + let key: u64 = 111; + let error_code: u64 = 1; + assert!(!contains(&t, key), error_code); + upsert(&mut t, key, 12); + assert!(*borrow(&t, key) == 12, error_code); + upsert(&mut t, key, 23); + assert!(*borrow(&t, key) == 23, error_code); + + move_to(&account, TableHolder { t }); + } + + #[test(account = @0x1)] + fun test_borrow_with_default(account: signer) { + let t = new(); + let key: u64 = 100; + let error_code: u64 = 1; + assert!(!contains(&t, key), error_code); + assert!(*borrow_with_default(&t, key, &12) == 12, error_code); + add(&mut t, key, 1); + assert!(*borrow_with_default(&t, key, &12) == 1, error_code); + + move_to(&account, TableHolder{ t }); + } + + // ====================================================================================================== + // Internal API + + /// Wrapper for values. Required for making values appear as resources in the implementation. + struct Box has key, drop, store { + val: V + } + + // Primitives which take as an additional type parameter `Box`, so the implementation + // can use this to determine serialization layout. + native fun new_table_handle(): address; + + native fun add_box(table: &mut Table, key: K, val: Box); + + native fun borrow_box(table: &Table, key: K): &Box; + + native fun borrow_box_mut(table: &mut Table, key: K): &mut Box; + + native fun contains_box(table: &Table, key: K): bool; + + native fun remove_box(table: &mut Table, key: K): Box; + + native fun destroy_empty_box(table: &Table); + + native fun drop_unchecked_box(table: Table); +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/table_with_length.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/table_with_length.move new file mode 100644 index 000000000..c56ff2b42 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/table_with_length.move @@ -0,0 +1,141 @@ +/// Extends Table and provides functions such as length and the ability to be destroyed + +module aptos_std::table_with_length { + use std::error; + use aptos_std::table::{Self, Table}; + + // native code raises this with error::invalid_arguments() + const EALREADY_EXISTS: u64 = 100; + // native code raises this with error::invalid_arguments() + const ENOT_FOUND: u64 = 101; + const ENOT_EMPTY: u64 = 102; + + /// Type of tables + struct TableWithLength has store { + inner: Table, + length: u64, + } + + /// Create a new Table. + public fun new(): TableWithLength { + TableWithLength { + inner: table::new(), + length: 0, + } + } + + /// Destroy a table. The table must be empty to succeed. + public fun destroy_empty(table: TableWithLength) { + assert!(table.length == 0, error::invalid_state(ENOT_EMPTY)); + let TableWithLength { inner, length: _ } = table; + table::destroy(inner) + } + + /// Add a new entry to the table. Aborts if an entry for this + /// key already exists. The entry itself is not stored in the + /// table, and cannot be discovered from it. + public fun add(table: &mut TableWithLength, key: K, val: V) { + table::add(&mut table.inner, key, val); + table.length = table.length + 1; + } + + /// Acquire an immutable reference to the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun borrow(table: &TableWithLength, key: K): &V { + table::borrow(&table.inner, key) + } + + /// Acquire a mutable reference to the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun borrow_mut(table: &mut TableWithLength, key: K): &mut V { + table::borrow_mut(&mut table.inner, key) + } + + /// Returns the length of the table, i.e. the number of entries. + public fun length(table: &TableWithLength): u64 { + table.length + } + + /// Returns true if this table is empty. + public fun empty(table: &TableWithLength): bool { + table.length == 0 + } + + /// Acquire a mutable reference to the value which `key` maps to. + /// Insert the pair (`key`, `default`) first if there is no entry for `key`. + public fun borrow_mut_with_default(table: &mut TableWithLength, key: K, default: V): &mut V { + if (table::contains(&table.inner, key)) { + table::borrow_mut(&mut table.inner, key) + } else { + table::add(&mut table.inner, key, default); + table.length = table.length + 1; + table::borrow_mut(&mut table.inner, key) + } + } + + /// Insert the pair (`key`, `value`) if there is no entry for `key`. + /// update the value of the entry for `key` to `value` otherwise + public fun upsert(table: &mut TableWithLength, key: K, value: V) { + if (!table::contains(&table.inner, key)) { + add(table, copy key, value) + } else { + let ref = table::borrow_mut(&mut table.inner, key); + *ref = value; + }; + } + + /// Remove from `table` and return the value which `key` maps to. + /// Aborts if there is no entry for `key`. + public fun remove(table: &mut TableWithLength, key: K): V { + let val = table::remove(&mut table.inner, key); + table.length = table.length - 1; + val + } + + /// Returns true iff `table` contains an entry for `key`. + public fun contains(table: &TableWithLength, key: K): bool { + table::contains(&table.inner, key) + } + + #[test_only] + /// Drop table even if not empty, only when testing. + public fun drop_unchecked(table: TableWithLength) { + // Unpack table with length, dropping length count but not + // inner table. + let TableWithLength{inner, length: _} = table; + table::drop_unchecked(inner); // Drop inner table. + } + + #[test] + /// Verify test-only drop functionality. + fun test_drop_unchecked() { + let table = new(); // Declare new table. + add(&mut table, true, false); // Add table entry. + drop_unchecked(table); // Drop table. + } + + #[test] + fun test_upsert() { + let t = new(); + // Table should not have key 0 yet + assert!(!contains(&t, 0), 1); + // This should insert key 0, with value 10, and length should be 1 + upsert(&mut t, 0, 10); + // Ensure the value is correctly set to 10 + assert!(*borrow(&t, 0) == 10, 1); + // Ensure the length is correctly set + assert!(length(&t) == 1, 1); + // Lets upsert the value to something else, and verify it's correct + upsert(&mut t, 0, 23); + assert!(*borrow(&t, 0) == 23, 1); + // Since key 0 already existed, the length should not have changed + assert!(length(&t) == 1, 1); + // If we upsert a non-existing key, the length should increase + upsert(&mut t, 1, 7); + assert!(length(&t) == 2, 1); + + remove(&mut t, 0); + remove(&mut t, 1); + destroy_empty(t); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/type_info.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/type_info.move new file mode 100644 index 000000000..2ad3bba40 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/AptosStdlib/type_info.move @@ -0,0 +1,350 @@ +module aptos_std::type_info { + use std::bcs; + use std::features; + use std::string::{Self, String}; + use std::vector; + + // + // Error codes + // + + const E_NATIVE_FUN_NOT_AVAILABLE: u64 = 1; + + // + // Structs + // + + struct TypeInfo has copy, drop, store { + account_address: address, + module_name: vector, + struct_name: vector, + } + + // + // Public functions + // + + public fun account_address(type_info: &TypeInfo): address { + type_info.account_address + } + + public fun module_name(type_info: &TypeInfo): vector { + type_info.module_name + } + + public fun struct_name(type_info: &TypeInfo): vector { + type_info.struct_name + } + + /// Returns the current chain ID, mirroring what `aptos_framework::chain_id::get()` would return, except in `#[test]` + /// functions, where this will always return `4u8` as the chain ID, whereas `aptos_framework::chain_id::get()` will + /// return whichever ID was passed to `aptos_framework::chain_id::initialize_for_test()`. + public fun chain_id(): u8 { + if (!features::aptos_stdlib_chain_id_enabled()) { + abort(std::error::invalid_state(E_NATIVE_FUN_NOT_AVAILABLE)) + }; + + chain_id_internal() + } + + /// Return the `TypeInfo` struct containing for the type `T`. + public native fun type_of(): TypeInfo; + + /// Return the human readable string for the type, including the address, module name, and any type arguments. + /// Example: 0x1::coin::CoinStore<0x1::aptos_coin::AptosCoin> + /// Or: 0x1::table::Table<0x1::string::String, 0x1::string::String> + public native fun type_name(): String; + + native fun chain_id_internal(): u8; + + /// Return the BCS size, in bytes, of value at `val_ref`. + /// + /// See the [BCS spec](https://github.com/diem/bcs) + /// + /// See `test_size_of_val()` for an analysis of common types and + /// nesting patterns, as well as `test_size_of_val_vectors()` for an + /// analysis of vector size dynamism. + public fun size_of_val(val_ref: &T): u64 { + // Return vector length of vectorized BCS representation. + vector::length(&bcs::to_bytes(val_ref)) + } + + #[test_only] + use aptos_std::table::Table; + + #[test] + fun test_type_of() { + let type_info = type_of(); + assert!(account_address(&type_info) == @aptos_std, 0); + assert!(module_name(&type_info) == b"type_info", 1); + assert!(struct_name(&type_info) == b"TypeInfo", 2); + } + + #[test] + fun test_type_of_with_type_arg() { + let type_info = type_of>(); + assert!(account_address(&type_info) == @aptos_std, 0); + assert!(module_name(&type_info) == b"table", 1); + assert!(struct_name(&type_info) == b"Table<0x1::string::String, 0x1::string::String>", 2); + } + + #[test(fx = @std)] + fun test_chain_id(fx: signer) { + // We need to enable the feature in order for the native call to be allowed. + features::change_feature_flags_for_testing(&fx, vector[features::get_aptos_stdlib_chain_id_feature()], vector[]); + + // The testing environment chain ID is 4u8. + assert!(chain_id() == 4u8, 1); + } + + #[test] + fun test_type_name() { + + + assert!(type_name() == string::utf8(b"bool"), 0); + assert!(type_name() == string::utf8(b"u8"), 1); + assert!(type_name() == string::utf8(b"u64"), 2); + assert!(type_name() == string::utf8(b"u128"), 3); + assert!(type_name

() == string::utf8(b"address"), 4); + assert!(type_name() == string::utf8(b"signer"), 5); + + // vector + assert!(type_name>() == string::utf8(b"vector"), 6); + assert!(type_name>>() == string::utf8(b"vector>"), 7); + assert!(type_name>>() == string::utf8(b"vector>"), 8); + + + // struct + assert!(type_name() == string::utf8(b"0x1::type_info::TypeInfo"), 9); + assert!(type_name< + Table< + TypeInfo, + Table> + > + >() == string::utf8(b"0x1::table::Table<0x1::type_info::TypeInfo, 0x1::table::Table>>"), 10); + } + + #[verify_only] + fun verify_type_of() { + let type_info = type_of(); + let account_address = account_address(&type_info); + let module_name = module_name(&type_info); + let struct_name = struct_name(&type_info); + spec { + assert account_address == @aptos_std; + assert module_name == b"type_info"; + assert struct_name == b"TypeInfo"; + }; + } + + #[verify_only] + fun verify_type_of_generic() { + let type_info = type_of(); + let account_address = account_address(&type_info); + let module_name = module_name(&type_info); + let struct_name = struct_name(&type_info); + spec { + assert account_address == type_of().account_address; + assert module_name == type_of().module_name; + assert struct_name == type_of().struct_name; + }; + } + spec verify_type_of_generic { + aborts_if !spec_is_struct(); + } + + #[test_only] + struct CustomType has drop {} + + #[test_only] + struct SimpleStruct has copy, drop { + field: u8 + } + + #[test_only] + struct ComplexStruct has copy, drop { + field_1: bool, + field_2: u8, + field_3: u64, + field_4: u128, + field_5: SimpleStruct, + field_6: T + } + + #[test_only] + struct TwoBools has drop { + bool_1: bool, + bool_2: bool + } + + #[test_only] + use std::option; + + #[test(account = @0x0)] + /// Ensure valid returns across native types and nesting schemas. + fun test_size_of_val( + account: &signer + ) { + assert!(size_of_val(&false) == 1, 0); // Bool takes 1 byte. + assert!(size_of_val(&0) == 1, 0); // u8 takes 1 byte. + assert!(size_of_val(&0) == 8, 0); // u64 takes 8 bytes. + assert!(size_of_val(&0) == 16, 0); // u128 takes 16 bytes. + // Address is a u256. + assert!(size_of_val(&@0x0) == 32, 0); + assert!(size_of_val(account) == 32, 0); // Signer is an address. + // Assert custom type without fields has size 1. + assert!(size_of_val(&CustomType{}) == 1, 0); + // Declare a simple struct with a 1-byte field. + let simple_struct = SimpleStruct{field: 0}; + // Assert size is indicated as 1 byte. + assert!(size_of_val(&simple_struct) == 1, 0); + let complex_struct = ComplexStruct{ + field_1: false, + field_2: 0, + field_3: 0, + field_4: 0, + field_5: simple_struct, + field_6: 0 + }; // Declare a complex struct with another nested inside. + // Assert size is bytewise sum of components. + assert!(size_of_val(&complex_struct) == (1 + 1 + 8 + 16 + 1 + 16), 0); + // Declare a struct with two boolean values. + let two_bools = TwoBools{bool_1: false, bool_2: false}; + // Assert size is two bytes. + assert!(size_of_val(&two_bools) == 2, 0); + // Declare an empty vector of element type u64. + let empty_vector_u64 = vector::empty(); + // Declare an empty vector of element type u128. + let empty_vector_u128 = vector::empty(); + // Assert size is 1 byte regardless of underlying element type. + assert!(size_of_val(&empty_vector_u64) == 1, 0); + // Assert size is 1 byte regardless of underlying element type. + assert!(size_of_val(&empty_vector_u128) == 1, 0); + // Declare a bool in a vector. + let bool_vector = vector::singleton(false); + // Push back another bool. + vector::push_back(&mut bool_vector, false); + // Assert size is 3 bytes (1 per element, 1 for base vector). + assert!(size_of_val(&bool_vector) == 3, 0); + // Get a some option, which is implemented as a vector. + let u64_option = option::some(0); + // Assert size is 9 bytes (8 per element, 1 for base vector). + assert!(size_of_val(&u64_option) == 9, 0); + option::extract(&mut u64_option); // Remove the value inside. + // Assert size reduces to 1 byte. + assert!(size_of_val(&u64_option) == 1, 0); + } + + #[test] + /// Verify returns for base vector size at different lengths, with + /// different underlying fixed-size elements. + /// + /// For a vector of length n containing fixed-size elements, the + /// size of the vector is b + n * s bytes, where s is the size of an + /// element in bytes, and b is a "base size" in bytes that varies + /// with n. + /// + /// The base size is an artifact of vector BCS encoding, namely, + /// with b leading bytes that declare how many elements are in the + /// vector. Each such leading byte has a reserved control bit (e.g. + /// is this the last leading byte?), such that 7 bits per leading + /// byte remain for the actual element count. Hence for a single + /// leading byte, the maximum element count that can be described is + /// (2 ^ 7) - 1, and for b leading bytes, the maximum element count + /// that can be described is (2 ^ 7) ^ b - 1: + /// + /// * b = 1, n < 128 + /// * b = 2, 128 <= n < 16384 + /// * b = 3, 16384 <= n < 2097152 + /// * ... + /// * (2 ^ 7) ^ (b - 1) <= n < (2 ^ 7) ^ b + /// * ... + /// * b = 9, 72057594037927936 <= n < 9223372036854775808 + /// * b = 10, 9223372036854775808 <= n < 18446744073709551616 + /// + /// Note that the upper bound on n for b = 10 is 2 ^ 64, rather than + /// (2 ^ 7) ^ 10 - 1, because the former, lower figure is the + /// maximum number of elements that can be stored in a vector in the + /// first place, e.g. U64_MAX. + /// + /// In practice b > 2 is unlikely to be encountered. + fun test_size_of_val_vectors() { + // Declare vector base sizes. + let (base_size_1, base_size_2, base_size_3) = (1, 2, 3); + // A base size of 1 applies for 127 or less elements. + let n_elems_cutoff_1 = 127; // (2 ^ 7) ^ 1 - 1. + // A base size of 2 applies for 128 < n <= 16384 elements. + let n_elems_cutoff_2 = 16383; // (2 ^ 7) ^ 2 - 1. + let vector_u64 = vector::empty(); // Declare empty vector. + let null_element = 0; // Declare a null element. + // Get element size. + let element_size = size_of_val(&null_element); + // Vector size is 1 byte when length is 0. + assert!(size_of_val(&vector_u64) == base_size_1, 0); + let i = 0; // Declare loop counter. + while (i < n_elems_cutoff_1) { // Iterate until first cutoff: + // Add an element. + vector::push_back(&mut vector_u64, null_element); + i = i + 1; // Increment counter. + }; + // Vector base size is still 1 byte. + assert!(size_of_val(&vector_u64) - element_size * i == base_size_1, 0); + // Add another element, exceeding the cutoff. + vector::push_back(&mut vector_u64, null_element); + i = i + 1; // Increment counter. + // Vector base size is now 2 bytes. + assert!(size_of_val(&vector_u64) - element_size * i == base_size_2, 0); + while (i < n_elems_cutoff_2) { // Iterate until second cutoff: + // Add an element. + vector::push_back(&mut vector_u64, null_element); + i = i + 1; // Increment counter. + }; + // Vector base size is still 2 bytes. + assert!(size_of_val(&vector_u64) - element_size * i == base_size_2, 0); + // Add another element, exceeding the cutoff. + vector::push_back(&mut vector_u64, null_element); + i = i + 1; // Increment counter. + // Vector base size is now 3 bytes. + assert!(size_of_val(&vector_u64) - element_size * i == base_size_3, 0); + // Repeat for custom struct. + let vector_complex = vector::empty>(); + // Declare a null element. + let null_element = ComplexStruct{ + field_1: false, + field_2: 0, + field_3: 0, + field_4: 0, + field_5: SimpleStruct{field: 0}, + field_6: @0x0 + }; + element_size = size_of_val(&null_element); // Get element size. + // Vector size is 1 byte when length is 0. + assert!(size_of_val(&vector_complex) == base_size_1, 0); + i = 0; // Re-initialize loop counter. + while (i < n_elems_cutoff_1) { // Iterate until first cutoff: + // Add an element. + vector::push_back(&mut vector_complex, copy null_element); + i = i + 1; // Increment counter. + }; + assert!( // Vector base size is still 1 byte. + size_of_val(&vector_complex) - element_size * i == base_size_1, 0); + // Add another element, exceeding the cutoff. + vector::push_back(&mut vector_complex, null_element); + i = i + 1; // Increment counter. + assert!( // Vector base size is now 2 bytes. + size_of_val(&vector_complex) - element_size * i == base_size_2, 0); + while (i < n_elems_cutoff_2) { // Iterate until second cutoff: + // Add an element. + vector::push_back(&mut vector_complex, copy null_element); + i = i + 1; // Increment counter. + }; + assert!( // Vector base size is still 2 bytes. + size_of_val(&vector_complex) - element_size * i == base_size_2, 0); + // Add another element, exceeding the cutoff. + vector::push_back(&mut vector_complex, null_element); + i = i + 1; // Increment counter. + assert!( // Vector base size is now 3 bytes. + size_of_val(&vector_complex) - element_size * i == base_size_3, 0); + } + +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/acl.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/acl.move new file mode 100644 index 000000000..5cf71e635 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/acl.move @@ -0,0 +1,46 @@ +/// Access control list (acl) module. An acl is a list of account addresses who +/// have the access permission to a certain object. +/// This module uses a `vector` to represent the list, but can be refactored to +/// use a "set" instead when it's available in the language in the future. + +module std::acl { + use std::vector; + use std::error; + + /// The ACL already contains the address. + const ECONTAIN: u64 = 0; + /// The ACL does not contain the address. + const ENOT_CONTAIN: u64 = 1; + + struct ACL has store, drop, copy { + list: vector
+ } + + /// Return an empty ACL. + public fun empty(): ACL { + ACL{ list: vector::empty
() } + } + + /// Add the address to the ACL. + public fun add(acl: &mut ACL, addr: address) { + assert!(!vector::contains(&mut acl.list, &addr), error::invalid_argument(ECONTAIN)); + vector::push_back(&mut acl.list, addr); + } + + /// Remove the address from the ACL. + public fun remove(acl: &mut ACL, addr: address) { + let (found, index) = vector::index_of(&mut acl.list, &addr); + assert!(found, error::invalid_argument(ENOT_CONTAIN)); + vector::remove(&mut acl.list, index); + } + + /// Return true iff the ACL contains the address. + public fun contains(acl: &ACL, addr: address): bool { + vector::contains(&acl.list, &addr) + } + + /// assert! that the ACL has the address. + public fun assert_contains(acl: &ACL, addr: address) { + assert!(contains(acl, addr), error::invalid_argument(ENOT_CONTAIN)); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/bcs.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/bcs.move new file mode 100644 index 000000000..79b4c9889 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/bcs.move @@ -0,0 +1,17 @@ +/// Utility for converting a Move value to its binary representation in BCS (Binary Canonical +/// Serialization). BCS is the binary encoding for Move resources and other non-module values +/// published on-chain. See https://github.com/aptos-labs/bcs#binary-canonical-serialization-bcs for more +/// details on BCS. +module std::bcs { + /// Return the binary representation of `v` in BCS (Binary Canonical Serialization) format + native public fun to_bytes(v: &MoveValue): vector; + + // ============================== + // Module Specification + spec module {} // switch to module documentation context + + spec module { + /// Native function which is defined in the prover's prelude. + native fun serialize(v: &MoveValue): vector; + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/bit_vector.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/bit_vector.move new file mode 100644 index 000000000..7bf3e2269 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/bit_vector.move @@ -0,0 +1,239 @@ +module std::bit_vector { + use std::vector; + + /// The provided index is out of bounds + const EINDEX: u64 = 0x20000; + /// An invalid length of bitvector was given + const ELENGTH: u64 = 0x20001; + + const WORD_SIZE: u64 = 1; + /// The maximum allowed bitvector size + const MAX_SIZE: u64 = 1024; + + spec BitVector { + invariant length == len(bit_field); + } + + struct BitVector has copy, drop, store { + length: u64, + bit_field: vector, + } + + public fun new(length: u64): BitVector { + assert!(length > 0, ELENGTH); + assert!(length < MAX_SIZE, ELENGTH); + let counter = 0; + let bit_field = vector::empty(); + while ({spec { + invariant counter <= length; + invariant len(bit_field) == counter; + }; + (counter < length)}) { + vector::push_back(&mut bit_field, false); + counter = counter + 1; + }; + spec { + assert counter == length; + assert len(bit_field) == length; + }; + + BitVector { + length, + bit_field, + } + } + spec new { + include NewAbortsIf; + ensures result.length == length; + ensures len(result.bit_field) == length; + } + spec schema NewAbortsIf { + length: u64; + aborts_if length <= 0 with ELENGTH; + aborts_if length >= MAX_SIZE with ELENGTH; + } + + /// Set the bit at `bit_index` in the `bitvector` regardless of its previous state. + public fun set(bitvector: &mut BitVector, bit_index: u64) { + assert!(bit_index < vector::length(&bitvector.bit_field), EINDEX); + let x = vector::borrow_mut(&mut bitvector.bit_field, bit_index); + *x = true; + } + spec set { + include SetAbortsIf; + ensures bitvector.bit_field[bit_index]; + } + spec schema SetAbortsIf { + bitvector: BitVector; + bit_index: u64; + aborts_if bit_index >= length(bitvector) with EINDEX; + } + + /// Unset the bit at `bit_index` in the `bitvector` regardless of its previous state. + public fun unset(bitvector: &mut BitVector, bit_index: u64) { + assert!(bit_index < vector::length(&bitvector.bit_field), EINDEX); + let x = vector::borrow_mut(&mut bitvector.bit_field, bit_index); + *x = false; + } + spec unset { + include UnsetAbortsIf; + ensures !bitvector.bit_field[bit_index]; + } + spec schema UnsetAbortsIf { + bitvector: BitVector; + bit_index: u64; + aborts_if bit_index >= length(bitvector) with EINDEX; + } + + /// Shift the `bitvector` left by `amount`. If `amount` is greater than the + /// bitvector's length the bitvector will be zeroed out. + public fun shift_left(bitvector: &mut BitVector, amount: u64) { + if (amount >= bitvector.length) { + vector::for_each_mut(&mut bitvector.bit_field, |elem| { + *elem = false; + }); + } else { + let i = amount; + + while (i < bitvector.length) { + if (is_index_set(bitvector, i)) set(bitvector, i - amount) + else unset(bitvector, i - amount); + i = i + 1; + }; + + i = bitvector.length - amount; + + while (i < bitvector.length) { + unset(bitvector, i); + i = i + 1; + }; + } + } + spec shift_left { + // TODO: set to false because data invariant cannot be proved with inline function. Will remove it once inline is supported + pragma verify = false; + } + + /// Return the value of the bit at `bit_index` in the `bitvector`. `true` + /// represents "1" and `false` represents a 0 + public fun is_index_set(bitvector: &BitVector, bit_index: u64): bool { + assert!(bit_index < vector::length(&bitvector.bit_field), EINDEX); + *vector::borrow(&bitvector.bit_field, bit_index) + } + spec is_index_set { + include IsIndexSetAbortsIf; + ensures result == bitvector.bit_field[bit_index]; + } + spec schema IsIndexSetAbortsIf { + bitvector: BitVector; + bit_index: u64; + aborts_if bit_index >= length(bitvector) with EINDEX; + } + spec fun spec_is_index_set(bitvector: BitVector, bit_index: u64): bool { + if (bit_index >= length(bitvector)) { + false + } else { + bitvector.bit_field[bit_index] + } + } + + /// Return the length (number of usable bits) of this bitvector + public fun length(bitvector: &BitVector): u64 { + vector::length(&bitvector.bit_field) + } + + /// Returns the length of the longest sequence of set bits starting at (and + /// including) `start_index` in the `bitvector`. If there is no such + /// sequence, then `0` is returned. + public fun longest_set_sequence_starting_at(bitvector: &BitVector, start_index: u64): u64 { + assert!(start_index < bitvector.length, EINDEX); + let index = start_index; + + // Find the greatest index in the vector such that all indices less than it are set. + while ({ + spec { + invariant index >= start_index; + invariant index == start_index || is_index_set(bitvector, index - 1); + invariant index == start_index || index - 1 < vector::length(bitvector.bit_field); + invariant forall j in start_index..index: is_index_set(bitvector, j); + invariant forall j in start_index..index: j < vector::length(bitvector.bit_field); + }; + index < bitvector.length + }) { + if (!is_index_set(bitvector, index)) break; + index = index + 1; + }; + + index - start_index + } + + spec longest_set_sequence_starting_at(bitvector: &BitVector, start_index: u64): u64 { + aborts_if start_index >= bitvector.length; + ensures forall i in start_index..result: is_index_set(bitvector, i); + } + + #[test_only] + public fun word_size(): u64 { + WORD_SIZE + } + + #[verify_only] + public fun shift_left_for_verification_only(bitvector: &mut BitVector, amount: u64) { + if (amount >= bitvector.length) { + let len = vector::length(&bitvector.bit_field); + let i = 0; + while ({ + spec { + invariant len == bitvector.length; + invariant forall k in 0..i: !bitvector.bit_field[k]; + invariant forall k in i..bitvector.length: bitvector.bit_field[k] == old(bitvector).bit_field[k]; + }; + i < len + }) { + let elem = vector::borrow_mut(&mut bitvector.bit_field, i); + *elem = false; + i = i + 1; + }; + } else { + let i = amount; + + while ({ + spec { + invariant i >= amount; + invariant bitvector.length == old(bitvector).length; + invariant forall j in amount..i: old(bitvector).bit_field[j] == bitvector.bit_field[j - amount]; + invariant forall j in (i-amount)..bitvector.length : old(bitvector).bit_field[j] == bitvector.bit_field[j]; + invariant forall k in 0..i-amount: bitvector.bit_field[k] == old(bitvector).bit_field[k + amount]; + }; + i < bitvector.length + }) { + if (is_index_set(bitvector, i)) set(bitvector, i - amount) + else unset(bitvector, i - amount); + i = i + 1; + }; + + + i = bitvector.length - amount; + + while ({ + spec { + invariant forall j in bitvector.length - amount..i: !bitvector.bit_field[j]; + invariant forall k in 0..bitvector.length - amount: bitvector.bit_field[k] == old(bitvector).bit_field[k + amount]; + invariant i >= bitvector.length - amount; + }; + i < bitvector.length + }) { + unset(bitvector, i); + i = i + 1; + } + } + } + spec shift_left_for_verification_only { + aborts_if false; + ensures amount >= bitvector.length ==> (forall k in 0..bitvector.length: !bitvector.bit_field[k]); + ensures amount < bitvector.length ==> + (forall i in bitvector.length - amount..bitvector.length: !bitvector.bit_field[i]); + ensures amount < bitvector.length ==> + (forall i in 0..bitvector.length - amount: bitvector.bit_field[i] == old(bitvector).bit_field[i + amount]); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/error.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/error.move new file mode 100644 index 000000000..1facaf01d --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/error.move @@ -0,0 +1,88 @@ +/// This module defines a set of canonical error codes which are optional to use by applications for the +/// `abort` and `assert!` features. +/// +/// Canonical error codes use the 3 lowest bytes of the u64 abort code range (the upper 5 bytes are free for other use). +/// Of those, the highest byte represents the *error category* and the lower two bytes the *error reason*. +/// Given an error category `0x1` and a reason `0x3`, a canonical abort code looks as `0x10003`. +/// +/// A module can use a canonical code with a constant declaration of the following form: +/// +/// ``` +/// /// An invalid ASCII character was encountered when creating a string. +/// const EINVALID_CHARACTER: u64 = 0x010003; +/// ``` +/// +/// This code is both valid in the worlds with and without canonical errors. It can be used as a plain module local +/// error reason understand by the existing error map tooling, or as a canonical code. +/// +/// The actual canonical categories have been adopted from Google's canonical error codes, which in turn are derived +/// from Unix error codes [see here](https://cloud.google.com/apis/design/errors#handling_errors). Each code has an +/// associated HTTP error code which can be used in REST apis. The mapping from error code to http code is not 1:1; +/// error codes here are a bit richer than HTTP codes. +module std::error { + + /// Caller specified an invalid argument (http: 400) + const INVALID_ARGUMENT: u64 = 0x1; + + /// An input or result of a computation is out of range (http: 400) + const OUT_OF_RANGE: u64 = 0x2; + + /// The system is not in a state where the operation can be performed (http: 400) + const INVALID_STATE: u64 = 0x3; + + /// Request not authenticated due to missing, invalid, or expired auth token (http: 401) + const UNAUTHENTICATED: u64 = 0x4; + + /// client does not have sufficient permission (http: 403) + const PERMISSION_DENIED: u64 = 0x5; + + /// A specified resource is not found (http: 404) + const NOT_FOUND: u64 = 0x6; + + /// Concurrency conflict, such as read-modify-write conflict (http: 409) + const ABORTED: u64 = 0x7; + + /// The resource that a client tried to create already exists (http: 409) + const ALREADY_EXISTS: u64 = 0x8; + + /// Out of gas or other forms of quota (http: 429) + const RESOURCE_EXHAUSTED: u64 = 0x9; + + /// Request cancelled by the client (http: 499) + const CANCELLED: u64 = 0xA; + + /// Internal error (http: 500) + const INTERNAL: u64 = 0xB; + + /// Feature not implemented (http: 501) + const NOT_IMPLEMENTED: u64 = 0xC; + + /// The service is currently unavailable. Indicates that a retry could solve the issue (http: 503) + const UNAVAILABLE: u64 = 0xD; + + /// Construct a canonical error code from a category and a reason. + public fun canonical(category: u64, reason: u64): u64 { + (category << 16) + reason + } + spec canonical { + pragma opaque = true; + let shl_res = category << 16; + ensures [concrete] result == shl_res + reason; + aborts_if [abstract] false; + ensures [abstract] result == category; + } + + /// Functions to construct a canonical error code of the given category. + public fun invalid_argument(r: u64): u64 { canonical(INVALID_ARGUMENT, r) } + public fun out_of_range(r: u64): u64 { canonical(OUT_OF_RANGE, r) } + public fun invalid_state(r: u64): u64 { canonical(INVALID_STATE, r) } + public fun unauthenticated(r: u64): u64 { canonical(UNAUTHENTICATED, r) } + public fun permission_denied(r: u64): u64 { canonical(PERMISSION_DENIED, r) } + public fun not_found(r: u64): u64 { canonical(NOT_FOUND, r) } + public fun aborted(r: u64): u64 { canonical(ABORTED, r) } + public fun already_exists(r: u64): u64 { canonical(ALREADY_EXISTS, r) } + public fun resource_exhausted(r: u64): u64 { canonical(RESOURCE_EXHAUSTED, r) } + public fun internal(r: u64): u64 { canonical(INTERNAL, r) } + public fun not_implemented(r: u64): u64 { canonical(NOT_IMPLEMENTED, r) } + public fun unavailable(r: u64): u64 { canonical(UNAVAILABLE, r) } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/features.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/features.move new file mode 100644 index 000000000..6732f9114 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/features.move @@ -0,0 +1,794 @@ +/// Defines feature flags for Aptos. Those are used in Aptos specific implementations of features in +/// the Move stdlib, the Aptos stdlib, and the Aptos framework. +/// +/// ============================================================================================ +/// Feature Flag Definitions +/// +/// Each feature flag should come with documentation which justifies the need of the flag. +/// Introduction of a new feature flag requires approval of framework owners. Be frugal when +/// introducing new feature flags, as too many can make it hard to understand the code. +/// +/// Each feature flag should come with a specification of a lifetime: +/// +/// - a *transient* feature flag is only needed until a related code rollout has happened. This +/// is typically associated with the introduction of new native Move functions, and is only used +/// from Move code. The owner of this feature is obliged to remove it once this can be done. +/// +/// - a *permanent* feature flag is required to stay around forever. Typically, those flags guard +/// behavior in native code, and the behavior with or without the feature need to be preserved +/// for playback. +/// +/// Note that removing a feature flag still requires the function which tests for the feature +/// (like `code_dependency_check_enabled` below) to stay around for compatibility reasons, as it +/// is a public function. However, once the feature flag is disabled, those functions can constantly +/// return true. +module std::features { + use std::error; + use std::signer; + use std::vector; + + const EINVALID_FEATURE: u64 = 1; + const EAPI_DISABLED: u64 = 2; + /// Deployed to production, and disabling is deprecated. + const EFEATURE_CANNOT_BE_DISABLED: u64 = 3; + + // -------------------------------------------------------------------------------------------- + // Code Publishing + + /// Whether validation of package dependencies is enabled, and the related native function is + /// available. This is needed because of introduction of a new native function. + /// Lifetime: transient + const CODE_DEPENDENCY_CHECK: u64 = 1; + + public fun code_dependency_check_enabled(): bool acquires Features { + is_enabled(CODE_DEPENDENCY_CHECK) + } + + /// Whether during upgrade compatibility checking, friend functions should be treated similar like + /// private functions. + /// Lifetime: permanent + const TREAT_FRIEND_AS_PRIVATE: u64 = 2; + + public fun treat_friend_as_private(): bool acquires Features { + is_enabled(TREAT_FRIEND_AS_PRIVATE) + } + + /// Whether the new SHA2-512, SHA3-512 and RIPEMD-160 hash function natives are enabled. + /// This is needed because of the introduction of new native functions. + /// Lifetime: transient + const SHA_512_AND_RIPEMD_160_NATIVES: u64 = 3; + + public fun get_sha_512_and_ripemd_160_feature(): u64 { SHA_512_AND_RIPEMD_160_NATIVES } + + public fun sha_512_and_ripemd_160_enabled(): bool acquires Features { + is_enabled(SHA_512_AND_RIPEMD_160_NATIVES) + } + + /// Whether the new `aptos_stdlib::type_info::chain_id()` native for fetching the chain ID is enabled. + /// This is needed because of the introduction of a new native function. + /// Lifetime: transient + const APTOS_STD_CHAIN_ID_NATIVES: u64 = 4; + + public fun get_aptos_stdlib_chain_id_feature(): u64 { APTOS_STD_CHAIN_ID_NATIVES } + + public fun aptos_stdlib_chain_id_enabled(): bool acquires Features { + is_enabled(APTOS_STD_CHAIN_ID_NATIVES) + } + + /// Whether to allow the use of binary format version v6. + /// Lifetime: transient + const VM_BINARY_FORMAT_V6: u64 = 5; + + public fun get_vm_binary_format_v6(): u64 { VM_BINARY_FORMAT_V6 } + + public fun allow_vm_binary_format_v6(): bool acquires Features { + is_enabled(VM_BINARY_FORMAT_V6) + } + + /// Whether gas fees are collected and distributed to the block proposers. + /// Lifetime: transient + const COLLECT_AND_DISTRIBUTE_GAS_FEES: u64 = 6; + + public fun get_collect_and_distribute_gas_fees_feature(): u64 { COLLECT_AND_DISTRIBUTE_GAS_FEES } + + public fun collect_and_distribute_gas_fees(): bool acquires Features { + is_enabled(COLLECT_AND_DISTRIBUTE_GAS_FEES) + } + + /// Whether the new `aptos_stdlib::multi_ed25519::public_key_validate_internal_v2()` native is enabled. + /// This is needed because of the introduction of a new native function. + /// Lifetime: transient + const MULTI_ED25519_PK_VALIDATE_V2_NATIVES: u64 = 7; + + public fun multi_ed25519_pk_validate_v2_feature(): u64 { MULTI_ED25519_PK_VALIDATE_V2_NATIVES } + + public fun multi_ed25519_pk_validate_v2_enabled(): bool acquires Features { + is_enabled(MULTI_ED25519_PK_VALIDATE_V2_NATIVES) + } + + /// Whether the new BLAKE2B-256 hash function native is enabled. + /// This is needed because of the introduction of new native function(s). + /// Lifetime: transient + const BLAKE2B_256_NATIVE: u64 = 8; + + public fun get_blake2b_256_feature(): u64 { BLAKE2B_256_NATIVE } + + public fun blake2b_256_enabled(): bool acquires Features { + is_enabled(BLAKE2B_256_NATIVE) + } + + /// Whether resource groups are enabled. + /// This is needed because of new attributes for structs and a change in storage representation. + const RESOURCE_GROUPS: u64 = 9; + + public fun get_resource_groups_feature(): u64 { RESOURCE_GROUPS } + + public fun resource_groups_enabled(): bool acquires Features { + is_enabled(RESOURCE_GROUPS) + } + + /// Whether multisig accounts (different from accounts with multi-ed25519 auth keys) are enabled. + const MULTISIG_ACCOUNTS: u64 = 10; + + public fun get_multisig_accounts_feature(): u64 { MULTISIG_ACCOUNTS } + + public fun multisig_accounts_enabled(): bool acquires Features { + is_enabled(MULTISIG_ACCOUNTS) + } + + /// Whether delegation pools are enabled. + /// Lifetime: transient + const DELEGATION_POOLS: u64 = 11; + + public fun get_delegation_pools_feature(): u64 { DELEGATION_POOLS } + + public fun delegation_pools_enabled(): bool acquires Features { + is_enabled(DELEGATION_POOLS) + } + + /// Whether generic algebra basic operation support in `crypto_algebra.move` are enabled. + /// + /// Lifetime: transient + const CRYPTOGRAPHY_ALGEBRA_NATIVES: u64 = 12; + + public fun get_cryptography_algebra_natives_feature(): u64 { CRYPTOGRAPHY_ALGEBRA_NATIVES } + + public fun cryptography_algebra_enabled(): bool acquires Features { + is_enabled(CRYPTOGRAPHY_ALGEBRA_NATIVES) + } + + /// Whether the generic algebra implementation for BLS12381 operations are enabled. + /// + /// Lifetime: transient + const BLS12_381_STRUCTURES: u64 = 13; + + public fun get_bls12_381_strutures_feature(): u64 { BLS12_381_STRUCTURES } + + public fun bls12_381_structures_enabled(): bool acquires Features { + is_enabled(BLS12_381_STRUCTURES) + } + + + /// Whether native_public_key_validate aborts when a public key of the wrong length is given + /// Lifetime: ephemeral + const ED25519_PUBKEY_VALIDATE_RETURN_FALSE_WRONG_LENGTH: u64 = 14; + + /// Whether struct constructors are enabled + /// + /// Lifetime: transient + const STRUCT_CONSTRUCTORS: u64 = 15; + + /// Whether reward rate decreases periodically. + /// Lifetime: transient + const PERIODICAL_REWARD_RATE_DECREASE: u64 = 16; + + public fun get_periodical_reward_rate_decrease_feature(): u64 { PERIODICAL_REWARD_RATE_DECREASE } + + public fun periodical_reward_rate_decrease_enabled(): bool acquires Features { + is_enabled(PERIODICAL_REWARD_RATE_DECREASE) + } + + /// Whether enable paritial governance voting on aptos_governance. + /// Lifetime: transient + const PARTIAL_GOVERNANCE_VOTING: u64 = 17; + + public fun get_partial_governance_voting(): u64 { PARTIAL_GOVERNANCE_VOTING } + + public fun partial_governance_voting_enabled(): bool acquires Features { + is_enabled(PARTIAL_GOVERNANCE_VOTING) + } + + /// Charge invariant violation error. + /// Lifetime: transient + const CHARGE_INVARIANT_VIOLATION: u64 = 20; + + /// Whether enable paritial governance voting on delegation_pool. + /// Lifetime: transient + const DELEGATION_POOL_PARTIAL_GOVERNANCE_VOTING: u64 = 21; + + public fun get_delegation_pool_partial_governance_voting(): u64 { DELEGATION_POOL_PARTIAL_GOVERNANCE_VOTING } + + public fun delegation_pool_partial_governance_voting_enabled(): bool acquires Features { + is_enabled(DELEGATION_POOL_PARTIAL_GOVERNANCE_VOTING) + } + + /// Whether alternate gas payer is supported + /// Lifetime: transient + const FEE_PAYER_ENABLED: u64 = 22; + + public fun fee_payer_enabled(): bool acquires Features { + is_enabled(FEE_PAYER_ENABLED) + } + + /// Whether enable MOVE functions to call create_auid method to create AUIDs. + /// Lifetime: transient + const APTOS_UNIQUE_IDENTIFIERS: u64 = 23; + + public fun get_auids(): u64 { + error::invalid_argument(EFEATURE_CANNOT_BE_DISABLED) + } + + public fun auids_enabled(): bool { + true + } + + /// Whether the Bulletproofs zero-knowledge range proof module is enabled, and the related native function is + /// available. This is needed because of the introduction of a new native function. + /// Lifetime: transient + const BULLETPROOFS_NATIVES: u64 = 24; + + public fun get_bulletproofs_feature(): u64 { BULLETPROOFS_NATIVES } + + public fun bulletproofs_enabled(): bool acquires Features { + is_enabled(BULLETPROOFS_NATIVES) + } + + /// Fix the native formatter for signer. + /// Lifetime: transient + const SIGNER_NATIVE_FORMAT_FIX: u64 = 25; + + public fun get_signer_native_format_fix_feature(): u64 { SIGNER_NATIVE_FORMAT_FIX } + + public fun signer_native_format_fix_enabled(): bool acquires Features { + is_enabled(SIGNER_NATIVE_FORMAT_FIX) + } + + /// Whether emit function in `event.move` are enabled for module events. + /// + /// Lifetime: transient + const MODULE_EVENT: u64 = 26; + + public fun get_module_event_feature(): u64 { MODULE_EVENT } + + public fun module_event_enabled(): bool acquires Features { + is_enabled(MODULE_EVENT) + } + + /// Whether the fix for a counting bug in the script path of the signature checker pass is enabled. + /// Lifetime: transient + const SIGNATURE_CHECKER_V2_SCRIPT_FIX: u64 = 29; + + public fun get_aggregator_v2_api_feature(): u64 { + abort error::invalid_argument(EFEATURE_CANNOT_BE_DISABLED) + } + + public fun aggregator_v2_api_enabled(): bool { + true + } + + #[deprecated] + public fun get_aggregator_snapshots_feature(): u64 { + abort error::invalid_argument(EINVALID_FEATURE) + } + + #[deprecated] + public fun aggregator_snapshots_enabled(): bool { + abort error::invalid_argument(EINVALID_FEATURE) + } + + const SAFER_RESOURCE_GROUPS: u64 = 31; + + const SAFER_METADATA: u64 = 32; + + const SINGLE_SENDER_AUTHENTICATOR: u64 = 33; + + /// Whether the automatic creation of accounts is enabled for sponsored transactions. + /// Lifetime: transient + const SPONSORED_AUTOMATIC_ACCOUNT_CREATION: u64 = 34; + + public fun get_sponsored_automatic_account_creation(): u64 { SPONSORED_AUTOMATIC_ACCOUNT_CREATION } + + public fun sponsored_automatic_account_creation_enabled(): bool acquires Features { + is_enabled(SPONSORED_AUTOMATIC_ACCOUNT_CREATION) + } + + const FEE_PAYER_ACCOUNT_OPTIONAL: u64 = 35; + + public fun get_concurrent_token_v2_feature(): u64 { + error::invalid_argument(EFEATURE_CANNOT_BE_DISABLED) + } + + public fun concurrent_token_v2_enabled(): bool { + true + } + + #[deprecated] + public fun get_concurrent_assets_feature(): u64 { + abort error::invalid_argument(EFEATURE_CANNOT_BE_DISABLED) + } + + #[deprecated] + public fun concurrent_assets_enabled(): bool { + abort error::invalid_argument(EFEATURE_CANNOT_BE_DISABLED) + } + + const LIMIT_MAX_IDENTIFIER_LENGTH: u64 = 38; + + /// Whether allow changing beneficiaries for operators. + /// Lifetime: transient + const OPERATOR_BENEFICIARY_CHANGE: u64 = 39; + + public fun get_operator_beneficiary_change_feature(): u64 { OPERATOR_BENEFICIARY_CHANGE } + + public fun operator_beneficiary_change_enabled(): bool acquires Features { + is_enabled(OPERATOR_BENEFICIARY_CHANGE) + } + + const VM_BINARY_FORMAT_V7: u64 = 40; + + const RESOURCE_GROUPS_SPLIT_IN_VM_CHANGE_SET: u64 = 41; + + /// Whether the operator commission rate change in delegation pool is enabled. + /// Lifetime: transient + const COMMISSION_CHANGE_DELEGATION_POOL: u64 = 42; + + public fun get_commission_change_delegation_pool_feature(): u64 { COMMISSION_CHANGE_DELEGATION_POOL } + + public fun commission_change_delegation_pool_enabled(): bool acquires Features { + is_enabled(COMMISSION_CHANGE_DELEGATION_POOL) + } + + /// Whether the generic algebra implementation for BN254 operations are enabled. + /// + /// Lifetime: transient + const BN254_STRUCTURES: u64 = 43; + + public fun get_bn254_strutures_feature(): u64 { BN254_STRUCTURES } + + public fun bn254_structures_enabled(): bool acquires Features { + is_enabled(BN254_STRUCTURES) + } + + /// Deprecated by `aptos_framework::randomness_config::RandomnessConfig`. + const RECONFIGURE_WITH_DKG: u64 = 45; + + public fun get_reconfigure_with_dkg_feature(): u64 { RECONFIGURE_WITH_DKG } + + public fun reconfigure_with_dkg_enabled(): bool acquires Features { + is_enabled(RECONFIGURE_WITH_DKG) + } + + /// Whether the OIDB feature is enabled, possibly with the ZK-less verification mode. + /// + /// Lifetime: transient + const KEYLESS_ACCOUNTS: u64 = 46; + + public fun get_keyless_accounts_feature(): u64 { KEYLESS_ACCOUNTS } + + public fun keyless_accounts_enabled(): bool acquires Features { + is_enabled(KEYLESS_ACCOUNTS) + } + + /// Whether the ZK-less mode of the keyless accounts feature is enabled. + /// + /// Lifetime: transient + const KEYLESS_BUT_ZKLESS_ACCOUNTS: u64 = 47; + + public fun get_keyless_but_zkless_accounts_feature(): u64 { KEYLESS_BUT_ZKLESS_ACCOUNTS } + + public fun keyless_but_zkless_accounts_feature_enabled(): bool acquires Features { + is_enabled(KEYLESS_BUT_ZKLESS_ACCOUNTS) + } + + /// Deprecated by `aptos_framework::jwk_consensus_config::JWKConsensusConfig`. + const JWK_CONSENSUS: u64 = 49; + + public fun get_jwk_consensus_feature(): u64 { JWK_CONSENSUS } + + public fun jwk_consensus_enabled(): bool acquires Features { + is_enabled(JWK_CONSENSUS) + } + + /// Whether enable Fungible Asset creation + /// to create higher throughput concurrent variants. + /// Lifetime: transient + const CONCURRENT_FUNGIBLE_ASSETS: u64 = 50; + + public fun get_concurrent_fungible_assets_feature(): u64 { CONCURRENT_FUNGIBLE_ASSETS } + + public fun concurrent_fungible_assets_enabled(): bool acquires Features { + is_enabled(CONCURRENT_FUNGIBLE_ASSETS) + } + + /// Whether deploying to objects is enabled. + const OBJECT_CODE_DEPLOYMENT: u64 = 52; + + public fun is_object_code_deployment_enabled(): bool acquires Features { + is_enabled(OBJECT_CODE_DEPLOYMENT) + } + + /// Whether checking the maximum object nesting is enabled. + const MAX_OBJECT_NESTING_CHECK: u64 = 53; + + public fun get_max_object_nesting_check_feature(): u64 { MAX_OBJECT_NESTING_CHECK } + + public fun max_object_nesting_check_enabled(): bool acquires Features { + is_enabled(MAX_OBJECT_NESTING_CHECK) + } + + /// Whether keyless accounts support passkey-based ephemeral signatures. + /// + /// Lifetime: transient + const KEYLESS_ACCOUNTS_WITH_PASSKEYS: u64 = 54; + + public fun get_keyless_accounts_with_passkeys_feature(): u64 { KEYLESS_ACCOUNTS_WITH_PASSKEYS } + + public fun keyless_accounts_with_passkeys_feature_enabled(): bool acquires Features { + is_enabled(KEYLESS_ACCOUNTS_WITH_PASSKEYS) + } + + /// Whether the Multisig V2 enhancement feature is enabled. + /// + /// Lifetime: transient + const MULTISIG_V2_ENHANCEMENT: u64 = 55; + + public fun get_multisig_v2_enhancement_feature(): u64 { MULTISIG_V2_ENHANCEMENT } + + public fun multisig_v2_enhancement_feature_enabled(): bool acquires Features { + is_enabled(MULTISIG_V2_ENHANCEMENT) + } + + /// Whether delegators allowlisting for delegation pools is supported. + /// Lifetime: transient + const DELEGATION_POOL_ALLOWLISTING: u64 = 56; + + public fun get_delegation_pool_allowlisting_feature(): u64 { DELEGATION_POOL_ALLOWLISTING } + + public fun delegation_pool_allowlisting_enabled(): bool acquires Features { + is_enabled(DELEGATION_POOL_ALLOWLISTING) + } + + /// Whether aptos_framwork enables the behavior of module event migration. + /// + /// Lifetime: transient + const MODULE_EVENT_MIGRATION: u64 = 57; + + public fun get_module_event_migration_feature(): u64 { MODULE_EVENT_MIGRATION } + + public fun module_event_migration_enabled(): bool acquires Features { + is_enabled(MODULE_EVENT_MIGRATION) + } + + /// Whether the transaction context extension is enabled. This feature allows the module + /// `transaction_context` to provide contextual information about the user transaction. + /// + /// Lifetime: transient + const TRANSACTION_CONTEXT_EXTENSION: u64 = 59; + + public fun get_transaction_context_extension_feature(): u64 { TRANSACTION_CONTEXT_EXTENSION } + + public fun transaction_context_extension_enabled(): bool acquires Features { + is_enabled(TRANSACTION_CONTEXT_EXTENSION) + } + + /// Whether migration from coin to fungible asset feature is enabled. + /// + /// Lifetime: transient + const COIN_TO_FUNGIBLE_ASSET_MIGRATION: u64 = 60; + + public fun get_coin_to_fungible_asset_migration_feature(): u64 { COIN_TO_FUNGIBLE_ASSET_MIGRATION } + + public fun coin_to_fungible_asset_migration_feature_enabled(): bool acquires Features { + is_enabled(COIN_TO_FUNGIBLE_ASSET_MIGRATION) + } + + const PRIMARY_APT_FUNGIBLE_STORE_AT_USER_ADDRESS: u64 = 61; + + #[deprecated] + public fun get_primary_apt_fungible_store_at_user_address_feature( + ): u64 { + abort error::invalid_argument(EINVALID_FEATURE) + } + + #[deprecated] + public fun primary_apt_fungible_store_at_user_address_enabled(): bool acquires Features { + is_enabled(PRIMARY_APT_FUNGIBLE_STORE_AT_USER_ADDRESS) + } + + const AGGREGATOR_V2_IS_AT_LEAST_API: u64 = 66; + + public fun aggregator_v2_is_at_least_api_enabled(): bool acquires Features { + is_enabled(AGGREGATOR_V2_IS_AT_LEAST_API) + } + + /// Whether we use more efficient native implementation of computing object derived address + const OBJECT_NATIVE_DERIVED_ADDRESS: u64 = 62; + + public fun get_object_native_derived_address_feature(): u64 { OBJECT_NATIVE_DERIVED_ADDRESS } + + public fun object_native_derived_address_enabled(): bool acquires Features { + is_enabled(OBJECT_NATIVE_DERIVED_ADDRESS) + } + + /// Whether the dispatchable fungible asset standard feature is enabled. + /// + /// Lifetime: transient + const DISPATCHABLE_FUNGIBLE_ASSET: u64 = 63; + + public fun get_dispatchable_fungible_asset_feature(): u64 { DISPATCHABLE_FUNGIBLE_ASSET } + + public fun dispatchable_fungible_asset_enabled(): bool acquires Features { + is_enabled(DISPATCHABLE_FUNGIBLE_ASSET) + } + + /// Lifetime: transient + const NEW_ACCOUNTS_DEFAULT_TO_FA_APT_STORE: u64 = 64; + + public fun get_new_accounts_default_to_fa_apt_store_feature(): u64 { NEW_ACCOUNTS_DEFAULT_TO_FA_APT_STORE } + + public fun new_accounts_default_to_fa_apt_store_enabled(): bool acquires Features { + is_enabled(NEW_ACCOUNTS_DEFAULT_TO_FA_APT_STORE) + } + + /// Lifetime: transient + const OPERATIONS_DEFAULT_TO_FA_APT_STORE: u64 = 65; + + public fun get_operations_default_to_fa_apt_store_feature(): u64 { OPERATIONS_DEFAULT_TO_FA_APT_STORE } + + public fun operations_default_to_fa_apt_store_enabled(): bool acquires Features { + is_enabled(OPERATIONS_DEFAULT_TO_FA_APT_STORE) + } + + /// Whether enable concurent Fungible Balance + /// to create higher throughput concurrent variants. + /// Lifetime: transient + const CONCURRENT_FUNGIBLE_BALANCE: u64 = 67; + + public fun get_concurrent_fungible_balance_feature(): u64 { CONCURRENT_FUNGIBLE_BALANCE } + + public fun concurrent_fungible_balance_enabled(): bool acquires Features { + is_enabled(CONCURRENT_FUNGIBLE_BALANCE) + } + + /// Whether to default new Fungible Store to the concurrent variant. + /// Lifetime: transient + const DEFAULT_TO_CONCURRENT_FUNGIBLE_BALANCE: u64 = 68; + + public fun get_default_to_concurrent_fungible_balance_feature(): u64 { DEFAULT_TO_CONCURRENT_FUNGIBLE_BALANCE } + + public fun default_to_concurrent_fungible_balance_enabled(): bool acquires Features { + is_enabled(DEFAULT_TO_CONCURRENT_FUNGIBLE_BALANCE) + } + + /// Whether the multisig v2 fix is enabled. Once enabled, the multisig transaction execution will explicitly + /// abort if the provided payload does not match the payload stored on-chain. + /// + /// Lifetime: transient + const ABORT_IF_MULTISIG_PAYLOAD_MISMATCH: u64 = 70; + + public fun get_abort_if_multisig_payload_mismatch_feature(): u64 { ABORT_IF_MULTISIG_PAYLOAD_MISMATCH } + + public fun abort_if_multisig_payload_mismatch_enabled(): bool acquires Features { + is_enabled(ABORT_IF_MULTISIG_PAYLOAD_MISMATCH) + } + + /// Whether the Atomic bridge is available + /// Lifetime: transient + const ATOMIC_BRIDGE: u64 = 71; + + public fun get_atomic_bridge_feature(): u64 { ATOMIC_BRIDGE } + + public fun abort_atomic_bridge_enabled(): bool acquires Features { + is_enabled(ATOMIC_BRIDGE) + } + + + /// Whether the Atomic bridge is available + /// Lifetime: transient + const NATIVE_BRIDGE: u64 = 72; + + public fun get_native_bridge_feature(): u64 { NATIVE_BRIDGE } + + public fun abort_native_bridge_enabled(): bool acquires Features { + is_enabled(NATIVE_BRIDGE) + } + + /// Whether the Governed Gas Pool is used to capture gas fees + /// + /// Lifetime: permanent + const GOVERNED_GAS_POOL: u64 = 73; + + /// Whether the Governed Gas Pool is enabled. + public fun get_governed_gas_pool_feature(): u64 { GOVERNED_GAS_POOL } + + public fun governed_gas_pool_enabled(): bool acquires Features { + is_enabled(GOVERNED_GAS_POOL) + } + + // ============================================================================================ + // Feature Flag Implementation + + /// The provided signer has not a framework address. + const EFRAMEWORK_SIGNER_NEEDED: u64 = 1; + + /// The enabled features, represented by a bitset stored on chain. + struct Features has key { + features: vector, + } + + /// This resource holds the feature vec updates received in the current epoch. + /// On epoch change, the updates take effect and this buffer is cleared. + struct PendingFeatures has key { + features: vector, + } + + /// Deprecated to prevent validator set changes during DKG. + /// + /// Genesis/tests should use `change_feature_flags_internal()` for feature vec initialization. + /// + /// This can be used on testnet prior to successful DKG. + /// + /// Governance proposals should use `change_feature_flags_for_next_epoch()` to enable/disable features. + public fun change_feature_flags(framework: &signer, enable: vector, disable: vector) acquires Features { + change_feature_flags_internal(framework, enable, disable) + } + + /// Update feature flags directly. Only used in genesis/tests. + fun change_feature_flags_internal(framework: &signer, enable: vector, disable: vector) acquires Features { + assert!(signer::address_of(framework) == @std, error::permission_denied(EFRAMEWORK_SIGNER_NEEDED)); + if (!exists(@std)) { + move_to(framework, Features { features: vector[] }) + }; + let features = &mut borrow_global_mut(@std).features; + vector::for_each_ref(&enable, |feature| { + set(features, *feature, true); + }); + vector::for_each_ref(&disable, |feature| { + set(features, *feature, false); + }); + } + + /// Enable and disable features for the next epoch. + public fun change_feature_flags_for_next_epoch( + framework: &signer, + enable: vector, + disable: vector + ) acquires PendingFeatures, Features { + assert!(signer::address_of(framework) == @std, error::permission_denied(EFRAMEWORK_SIGNER_NEEDED)); + + // Figure out the baseline feature vec that the diff will be applied to. + let new_feature_vec = if (exists(@std)) { + // If there is a buffered feature vec, use it as the baseline. + let PendingFeatures { features } = move_from(@std); + features + } else if (exists(@std)) { + // Otherwise, use the currently effective feature flag vec as the baseline, if it exists. + borrow_global(@std).features + } else { + // Otherwise, use an empty feature vec. + vector[] + }; + + // Apply the diff and save it to the buffer. + apply_diff(&mut new_feature_vec, enable, disable); + move_to(framework, PendingFeatures { features: new_feature_vec }); + } + + /// Apply all the pending feature flag changes. Should only be used at the end of a reconfiguration with DKG. + /// + /// While the scope is public, it can only be usd in system transactions like `block_prologue` and governance proposals, + /// who have permission to set the flag that's checked in `extract()`. + public fun on_new_epoch(framework: &signer) acquires Features, PendingFeatures { + ensure_framework_signer(framework); + if (exists(@std)) { + let PendingFeatures { features } = move_from(@std); + if (exists(@std)) { + borrow_global_mut(@std).features = features; + } else { + move_to(framework, Features { features }) + } + } + } + + #[view] + /// Check whether the feature is enabled. + public fun is_enabled(feature: u64): bool acquires Features { + exists(@std) && + contains(&borrow_global(@std).features, feature) + } + + /// Helper to include or exclude a feature flag. + fun set(features: &mut vector, feature: u64, include: bool) { + let byte_index = feature / 8; + let bit_mask = 1 << ((feature % 8) as u8); + while (vector::length(features) <= byte_index) { + vector::push_back(features, 0) + }; + let entry = vector::borrow_mut(features, byte_index); + if (include) + *entry = *entry | bit_mask + else + *entry = *entry & (0xff ^ bit_mask) + } + + /// Helper to check whether a feature flag is enabled. + fun contains(features: &vector, feature: u64): bool { + let byte_index = feature / 8; + let bit_mask = 1 << ((feature % 8) as u8); + byte_index < vector::length(features) && (*vector::borrow(features, byte_index) & bit_mask) != 0 + } + + fun apply_diff(features: &mut vector, enable: vector, disable: vector) { + vector::for_each(enable, |feature| { + set(features, feature, true); + }); + vector::for_each(disable, |feature| { + set(features, feature, false); + }); + } + + fun ensure_framework_signer(account: &signer) { + let addr = signer::address_of(account); + assert!(addr == @std, error::permission_denied(EFRAMEWORK_SIGNER_NEEDED)); + } + + #[verify_only] + public fun change_feature_flags_for_verification( + framework: &signer, + enable: vector, + disable: vector + ) acquires Features { + change_feature_flags_internal(framework, enable, disable) + } + + #[test_only] + public fun change_feature_flags_for_testing( + framework: &signer, + enable: vector, + disable: vector + ) acquires Features { + change_feature_flags_internal(framework, enable, disable) + } + + #[test] + fun test_feature_sets() { + let features = vector[]; + set(&mut features, 1, true); + set(&mut features, 5, true); + set(&mut features, 17, true); + set(&mut features, 23, true); + assert!(contains(&features, 1), 0); + assert!(contains(&features, 5), 1); + assert!(contains(&features, 17), 2); + assert!(contains(&features, 23), 3); + set(&mut features, 5, false); + set(&mut features, 17, false); + assert!(contains(&features, 1), 0); + assert!(!contains(&features, 5), 1); + assert!(!contains(&features, 17), 2); + assert!(contains(&features, 23), 3); + } + + #[test(fx = @std)] + fun test_change_feature_txn(fx: signer) acquires Features { + change_feature_flags_for_testing(&fx, vector[1, 9, 23], vector[]); + assert!(is_enabled(1), 1); + assert!(is_enabled(9), 2); + assert!(is_enabled(23), 3); + change_feature_flags_for_testing(&fx, vector[17], vector[9]); + assert!(is_enabled(1), 1); + assert!(!is_enabled(9), 2); + assert!(is_enabled(17), 3); + assert!(is_enabled(23), 4); + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/fixed_point32.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/fixed_point32.move new file mode 100644 index 000000000..96409a9ac --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/fixed_point32.move @@ -0,0 +1,295 @@ +/// Defines a fixed-point numeric type with a 32-bit integer part and +/// a 32-bit fractional part. + +module std::fixed_point32 { + + /// Define a fixed-point numeric type with 32 fractional bits. + /// This is just a u64 integer but it is wrapped in a struct to + /// make a unique type. This is a binary representation, so decimal + /// values may not be exactly representable, but it provides more + /// than 9 decimal digits of precision both before and after the + /// decimal point (18 digits total). For comparison, double precision + /// floating-point has less than 16 decimal digits of precision, so + /// be careful about using floating-point to convert these values to + /// decimal. + struct FixedPoint32 has copy, drop, store { value: u64 } + + const MAX_U64: u128 = 18446744073709551615; + + /// The denominator provided was zero + const EDENOMINATOR: u64 = 0x10001; + /// The quotient value would be too large to be held in a `u64` + const EDIVISION: u64 = 0x20002; + /// The multiplied value would be too large to be held in a `u64` + const EMULTIPLICATION: u64 = 0x20003; + /// A division by zero was encountered + const EDIVISION_BY_ZERO: u64 = 0x10004; + /// The computed ratio when converting to a `FixedPoint32` would be unrepresentable + const ERATIO_OUT_OF_RANGE: u64 = 0x20005; + + /// Multiply a u64 integer by a fixed-point number, truncating any + /// fractional part of the product. This will abort if the product + /// overflows. + public fun multiply_u64(val: u64, multiplier: FixedPoint32): u64 { + // The product of two 64 bit values has 128 bits, so perform the + // multiplication with u128 types and keep the full 128 bit product + // to avoid losing accuracy. + let unscaled_product = (val as u128) * (multiplier.value as u128); + // The unscaled product has 32 fractional bits (from the multiplier) + // so rescale it by shifting away the low bits. + let product = unscaled_product >> 32; + // Check whether the value is too large. + assert!(product <= MAX_U64, EMULTIPLICATION); + (product as u64) + } + spec multiply_u64 { + pragma opaque; + include MultiplyAbortsIf; + ensures result == spec_multiply_u64(val, multiplier); + } + spec schema MultiplyAbortsIf { + val: num; + multiplier: FixedPoint32; + aborts_if spec_multiply_u64(val, multiplier) > MAX_U64 with EMULTIPLICATION; + } + spec fun spec_multiply_u64(val: num, multiplier: FixedPoint32): num { + (val * multiplier.value) >> 32 + } + + /// Divide a u64 integer by a fixed-point number, truncating any + /// fractional part of the quotient. This will abort if the divisor + /// is zero or if the quotient overflows. + public fun divide_u64(val: u64, divisor: FixedPoint32): u64 { + // Check for division by zero. + assert!(divisor.value != 0, EDIVISION_BY_ZERO); + // First convert to 128 bits and then shift left to + // add 32 fractional zero bits to the dividend. + let scaled_value = (val as u128) << 32; + let quotient = scaled_value / (divisor.value as u128); + // Check whether the value is too large. + assert!(quotient <= MAX_U64, EDIVISION); + // the value may be too large, which will cause the cast to fail + // with an arithmetic error. + (quotient as u64) + } + spec divide_u64 { + pragma opaque; + include DivideAbortsIf; + ensures result == spec_divide_u64(val, divisor); + } + spec schema DivideAbortsIf { + val: num; + divisor: FixedPoint32; + aborts_if divisor.value == 0 with EDIVISION_BY_ZERO; + aborts_if spec_divide_u64(val, divisor) > MAX_U64 with EDIVISION; + } + spec fun spec_divide_u64(val: num, divisor: FixedPoint32): num { + (val << 32) / divisor.value + } + + /// Create a fixed-point value from a rational number specified by its + /// numerator and denominator. Calling this function should be preferred + /// for using `Self::create_from_raw_value` which is also available. + /// This will abort if the denominator is zero. It will also + /// abort if the numerator is nonzero and the ratio is not in the range + /// 2^-32 .. 2^32-1. When specifying decimal fractions, be careful about + /// rounding errors: if you round to display N digits after the decimal + /// point, you can use a denominator of 10^N to avoid numbers where the + /// very small imprecision in the binary representation could change the + /// rounding, e.g., 0.0125 will round down to 0.012 instead of up to 0.013. + public fun create_from_rational(numerator: u64, denominator: u64): FixedPoint32 { + // If the denominator is zero, this will abort. + // Scale the numerator to have 64 fractional bits and the denominator + // to have 32 fractional bits, so that the quotient will have 32 + // fractional bits. + let scaled_numerator = (numerator as u128) << 64; + let scaled_denominator = (denominator as u128) << 32; + assert!(scaled_denominator != 0, EDENOMINATOR); + let quotient = scaled_numerator / scaled_denominator; + assert!(quotient != 0 || numerator == 0, ERATIO_OUT_OF_RANGE); + // Return the quotient as a fixed-point number. We first need to check whether the cast + // can succeed. + assert!(quotient <= MAX_U64, ERATIO_OUT_OF_RANGE); + FixedPoint32 { value: (quotient as u64) } + } + spec create_from_rational { + pragma opaque; + include CreateFromRationalAbortsIf; + ensures result == spec_create_from_rational(numerator, denominator); + } + spec schema CreateFromRationalAbortsIf { + numerator: u64; + denominator: u64; + let scaled_numerator = (numerator as u128)<< 64; + let scaled_denominator = (denominator as u128) << 32; + let quotient = scaled_numerator / scaled_denominator; + aborts_if scaled_denominator == 0 with EDENOMINATOR; + aborts_if quotient == 0 && scaled_numerator != 0 with ERATIO_OUT_OF_RANGE; + aborts_if quotient > MAX_U64 with ERATIO_OUT_OF_RANGE; + } + spec fun spec_create_from_rational(numerator: num, denominator: num): FixedPoint32 { + FixedPoint32{value: (numerator << 64) / (denominator << 32)} + } + + /// Create a fixedpoint value from a raw value. + public fun create_from_raw_value(value: u64): FixedPoint32 { + FixedPoint32 { value } + } + spec create_from_raw_value { + pragma opaque; + aborts_if false; + ensures result.value == value; + } + + /// Accessor for the raw u64 value. Other less common operations, such as + /// adding or subtracting FixedPoint32 values, can be done using the raw + /// values directly. + public fun get_raw_value(num: FixedPoint32): u64 { + num.value + } + + /// Returns true if the ratio is zero. + public fun is_zero(num: FixedPoint32): bool { + num.value == 0 + } + + /// Returns the smaller of the two FixedPoint32 numbers. + public fun min(num1: FixedPoint32, num2: FixedPoint32): FixedPoint32 { + if (num1.value < num2.value) { + num1 + } else { + num2 + } + } + spec min { + pragma opaque; + aborts_if false; + ensures result == spec_min(num1, num2); + } + spec fun spec_min(num1: FixedPoint32, num2: FixedPoint32): FixedPoint32 { + if (num1.value < num2.value) { + num1 + } else { + num2 + } + } + + /// Returns the larger of the two FixedPoint32 numbers. + public fun max(num1: FixedPoint32, num2: FixedPoint32): FixedPoint32 { + if (num1.value > num2.value) { + num1 + } else { + num2 + } + } + spec max { + pragma opaque; + aborts_if false; + ensures result == spec_max(num1, num2); + } + spec fun spec_max(num1: FixedPoint32, num2: FixedPoint32): FixedPoint32 { + if (num1.value > num2.value) { + num1 + } else { + num2 + } + } + + /// Create a fixedpoint value from a u64 value. + public fun create_from_u64(val: u64): FixedPoint32 { + let value = (val as u128) << 32; + assert!(value <= MAX_U64, ERATIO_OUT_OF_RANGE); + FixedPoint32 {value: (value as u64)} + } + spec create_from_u64 { + pragma opaque; + include CreateFromU64AbortsIf; + ensures result == spec_create_from_u64(val); + } + spec schema CreateFromU64AbortsIf { + val: num; + let scaled_value = (val as u128) << 32; + aborts_if scaled_value > MAX_U64; + } + spec fun spec_create_from_u64(val: num): FixedPoint32 { + FixedPoint32 {value: val << 32} + } + + /// Returns the largest integer less than or equal to a given number. + public fun floor(num: FixedPoint32): u64 { + num.value >> 32 + } + spec floor { + pragma opaque; + aborts_if false; + ensures result == spec_floor(num); + } + spec fun spec_floor(val: FixedPoint32): u64 { + let fractional = val.value % (1 << 32); + if (fractional == 0) { + val.value >> 32 + } else { + (val.value - fractional) >> 32 + } + } + + /// Rounds up the given FixedPoint32 to the next largest integer. + public fun ceil(num: FixedPoint32): u64 { + let floored_num = floor(num) << 32; + if (num.value == floored_num) { + return floored_num >> 32 + }; + let val = ((floored_num as u128) + (1 << 32)); + (val >> 32 as u64) + } + spec ceil { + pragma verify_duration_estimate = 120; + pragma opaque; + aborts_if false; + ensures result == spec_ceil(num); + } + spec fun spec_ceil(val: FixedPoint32): u64 { + let fractional = val.value % (1 << 32); + let one = 1 << 32; + if (fractional == 0) { + val.value >> 32 + } else { + (val.value - fractional + one) >> 32 + } + } + + /// Returns the value of a FixedPoint32 to the nearest integer. + public fun round(num: FixedPoint32): u64 { + let floored_num = floor(num) << 32; + let boundary = floored_num + ((1 << 32) / 2); + if (num.value < boundary) { + floored_num >> 32 + } else { + ceil(num) + } + } + spec round { + pragma verify_duration_estimate = 120; + pragma opaque; + aborts_if false; + ensures result == spec_round(num); + } + spec fun spec_round(val: FixedPoint32): u64 { + let fractional = val.value % (1 << 32); + let boundary = (1 << 32) / 2; + let one = 1 << 32; + if (fractional < boundary) { + (val.value - fractional) >> 32 + } else { + (val.value - fractional + one) >> 32 + } + } + + // **************** SPECIFICATIONS **************** + + spec module {} // switch documentation context to module level + + spec module { + pragma aborts_if_is_strict; + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/hash.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/hash.move new file mode 100644 index 000000000..daadc4e81 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/hash.move @@ -0,0 +1,8 @@ +/// Module which defines SHA hashes for byte vectors. +/// +/// The functions in this module are natively declared both in the Move runtime +/// as in the Move prover's prelude. +module std::hash { + native public fun sha2_256(data: vector): vector; + native public fun sha3_256(data: vector): vector; +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/option.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/option.move new file mode 100644 index 000000000..1793abfe9 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/option.move @@ -0,0 +1,356 @@ +/// This module defines the Option type and its methods to represent and handle an optional value. +module std::option { + use std::vector; + + /// Abstraction of a value that may or may not be present. Implemented with a vector of size + /// zero or one because Move bytecode does not have ADTs. + struct Option has copy, drop, store { + vec: vector + } + spec Option { + /// The size of vector is always less than equal to 1 + /// because it's 0 for "none" or 1 for "some". + invariant len(vec) <= 1; + } + + /// The `Option` is in an invalid state for the operation attempted. + /// The `Option` is `Some` while it should be `None`. + const EOPTION_IS_SET: u64 = 0x40000; + /// The `Option` is in an invalid state for the operation attempted. + /// The `Option` is `None` while it should be `Some`. + const EOPTION_NOT_SET: u64 = 0x40001; + /// Cannot construct an option from a vector with 2 or more elements. + const EOPTION_VEC_TOO_LONG: u64 = 0x40002; + + /// Return an empty `Option` + public fun none(): Option { + Option { vec: vector::empty() } + } + spec none { + pragma opaque; + aborts_if false; + ensures result == spec_none(); + } + spec fun spec_none(): Option { + Option{ vec: vec() } + } + + /// Return an `Option` containing `e` + public fun some(e: Element): Option { + Option { vec: vector::singleton(e) } + } + spec some { + pragma opaque; + aborts_if false; + ensures result == spec_some(e); + } + spec fun spec_some(e: Element): Option { + Option{ vec: vec(e) } + } + + public fun from_vec(vec: vector): Option { + assert!(vector::length(&vec) <= 1, EOPTION_VEC_TOO_LONG); + Option { vec } + } + + spec from_vec { + aborts_if vector::length(vec) > 1; + } + + /// Return true if `t` does not hold a value + public fun is_none(t: &Option): bool { + vector::is_empty(&t.vec) + } + spec is_none { + pragma opaque; + aborts_if false; + ensures result == spec_is_none(t); + } + spec fun spec_is_none(t: Option): bool { + vector::is_empty(t.vec) + } + + /// Return true if `t` holds a value + public fun is_some(t: &Option): bool { + !vector::is_empty(&t.vec) + } + spec is_some { + pragma opaque; + aborts_if false; + ensures result == spec_is_some(t); + } + spec fun spec_is_some(t: Option): bool { + !vector::is_empty(t.vec) + } + + /// Return true if the value in `t` is equal to `e_ref` + /// Always returns `false` if `t` does not hold a value + public fun contains(t: &Option, e_ref: &Element): bool { + vector::contains(&t.vec, e_ref) + } + spec contains { + pragma opaque; + aborts_if false; + ensures result == spec_contains(t, e_ref); + } + spec fun spec_contains(t: Option, e: Element): bool { + is_some(t) && borrow(t) == e + } + + /// Return an immutable reference to the value inside `t` + /// Aborts if `t` does not hold a value + public fun borrow(t: &Option): &Element { + assert!(is_some(t), EOPTION_NOT_SET); + vector::borrow(&t.vec, 0) + } + spec borrow { + pragma opaque; + include AbortsIfNone; + ensures result == spec_borrow(t); + } + spec fun spec_borrow(t: Option): Element { + t.vec[0] + } + + /// Return a reference to the value inside `t` if it holds one + /// Return `default_ref` if `t` does not hold a value + public fun borrow_with_default(t: &Option, default_ref: &Element): &Element { + let vec_ref = &t.vec; + if (vector::is_empty(vec_ref)) default_ref + else vector::borrow(vec_ref, 0) + } + spec borrow_with_default { + pragma opaque; + aborts_if false; + ensures result == (if (spec_is_some(t)) spec_borrow(t) else default_ref); + } + + /// Return the value inside `t` if it holds one + /// Return `default` if `t` does not hold a value + public fun get_with_default( + t: &Option, + default: Element, + ): Element { + let vec_ref = &t.vec; + if (vector::is_empty(vec_ref)) default + else *vector::borrow(vec_ref, 0) + } + spec get_with_default { + pragma opaque; + aborts_if false; + ensures result == (if (spec_is_some(t)) spec_borrow(t) else default); + } + + /// Convert the none option `t` to a some option by adding `e`. + /// Aborts if `t` already holds a value + public fun fill(t: &mut Option, e: Element) { + let vec_ref = &mut t.vec; + if (vector::is_empty(vec_ref)) vector::push_back(vec_ref, e) + else abort EOPTION_IS_SET + } + spec fill { + pragma opaque; + aborts_if spec_is_some(t) with EOPTION_IS_SET; + ensures spec_is_some(t); + ensures spec_borrow(t) == e; + } + + /// Convert a `some` option to a `none` by removing and returning the value stored inside `t` + /// Aborts if `t` does not hold a value + public fun extract(t: &mut Option): Element { + assert!(is_some(t), EOPTION_NOT_SET); + vector::pop_back(&mut t.vec) + } + spec extract { + pragma opaque; + include AbortsIfNone; + ensures result == spec_borrow(old(t)); + ensures spec_is_none(t); + } + + /// Return a mutable reference to the value inside `t` + /// Aborts if `t` does not hold a value + public fun borrow_mut(t: &mut Option): &mut Element { + assert!(is_some(t), EOPTION_NOT_SET); + vector::borrow_mut(&mut t.vec, 0) + } + spec borrow_mut { + include AbortsIfNone; + ensures result == spec_borrow(t); + ensures t == old(t); + } + + /// Swap the old value inside `t` with `e` and return the old value + /// Aborts if `t` does not hold a value + public fun swap(t: &mut Option, e: Element): Element { + assert!(is_some(t), EOPTION_NOT_SET); + let vec_ref = &mut t.vec; + let old_value = vector::pop_back(vec_ref); + vector::push_back(vec_ref, e); + old_value + } + spec swap { + pragma opaque; + include AbortsIfNone; + ensures result == spec_borrow(old(t)); + ensures spec_is_some(t); + ensures spec_borrow(t) == e; + } + + /// Swap the old value inside `t` with `e` and return the old value; + /// or if there is no old value, fill it with `e`. + /// Different from swap(), swap_or_fill() allows for `t` not holding a value. + public fun swap_or_fill(t: &mut Option, e: Element): Option { + let vec_ref = &mut t.vec; + let old_value = if (vector::is_empty(vec_ref)) none() + else some(vector::pop_back(vec_ref)); + vector::push_back(vec_ref, e); + old_value + } + spec swap_or_fill { + pragma opaque; + aborts_if false; + ensures result == old(t); + ensures spec_borrow(t) == e; + } + + /// Destroys `t.` If `t` holds a value, return it. Returns `default` otherwise + public fun destroy_with_default(t: Option, default: Element): Element { + let Option { vec } = t; + if (vector::is_empty(&mut vec)) default + else vector::pop_back(&mut vec) + } + spec destroy_with_default { + pragma opaque; + aborts_if false; + ensures result == (if (spec_is_some(t)) spec_borrow(t) else default); + } + + /// Unpack `t` and return its contents + /// Aborts if `t` does not hold a value + public fun destroy_some(t: Option): Element { + assert!(is_some(&t), EOPTION_NOT_SET); + let Option { vec } = t; + let elem = vector::pop_back(&mut vec); + vector::destroy_empty(vec); + elem + } + spec destroy_some { + pragma opaque; + include AbortsIfNone; + ensures result == spec_borrow(t); + } + + /// Unpack `t` + /// Aborts if `t` holds a value + public fun destroy_none(t: Option) { + assert!(is_none(&t), EOPTION_IS_SET); + let Option { vec } = t; + vector::destroy_empty(vec) + } + spec destroy_none { + pragma opaque; + aborts_if spec_is_some(t) with EOPTION_IS_SET; + } + + /// Convert `t` into a vector of length 1 if it is `Some`, + /// and an empty vector otherwise + public fun to_vec(t: Option): vector { + let Option { vec } = t; + vec + } + spec to_vec { + pragma opaque; + aborts_if false; + ensures result == t.vec; + } + /// Apply the function to the optional element, consuming it. Does nothing if no value present. + public inline fun for_each(o: Option, f: |Element|) { + if (is_some(&o)) { + f(destroy_some(o)) + } else { + destroy_none(o) + } + } + + /// Apply the function to the optional element reference. Does nothing if no value present. + public inline fun for_each_ref(o: &Option, f: |&Element|) { + if (is_some(o)) { + f(borrow(o)) + } + } + + /// Apply the function to the optional element reference. Does nothing if no value present. + public inline fun for_each_mut(o: &mut Option, f: |&mut Element|) { + if (is_some(o)) { + f(borrow_mut(o)) + } + } + + /// Folds the function over the optional element. + public inline fun fold( + o: Option, + init: Accumulator, + f: |Accumulator,Element|Accumulator + ): Accumulator { + if (is_some(&o)) { + f(init, destroy_some(o)) + } else { + destroy_none(o); + init + } + } + + /// Maps the content of an option. + public inline fun map(o: Option, f: |Element|OtherElement): Option { + if (is_some(&o)) { + some(f(destroy_some(o))) + } else { + destroy_none(o); + none() + } + } + + /// Maps the content of an option without destroying the original option. + public inline fun map_ref( + o: &Option, f: |&Element|OtherElement): Option { + if (is_some(o)) { + some(f(borrow(o))) + } else { + none() + } + } + + /// Filters the content of an option + public inline fun filter(o: Option, f: |&Element|bool): Option { + if (is_some(&o) && f(borrow(&o))) { + o + } else { + none() + } + } + + /// Returns true if the option contains an element which satisfies predicate. + public inline fun any(o: &Option, p: |&Element|bool): bool { + is_some(o) && p(borrow(o)) + } + + /// Utility function to destroy an option that is not droppable. + public inline fun destroy(o: Option, d: |Element|) { + let vec = to_vec(o); + vector::destroy(vec, |e| d(e)); + } + + spec module {} // switch documentation context back to module level + + spec module { + pragma aborts_if_is_strict; + } + + /// # Helper Schema + + spec schema AbortsIfNone { + t: Option; + aborts_if spec_is_none(t) with EOPTION_NOT_SET; + } +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/signer.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/signer.move new file mode 100644 index 000000000..c2e3ab3f5 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/signer.move @@ -0,0 +1,21 @@ +module std::signer { + /// Borrows the address of the signer + /// Conceptually, you can think of the `signer` as being a struct wrapper around an + /// address + /// ``` + /// struct signer has drop { addr: address } + /// ``` + /// `borrow_address` borrows this inner field + native public fun borrow_address(s: &signer): &address; + + // Copies the address of the signer + public fun address_of(s: &signer): address { + *borrow_address(s) + } + + /// Return true only if `s` is a transaction signer. This is a spec function only available in spec. + spec native fun is_txn_signer(s: signer): bool; + + /// Return true only if `a` is a transaction signer address. This is a spec function only available in spec. + spec native fun is_txn_signer_addr(a: address): bool; +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/string.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/string.move new file mode 100644 index 000000000..6a2ca69d0 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/string.move @@ -0,0 +1,93 @@ +/// The `string` module defines the `String` type which represents UTF8 encoded strings. +module std::string { + use std::vector; + use std::option::{Self, Option}; + + /// An invalid UTF8 encoding. + const EINVALID_UTF8: u64 = 1; + + /// Index out of range. + const EINVALID_INDEX: u64 = 2; + + /// A `String` holds a sequence of bytes which is guaranteed to be in utf8 format. + struct String has copy, drop, store { + bytes: vector, + } + + /// Creates a new string from a sequence of bytes. Aborts if the bytes do not represent valid utf8. + public fun utf8(bytes: vector): String { + assert!(internal_check_utf8(&bytes), EINVALID_UTF8); + String{bytes} + } + + /// Tries to create a new string from a sequence of bytes. + public fun try_utf8(bytes: vector): Option { + if (internal_check_utf8(&bytes)) { + option::some(String{bytes}) + } else { + option::none() + } + } + + /// Returns a reference to the underlying byte vector. + public fun bytes(s: &String): &vector { + &s.bytes + } + + /// Checks whether this string is empty. + public fun is_empty(s: &String): bool { + vector::is_empty(&s.bytes) + } + + /// Returns the length of this string, in bytes. + public fun length(s: &String): u64 { + vector::length(&s.bytes) + } + + /// Appends a string. + public fun append(s: &mut String, r: String) { + vector::append(&mut s.bytes, r.bytes) + } + + /// Appends bytes which must be in valid utf8 format. + public fun append_utf8(s: &mut String, bytes: vector) { + append(s, utf8(bytes)) + } + + /// Insert the other string at the byte index in given string. The index must be at a valid utf8 char + /// boundary. + public fun insert(s: &mut String, at: u64, o: String) { + let bytes = &s.bytes; + assert!(at <= vector::length(bytes) && internal_is_char_boundary(bytes, at), EINVALID_INDEX); + let l = length(s); + let front = sub_string(s, 0, at); + let end = sub_string(s, at, l); + append(&mut front, o); + append(&mut front, end); + *s = front; + } + + /// Returns a sub-string using the given byte indices, where `i` is the first byte position and `j` is the start + /// of the first byte not included (or the length of the string). The indices must be at valid utf8 char boundaries, + /// guaranteeing that the result is valid utf8. + public fun sub_string(s: &String, i: u64, j: u64): String { + let bytes = &s.bytes; + let l = vector::length(bytes); + assert!( + j <= l && i <= j && internal_is_char_boundary(bytes, i) && internal_is_char_boundary(bytes, j), + EINVALID_INDEX + ); + String { bytes: internal_sub_string(bytes, i, j) } + } + + /// Computes the index of the first occurrence of a string. Returns `length(s)` if no occurrence found. + public fun index_of(s: &String, r: &String): u64 { + internal_index_of(&s.bytes, &r.bytes) + } + + // Native API + public native fun internal_check_utf8(v: &vector): bool; + native fun internal_is_char_boundary(v: &vector, i: u64): bool; + native fun internal_sub_string(v: &vector, i: u64, j: u64): vector; + native fun internal_index_of(v: &vector, r: &vector): u64; +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/vector.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/vector.move new file mode 100644 index 000000000..05368acf4 --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/dependencies/MoveStdlib/vector.move @@ -0,0 +1,669 @@ +/// A variable-sized container that can hold any type. Indexing is 0-based, and +/// vectors are growable. This module has many native functions. +/// Verification of modules that use this one uses model functions that are implemented +/// directly in Boogie. The specification language has built-in functions operations such +/// as `singleton_vector`. There are some helper functions defined here for specifications in other +/// modules as well. +/// +/// >Note: We did not verify most of the +/// Move functions here because many have loops, requiring loop invariants to prove, and +/// the return on investment didn't seem worth it for these simple functions. +module std::vector { + /// The index into the vector is out of bounds + const EINDEX_OUT_OF_BOUNDS: u64 = 0x20000; + + /// The index into the vector is out of bounds + const EINVALID_RANGE: u64 = 0x20001; + + /// The length of the vectors are not equal. + const EVECTORS_LENGTH_MISMATCH: u64 = 0x20002; + + /// The step provided in `range` is invalid, must be greater than zero. + const EINVALID_STEP: u64 = 0x20003; + + /// The range in `slice` is invalid. + const EINVALID_SLICE_RANGE: u64 = 0x20004; + + #[bytecode_instruction] + /// Create an empty vector. + native public fun empty(): vector; + + #[bytecode_instruction] + /// Return the length of the vector. + native public fun length(v: &vector): u64; + + #[bytecode_instruction] + /// Acquire an immutable reference to the `i`th element of the vector `v`. + /// Aborts if `i` is out of bounds. + native public fun borrow(v: &vector, i: u64): ∈ + + #[bytecode_instruction] + /// Add element `e` to the end of the vector `v`. + native public fun push_back(v: &mut vector, e: Element); + + #[bytecode_instruction] + /// Return a mutable reference to the `i`th element in the vector `v`. + /// Aborts if `i` is out of bounds. + native public fun borrow_mut(v: &mut vector, i: u64): &mut Element; + + #[bytecode_instruction] + /// Pop an element from the end of vector `v`. + /// Aborts if `v` is empty. + native public fun pop_back(v: &mut vector): Element; + + #[bytecode_instruction] + /// Destroy the vector `v`. + /// Aborts if `v` is not empty. + native public fun destroy_empty(v: vector); + + #[bytecode_instruction] + /// Swaps the elements at the `i`th and `j`th indices in the vector `v`. + /// Aborts if `i` or `j` is out of bounds. + native public fun swap(v: &mut vector, i: u64, j: u64); + + /// Return an vector of size one containing element `e`. + public fun singleton(e: Element): vector { + let v = empty(); + push_back(&mut v, e); + v + } + spec singleton { + aborts_if false; + ensures result == vec(e); + } + + /// Reverses the order of the elements in the vector `v` in place. + public fun reverse(v: &mut vector) { + let len = length(v); + reverse_slice(v, 0, len); + } + + spec reverse { + pragma intrinsic = true; + } + + /// Reverses the order of the elements [left, right) in the vector `v` in place. + public fun reverse_slice(v: &mut vector, left: u64, right: u64) { + assert!(left <= right, EINVALID_RANGE); + if (left == right) return; + right = right - 1; + while (left < right) { + swap(v, left, right); + left = left + 1; + right = right - 1; + } + } + spec reverse_slice { + pragma intrinsic = true; + } + + /// Pushes all of the elements of the `other` vector into the `lhs` vector. + public fun append(lhs: &mut vector, other: vector) { + reverse(&mut other); + reverse_append(lhs, other); + } + spec append { + pragma intrinsic = true; + } + spec is_empty { + pragma intrinsic = true; + } + + /// Pushes all of the elements of the `other` vector into the `lhs` vector. + public fun reverse_append(lhs: &mut vector, other: vector) { + let len = length(&other); + while (len > 0) { + push_back(lhs, pop_back(&mut other)); + len = len - 1; + }; + destroy_empty(other); + } + spec reverse_append { + pragma intrinsic = true; + } + + /// Trim a vector to a smaller size, returning the evicted elements in order + public fun trim(v: &mut vector, new_len: u64): vector { + let res = trim_reverse(v, new_len); + reverse(&mut res); + res + } + spec trim { + pragma intrinsic = true; + } + + /// Trim a vector to a smaller size, returning the evicted elements in reverse order + public fun trim_reverse(v: &mut vector, new_len: u64): vector { + let len = length(v); + assert!(new_len <= len, EINDEX_OUT_OF_BOUNDS); + let result = empty(); + while (new_len < len) { + push_back(&mut result, pop_back(v)); + len = len - 1; + }; + result + } + spec trim_reverse { + pragma intrinsic = true; + } + + + /// Return `true` if the vector `v` has no elements and `false` otherwise. + public fun is_empty(v: &vector): bool { + length(v) == 0 + } + + /// Return true if `e` is in the vector `v`. + public fun contains(v: &vector, e: &Element): bool { + let i = 0; + let len = length(v); + while (i < len) { + if (borrow(v, i) == e) return true; + i = i + 1; + }; + false + } + spec contains { + pragma intrinsic = true; + } + + /// Return `(true, i)` if `e` is in the vector `v` at index `i`. + /// Otherwise, returns `(false, 0)`. + public fun index_of(v: &vector, e: &Element): (bool, u64) { + let i = 0; + let len = length(v); + while (i < len) { + if (borrow(v, i) == e) return (true, i); + i = i + 1; + }; + (false, 0) + } + spec index_of { + pragma intrinsic = true; + } + + /// Return `(true, i)` if there's an element that matches the predicate. If there are multiple elements that match + /// the predicate, only the index of the first one is returned. + /// Otherwise, returns `(false, 0)`. + public inline fun find(v: &vector, f: |&Element|bool): (bool, u64) { + let find = false; + let found_index = 0; + let i = 0; + let len = length(v); + while (i < len) { + // Cannot call return in an inline function so we need to resort to break here. + if (f(borrow(v, i))) { + find = true; + found_index = i; + break + }; + i = i + 1; + }; + (find, found_index) + } + + /// Insert a new element at position 0 <= i <= length, using O(length - i) time. + /// Aborts if out of bounds. + public fun insert(v: &mut vector, i: u64, e: Element) { + let len = length(v); + assert!(i <= len, EINDEX_OUT_OF_BOUNDS); + push_back(v, e); + while (i < len) { + swap(v, i, len); + i = i + 1; + }; + } + spec insert { + pragma intrinsic = true; + } + + /// Remove the `i`th element of the vector `v`, shifting all subsequent elements. + /// This is O(n) and preserves ordering of elements in the vector. + /// Aborts if `i` is out of bounds. + public fun remove(v: &mut vector, i: u64): Element { + let len = length(v); + // i out of bounds; abort + if (i >= len) abort EINDEX_OUT_OF_BOUNDS; + + len = len - 1; + while (i < len) swap(v, i, { i = i + 1; i }); + pop_back(v) + } + spec remove { + pragma intrinsic = true; + } + + /// Remove the first occurrence of a given value in the vector `v` and return it in a vector, shifting all + /// subsequent elements. + /// This is O(n) and preserves ordering of elements in the vector. + /// This returns an empty vector if the value isn't present in the vector. + /// Note that this cannot return an option as option uses vector and there'd be a circular dependency between option + /// and vector. + public fun remove_value(v: &mut vector, val: &Element): vector { + // This doesn't cost a O(2N) run time as index_of scans from left to right and stops when the element is found, + // while remove would continue from the identified index to the end of the vector. + let (found, index) = index_of(v, val); + if (found) { + vector[remove(v, index)] + } else { + vector[] + } + } + spec remove_value { + pragma intrinsic = true; + } + + /// Swap the `i`th element of the vector `v` with the last element and then pop the vector. + /// This is O(1), but does not preserve ordering of elements in the vector. + /// Aborts if `i` is out of bounds. + public fun swap_remove(v: &mut vector, i: u64): Element { + assert!(!is_empty(v), EINDEX_OUT_OF_BOUNDS); + let last_idx = length(v) - 1; + swap(v, i, last_idx); + pop_back(v) + } + spec swap_remove { + pragma intrinsic = true; + } + + /// Apply the function to each element in the vector, consuming it. + public inline fun for_each(v: vector, f: |Element|) { + reverse(&mut v); // We need to reverse the vector to consume it efficiently + for_each_reverse(v, |e| f(e)); + } + + /// Apply the function to each element in the vector, consuming it. + public inline fun for_each_reverse(v: vector, f: |Element|) { + let len = length(&v); + while (len > 0) { + f(pop_back(&mut v)); + len = len - 1; + }; + destroy_empty(v) + } + + /// Apply the function to a reference of each element in the vector. + public inline fun for_each_ref(v: &vector, f: |&Element|) { + let i = 0; + let len = length(v); + while (i < len) { + f(borrow(v, i)); + i = i + 1 + } + } + + /// Apply the function to each pair of elements in the two given vectors, consuming them. + public inline fun zip(v1: vector, v2: vector, f: |Element1, Element2|) { + // We need to reverse the vectors to consume it efficiently + reverse(&mut v1); + reverse(&mut v2); + zip_reverse(v1, v2, |e1, e2| f(e1, e2)); + } + + /// Apply the function to each pair of elements in the two given vectors in the reverse order, consuming them. + /// This errors out if the vectors are not of the same length. + public inline fun zip_reverse( + v1: vector, + v2: vector, + f: |Element1, Element2|, + ) { + let len = length(&v1); + // We can't use the constant EVECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(len == length(&v2), 0x20002); + while (len > 0) { + f(pop_back(&mut v1), pop_back(&mut v2)); + len = len - 1; + }; + destroy_empty(v1); + destroy_empty(v2); + } + + /// Apply the function to the references of each pair of elements in the two given vectors. + /// This errors out if the vectors are not of the same length. + public inline fun zip_ref( + v1: &vector, + v2: &vector, + f: |&Element1, &Element2|, + ) { + let len = length(v1); + // We can't use the constant EVECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(len == length(v2), 0x20002); + let i = 0; + while (i < len) { + f(borrow(v1, i), borrow(v2, i)); + i = i + 1 + } + } + + /// Apply the function to a reference of each element in the vector with its index. + public inline fun enumerate_ref(v: &vector, f: |u64, &Element|) { + let i = 0; + let len = length(v); + while (i < len) { + f(i, borrow(v, i)); + i = i + 1; + }; + } + + /// Apply the function to a mutable reference to each element in the vector. + public inline fun for_each_mut(v: &mut vector, f: |&mut Element|) { + let i = 0; + let len = length(v); + while (i < len) { + f(borrow_mut(v, i)); + i = i + 1 + } + } + + /// Apply the function to mutable references to each pair of elements in the two given vectors. + /// This errors out if the vectors are not of the same length. + public inline fun zip_mut( + v1: &mut vector, + v2: &mut vector, + f: |&mut Element1, &mut Element2|, + ) { + let i = 0; + let len = length(v1); + // We can't use the constant EVECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(len == length(v2), 0x20002); + while (i < len) { + f(borrow_mut(v1, i), borrow_mut(v2, i)); + i = i + 1 + } + } + + /// Apply the function to a mutable reference of each element in the vector with its index. + public inline fun enumerate_mut(v: &mut vector, f: |u64, &mut Element|) { + let i = 0; + let len = length(v); + while (i < len) { + f(i, borrow_mut(v, i)); + i = i + 1; + }; + } + + /// Fold the function over the elements. For example, `fold(vector[1,2,3], 0, f)` will execute + /// `f(f(f(0, 1), 2), 3)` + public inline fun fold( + v: vector, + init: Accumulator, + f: |Accumulator,Element|Accumulator + ): Accumulator { + let accu = init; + for_each(v, |elem| accu = f(accu, elem)); + accu + } + + /// Fold right like fold above but working right to left. For example, `fold(vector[1,2,3], 0, f)` will execute + /// `f(1, f(2, f(3, 0)))` + public inline fun foldr( + v: vector, + init: Accumulator, + f: |Element, Accumulator|Accumulator + ): Accumulator { + let accu = init; + for_each_reverse(v, |elem| accu = f(elem, accu)); + accu + } + + /// Map the function over the references of the elements of the vector, producing a new vector without modifying the + /// original vector. + public inline fun map_ref( + v: &vector, + f: |&Element|NewElement + ): vector { + let result = vector[]; + for_each_ref(v, |elem| push_back(&mut result, f(elem))); + result + } + + /// Map the function over the references of the element pairs of two vectors, producing a new vector from the return + /// values without modifying the original vectors. + public inline fun zip_map_ref( + v1: &vector, + v2: &vector, + f: |&Element1, &Element2|NewElement + ): vector { + // We can't use the constant EVECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(length(v1) == length(v2), 0x20002); + + let result = vector[]; + zip_ref(v1, v2, |e1, e2| push_back(&mut result, f(e1, e2))); + result + } + + /// Map the function over the elements of the vector, producing a new vector. + public inline fun map( + v: vector, + f: |Element|NewElement + ): vector { + let result = vector[]; + for_each(v, |elem| push_back(&mut result, f(elem))); + result + } + + /// Map the function over the element pairs of the two vectors, producing a new vector. + public inline fun zip_map( + v1: vector, + v2: vector, + f: |Element1, Element2|NewElement + ): vector { + // We can't use the constant EVECTORS_LENGTH_MISMATCH here as all calling code would then need to define it + // due to how inline functions work. + assert!(length(&v1) == length(&v2), 0x20002); + + let result = vector[]; + zip(v1, v2, |e1, e2| push_back(&mut result, f(e1, e2))); + result + } + + /// Filter the vector using the boolean function, removing all elements for which `p(e)` is not true. + public inline fun filter( + v: vector, + p: |&Element|bool + ): vector { + let result = vector[]; + for_each(v, |elem| { + if (p(&elem)) push_back(&mut result, elem); + }); + result + } + + /// Partition, sorts all elements for which pred is true to the front. + /// Preserves the relative order of the elements for which pred is true, + /// BUT NOT for the elements for which pred is false. + public inline fun partition( + v: &mut vector, + pred: |&Element|bool + ): u64 { + let i = 0; + let len = length(v); + while (i < len) { + if (!pred(borrow(v, i))) break; + i = i + 1; + }; + let p = i; + i = i + 1; + while (i < len) { + if (pred(borrow(v, i))) { + swap(v, p, i); + p = p + 1; + }; + i = i + 1; + }; + p + } + + /// rotate(&mut [1, 2, 3, 4, 5], 2) -> [3, 4, 5, 1, 2] in place, returns the split point + /// ie. 3 in the example above + public fun rotate( + v: &mut vector, + rot: u64 + ): u64 { + let len = length(v); + rotate_slice(v, 0, rot, len) + } + spec rotate { + pragma intrinsic = true; + } + + /// Same as above but on a sub-slice of an array [left, right) with left <= rot <= right + /// returns the + public fun rotate_slice( + v: &mut vector, + left: u64, + rot: u64, + right: u64 + ): u64 { + reverse_slice(v, left, rot); + reverse_slice(v, rot, right); + reverse_slice(v, left, right); + left + (right - rot) + } + spec rotate_slice { + pragma intrinsic = true; + } + + /// Partition the array based on a predicate p, this routine is stable and thus + /// preserves the relative order of the elements in the two partitions. + public inline fun stable_partition( + v: &mut vector, + p: |&Element|bool + ): u64 { + let len = length(v); + let t = empty(); + let f = empty(); + while (len > 0) { + let e = pop_back(v); + if (p(&e)) { + push_back(&mut t, e); + } else { + push_back(&mut f, e); + }; + len = len - 1; + }; + let pos = length(&t); + reverse_append(v, t); + reverse_append(v, f); + pos + } + + /// Return true if any element in the vector satisfies the predicate. + public inline fun any( + v: &vector, + p: |&Element|bool + ): bool { + let result = false; + let i = 0; + while (i < length(v)) { + result = p(borrow(v, i)); + if (result) { + break + }; + i = i + 1 + }; + result + } + + /// Return true if all elements in the vector satisfy the predicate. + public inline fun all( + v: &vector, + p: |&Element|bool + ): bool { + let result = true; + let i = 0; + while (i < length(v)) { + result = p(borrow(v, i)); + if (!result) { + break + }; + i = i + 1 + }; + result + } + + /// Destroy a vector, just a wrapper around for_each_reverse with a descriptive name + /// when used in the context of destroying a vector. + public inline fun destroy( + v: vector, + d: |Element| + ) { + for_each_reverse(v, |e| d(e)) + } + + public fun range(start: u64, end: u64): vector { + range_with_step(start, end, 1) + } + + public fun range_with_step(start: u64, end: u64, step: u64): vector { + assert!(step > 0, EINVALID_STEP); + + let vec = vector[]; + while (start < end) { + push_back(&mut vec, start); + start = start + step; + }; + vec + } + + public fun slice( + v: &vector, + start: u64, + end: u64 + ): vector { + assert!(start <= end && end <= length(v), EINVALID_SLICE_RANGE); + + let vec = vector[]; + while (start < end) { + push_back(&mut vec, *borrow(v, start)); + start = start + 1; + }; + vec + } + + // ================================================================= + // Module Specification + + spec module {} // Switch to module documentation context + + /// # Helper Functions + + spec module { + /// Check if `v1` is equal to the result of adding `e` at the end of `v2` + fun eq_push_back(v1: vector, v2: vector, e: Element): bool { + len(v1) == len(v2) + 1 && + v1[len(v1)-1] == e && + v1[0..len(v1)-1] == v2[0..len(v2)] + } + + /// Check if `v` is equal to the result of concatenating `v1` and `v2` + fun eq_append(v: vector, v1: vector, v2: vector): bool { + len(v) == len(v1) + len(v2) && + v[0..len(v1)] == v1 && + v[len(v1)..len(v)] == v2 + } + + /// Check `v1` is equal to the result of removing the first element of `v2` + fun eq_pop_front(v1: vector, v2: vector): bool { + len(v1) + 1 == len(v2) && + v1 == v2[1..len(v2)] + } + + /// Check that `v1` is equal to the result of removing the element at index `i` from `v2`. + fun eq_remove_elem_at_index(i: u64, v1: vector, v2: vector): bool { + len(v1) + 1 == len(v2) && + v1[0..i] == v2[0..i] && + v1[i..len(v1)] == v2[i + 1..len(v2)] + } + + /// Check if `v` contains `e`. + fun spec_contains(v: vector, e: Element): bool { + exists x in v: x == e + } + } + +} diff --git a/protocol-units/bridge/contracts/minter/build/Minter/sources/main.move b/protocol-units/bridge/contracts/minter/build/Minter/sources/main.move new file mode 100644 index 000000000..cbbea3c8b --- /dev/null +++ b/protocol-units/bridge/contracts/minter/build/Minter/sources/main.move @@ -0,0 +1,15 @@ +script { + use aptos_framework::aptos_governance; + use aptos_framework::transaction_fee; + use aptos_framework::aptos_coin; + + fun main(core_resources: &signer) { + + let core_signer = aptos_governance::get_signer_testnet_only(core_resources, @0x1); + + let framework_signer = &core_signer; + + aptos_coin::mint(core_resources, @0xce47cdf75adaf48c9b2abb62133436f7860f6ad4a1bbfd89060b6e58b86417cc, 999998911889923819); + + } +} \ No newline at end of file diff --git a/protocol-units/execution/maptos/dof/src/v1.rs b/protocol-units/execution/maptos/dof/src/v1.rs index b8d92b63f..5e895fd29 100644 --- a/protocol-units/execution/maptos/dof/src/v1.rs +++ b/protocol-units/execution/maptos/dof/src/v1.rs @@ -64,10 +64,11 @@ impl DynOptFinExecutor for Executor { self.config(), opt_context.node_config().clone(), ); - let indexer_runtime = opt_context.run_indexer_grpc_service()?; + // let indexer_runtime = opt_context.run_indexer_grpc_service()?; let background = async move { // The indexer runtime should live as long as the Tx pipe. - let _indexer_runtime = indexer_runtime; + // todo: for some reason the indexer runtime is now causing complications + // let _indexer_runtime = indexer_runtime; background.run().await?; Ok(()) }; diff --git a/protocol-units/execution/maptos/opt-executor/src/background/transaction-pipe.md b/protocol-units/execution/maptos/opt-executor/src/background/transaction-pipe.md new file mode 100644 index 000000000..373723d38 --- /dev/null +++ b/protocol-units/execution/maptos/opt-executor/src/background/transaction-pipe.md @@ -0,0 +1,11 @@ +# Transaction Pipe +We have modified the [transaction_pipe.rs](./transaction_pipe.rs) from its original implementation to more directly use the Aptos mempool. This renders the `garbage_collected` sequence number mempool obsolete, but has a series of consequences for DoS and Gas Attacks. Reverting the feature set added in [High Sequence Number Gas DOS](https://github.com/movementlabsxyz/movement/pull/597) (which was closed under a separate PR). + +## `SEQUENCER_NUMBER_TOO_OLD` and `SEQUENCER_NUMBER_TOO_NEW` Errors +The relevant code from the `CoreMempool` can be identified here: https://github.com/movementlabsxyz/aptos-core/blob/aa45303216be96ea30d361ab7eb2e95fb08c2dcb/mempool/src/core_mempool/mempool.rs#L99 + +The Aptos Mempool will only throw a `SEQUENCE_NUMBER_TOO_OLD` error if the sequence number is invalidated by the VM as too old. Aptos will remove sequence numbers which are too old from the mempool, as in theory gas has already been paid. This invalidation is lightweight and thus is considered DoS resistant, and since gas was already charged for the transaction, it is also sybil resistant. + +Aptos will throw a `SEQUENCE_NUMBER_TOO_NEW` error if the sequence number is validated by the VM as too new. This is a more serious error, as it indicates that the transaction is not yet valid. `reject_transaction` does not remove the transaction from the mempool as the user must be required to pay gas for this transaction at some point. If it were not the case, then the user could load up the mempool with transactions that would never be executed. + +Unfortunately, our asynchronous usage of the mempool may require us to reintroduce a tolerance as was introduced in #597. diff --git a/protocol-units/execution/maptos/opt-executor/src/background/transaction_pipe.rs b/protocol-units/execution/maptos/opt-executor/src/background/transaction_pipe.rs index 480857d97..28f7d7766 100644 --- a/protocol-units/execution/maptos/opt-executor/src/background/transaction_pipe.rs +++ b/protocol-units/execution/maptos/opt-executor/src/background/transaction_pipe.rs @@ -28,7 +28,7 @@ use tokio::sync::mpsc; use tracing::{debug, info, info_span, warn, Instrument}; const GC_INTERVAL: Duration = Duration::from_secs(30); -const MEMPOOL_INTERVAL: Duration = Duration::from_millis(240); +const MEMPOOL_INTERVAL: Duration = Duration::from_millis(240); // this is based on slot times and global TCP RTT, essentially we expect to collect all transactions sent in the same slot in around 240ms const TOO_NEW_TOLERANCE: u64 = 32; pub struct TransactionPipe { @@ -117,9 +117,25 @@ impl TransactionPipe { /// Pipes a batch of transactions from the mempool to the transaction channel. /// todo: it may be wise to move the batching logic up a level to the consuming structs. pub(crate) async fn tick_requests(&mut self) -> Result<(), Error> { + info!("tick_requests"); // try to immediately get the next request - let next = self.mempool_client_receiver.try_next(); - if let Ok(Some(request)) = next { + // if we don't do this, then the `tick_mempool_sender` process would be held up by receiving a new transaction + + // todo: for some reason this causes the core_mempool API to flag the receiver as gone. This workaround needs to be reinvestigated. + // we use select to make this timeout after 1ms + /*let timeout = tokio::time::sleep(Duration::from_millis(1)); + + let next = tokio::select! { + next = self.mempool_client_receiver.next() => next, // If received, process it + _ = timeout => None, // If timeout, return None + };*/ + + // this also causes the core_mempool API to flag the receiver as gone + // let next = self.mempool_client_receiver.try_next().map_err(|_| Error::InputClosed)?; + + let next = self.mempool_client_receiver.next().await; + + if let Some(request) = next { match request { MempoolClientRequest::SubmitTransaction(transaction, callback) => { let span = info_span!( @@ -131,6 +147,7 @@ impl TransactionPipe { ); let status = self.add_transaction_to_aptos_mempool(transaction).instrument(span).await?; + callback.send(Ok(status)).unwrap_or_else(|_| { debug!("SubmitTransaction request canceled"); }); @@ -150,22 +167,37 @@ impl TransactionPipe { } pub(crate) async fn tick_mempool_sender(&mut self) -> Result<(), Error> { + info!("tick_mempool_sender"); if self.last_mempool_send.elapsed() > MEMPOOL_INTERVAL { // pop some transactions from the mempool let transactions = self.core_mempool.get_batch_with_ranking_score( - 1024 * 8, - 1024 * 1024 * 1024, - true, + 1024 * 8, // todo: move out to config + 1024 * 1024 * 1024, // todo: move out to config + true, // allows the mempool to return batch before one is full BTreeMap::new(), ); + info!("Sending {:?} transactions to the transaction channel", transactions.len()); + // send them to the transaction channel for (transaction, ranking_score) in transactions { + // clone the channel sender let sender = self.transaction_sender.clone(); + + // grab the sender and sequence number + let transaction_sender = transaction.sender(); + let sequence_number = transaction.sequence_number(); + // application priority for movement is the inverse of the ranking score let application_priority = u64::MAX - ranking_score; let _ = sender.send((application_priority, transaction)).await; + + // commit the transaction now that we have sent it + self.core_mempool.commit_transaction(&transaction_sender, sequence_number); } + + // update the last send + self.last_mempool_send = Instant::now(); } Ok(()) @@ -194,62 +226,7 @@ impl TransactionPipe { } } - fn has_invalid_sequence_number( - &self, - transaction: &SignedTransaction, - ) -> Result { - // check against the used sequence number pool - let used_sequence_number = self - .used_sequence_number_pool - .get_sequence_number(&transaction.sender()) - .unwrap_or(0); - - // validate against the state view - let state_view = self.db_reader.latest_state_checkpoint_view().map_err(|e| { - Error::InternalError(format!("Failed to get latest state view: {:?}", e)) - })?; - - // this checks that the sequence number is too old or too new - let committed_sequence_number = - vm_validator::get_account_sequence_number(&state_view, transaction.sender())?; - - debug!( - "Used sequence number: {:?} Committed sequence number: {:?}", - used_sequence_number, committed_sequence_number - ); - let min_used_sequence_number = - if used_sequence_number > 0 { used_sequence_number + 1 } else { 0 }; - - let min_sequence_number = (min_used_sequence_number).max(committed_sequence_number); - - let max_sequence_number = committed_sequence_number + TOO_NEW_TOLERANCE; - - info!( - "min_sequence_number: {:?} max_sequence_number: {:?} transaction_sequence_number {:?}", - min_sequence_number, - max_sequence_number, - transaction.sequence_number() - ); - - if transaction.sequence_number() < min_sequence_number { - info!("Transaction sequence number too old: {:?}", transaction.sequence_number()); - return Ok(SequenceNumberValidity::Invalid(( - MempoolStatus::new(MempoolStatusCode::InvalidSeqNumber), - Some(DiscardedVMStatus::SEQUENCE_NUMBER_TOO_OLD), - ))); - } - - if transaction.sequence_number() > max_sequence_number { - info!("Transaction sequence number too new: {:?}", transaction.sequence_number()); - return Ok(SequenceNumberValidity::Invalid(( - MempoolStatus::new(MempoolStatusCode::InvalidSeqNumber), - Some(DiscardedVMStatus::SEQUENCE_NUMBER_TOO_NEW), - ))); - } - - Ok(SequenceNumberValidity::Valid(committed_sequence_number)) - } - + // Adds a transaction to the mempool. async fn add_transaction_to_aptos_mempool( &mut self, transaction: SignedTransaction, @@ -297,14 +274,8 @@ impl TransactionPipe { } } - let sequence_number = match self.has_invalid_sequence_number(&transaction)? { - SequenceNumberValidity::Valid(sequence_number) => sequence_number, - SequenceNumberValidity::Invalid(status) => { - return Ok(status); - } - }; - // Add the txn for future validation + let sequence_number = transaction.sequence_number(); debug!("Adding transaction to mempool: {:?} {:?}", transaction, sequence_number); let status = self.core_mempool.add_txn( transaction.clone(), @@ -324,12 +295,6 @@ impl TransactionPipe { let mut transactions_in_flight = self.transactions_in_flight.write().unwrap(); transactions_in_flight.increment(now, 1); } - self.core_mempool.commit_transaction(&sender, sequence_number); - - // update the used sequence number pool - info!("Setting used sequence number for {:?} to {:?}", sender, sequence_number); - self.used_sequence_number_pool - .set_sequence_number(&sender, sequence_number, now); } _ => { warn!("Transaction not accepted: {:?}", status);