Files
serai/substrate/client/tests/common/genesis_liquidity.rs

120 lines
3.7 KiB
Rust
Raw Permalink Normal View History

use std::collections::HashMap;
use rand_core::{RngCore, OsRng};
use zeroize::Zeroizing;
use dalek_ff_group::Ristretto;
use ciphersuite::Ciphersuite;
2025-08-18 07:19:40 -04:00
use dkg_musig::musig;
use schnorrkel::Schnorrkel;
Move `develop` to `patch-polkadot-sdk` (#678) * Update `build-dependencies` CI action * Update `develop` to `patch-polkadot-sdk` Allows us to finally remove the old `serai-dex/substrate` repository _and_ should have CI pass without issue on `develop` again. The changes made here should be trivial and maintain all prior behavior/functionality. The most notable are to `chain_spec.rs`, in order to still use a SCALE-encoded `GenesisConfig` (avoiding `serde_json`). * CI fixes * Add `/usr/local/opt/llvm/lib` to paths on macOS hosts * Attempt to use `LD_LIBRARY_PATH` in macOS GitHub CI * Use `libp2p 0.56` in `serai-node` * Correct Windows build dependencies * Correct `llvm/lib` path on macOS * Correct how macOS 13 and 14 have different homebrew paths * Use `sw_vers` instead of `uname` on macOS Yields the macOS version instead of the kernel's version. * Replace hard-coded path with the intended env variable to fix macOS 13 * Add `libclang-dev` as dependency to the Debian Dockerfile * Set the `CODE` storage slot * Update to a version of substrate without `wasmtimer` Turns out `wasmtimer` is WASM only. This should restore the node's functioning on non-WASM environments. * Restore `clang` as a dependency due to the Debian Dockerfile as we require a C++ compiler * Move from Debian bookworm to trixie * Restore `chain_getBlockBin` to the RPC * Always generate a new key for the P2P network * Mention every account on-chain before they publish a transaction `CheckNonce` required accounts have a provider in order to even have their nonce considered. This shims that by claiming every account has a provider at the start of a block, if it signs a transaction. The actual execution could presumably diverge between block building (which sets the provider before each transaction) and execution (which sets the providers at the start of the block). It doesn't diverge in our current configuration and it won't be propagated to `next` (which doesn't use `CheckNonce`). Also uses explicit indexes for the `serai_abi::{Call, Event}` `enum`s. * Adopt `patch-polkadot-sdk` with fixed peering * Manually insert the authority discovery key into the keystore I did try pulling in `pallet-authority-discovery` for this, updating `SessionKeys`, but that was insufficient for whatever reason. * Update to latest `substrate-wasm-builder` * Fix timeline for incrementing providers e1671dd71b219bf7439c28f1c5bdf988b1e00ff5 incremented the providers for every single transaction's sender before execution, noting the solution was fragile but it worked for us at this time. It did not work for us at this time. The new solution replaces `inc_providers` with direct access to the `Account` `StorageMap` to increment the providers, achieving the desired goal, _without_ emitting an event (which is ordered, and the disparate order between building and execution was causing mismatches of the state root). This solution is also fragile and may also be insufficient. None of this code exists anymore on `next` however. It just has to work sufficiently for now. * clippy
2025-10-05 10:58:08 -04:00
use sp_core::Pair as PairTrait;
use serai_abi::{
genesis_liquidity::primitives::{oraclize_values_message, Values},
in_instructions::primitives::{Batch, InInstruction, InInstructionWithBalance},
primitives::{
insecure_pair_from_name, Amount, ExternalBalance, BlockHash, ExternalCoin, ExternalNetworkId,
NetworkId, SeraiAddress, EXTERNAL_COINS,
},
validator_sets::primitives::{musig_context, Session, ValidatorSet},
};
use serai_client::{Serai, SeraiGenesisLiquidity};
use crate::common::{in_instructions::provide_batch, tx::publish_tx};
#[allow(dead_code)]
pub async fn set_up_genesis(
serai: &Serai,
values: &HashMap<ExternalCoin, u64>,
) -> (HashMap<ExternalCoin, Vec<(SeraiAddress, Amount)>>, HashMap<ExternalNetworkId, u32>) {
// make accounts with amounts
let mut accounts = HashMap::new();
for coin in EXTERNAL_COINS {
// make 5 accounts per coin
let mut values = vec![];
for _ in 0 .. 5 {
let mut address = SeraiAddress::new([0; 32]);
OsRng.fill_bytes(&mut address.0);
values.push((address, Amount(OsRng.next_u64() % 10u64.pow(coin.decimals()))));
}
accounts.insert(coin, values);
}
// send a batch per coin
let mut batch_ids: HashMap<ExternalNetworkId, u32> = HashMap::new();
for coin in EXTERNAL_COINS {
// set up instructions
let instructions = accounts[&coin]
.iter()
.map(|(addr, amount)| InInstructionWithBalance {
instruction: InInstruction::GenesisLiquidity(*addr),
balance: ExternalBalance { coin, amount: *amount },
})
.collect::<Vec<_>>();
// set up bloch hash
let mut block = BlockHash([0; 32]);
OsRng.fill_bytes(&mut block.0);
// set up batch id
batch_ids
.entry(coin.network())
.and_modify(|v| {
*v += 1;
})
.or_insert(0);
let batch =
Batch { network: coin.network(), id: batch_ids[&coin.network()], block, instructions };
provide_batch(serai, batch).await;
}
// set values relative to each other. We can do that without checking for genesis period blocks
// since we are running in test(fast-epoch) mode.
// TODO: Random values here
let values = Values {
monero: values[&ExternalCoin::Monero],
ether: values[&ExternalCoin::Ether],
dai: values[&ExternalCoin::Dai],
};
set_values(serai, &values).await;
(accounts, batch_ids)
}
#[allow(dead_code)]
async fn set_values(serai: &Serai, values: &Values) {
// prepare a Musig tx to oraclize the relative values
let pair = insecure_pair_from_name("Alice");
let public = pair.public();
// we publish the tx in set 1
let set = ValidatorSet { session: Session(1), network: NetworkId::Serai };
let public_key = <Ristretto as Ciphersuite>::read_G::<&[u8]>(&mut public.0.as_ref()).unwrap();
let secret_key = <Ristretto as Ciphersuite>::read_F::<&[u8]>(
&mut pair.as_ref().secret.to_bytes()[.. 32].as_ref(),
)
.unwrap();
assert_eq!(Ristretto::generator() * secret_key, public_key);
let threshold_keys =
2025-08-18 07:19:40 -04:00
musig::<Ristretto>(musig_context(set), Zeroizing::new(secret_key), &[public_key]).unwrap();
let sig = frost::tests::sign_without_caching(
&mut OsRng,
frost::tests::algorithm_machines(
&mut OsRng,
&Schnorrkel::new(b"substrate"),
&HashMap::from([(threshold_keys.params().i(), threshold_keys.into())]),
),
&oraclize_values_message(&set, values),
);
// oraclize values
let _ =
Move `develop` to `patch-polkadot-sdk` (#678) * Update `build-dependencies` CI action * Update `develop` to `patch-polkadot-sdk` Allows us to finally remove the old `serai-dex/substrate` repository _and_ should have CI pass without issue on `develop` again. The changes made here should be trivial and maintain all prior behavior/functionality. The most notable are to `chain_spec.rs`, in order to still use a SCALE-encoded `GenesisConfig` (avoiding `serde_json`). * CI fixes * Add `/usr/local/opt/llvm/lib` to paths on macOS hosts * Attempt to use `LD_LIBRARY_PATH` in macOS GitHub CI * Use `libp2p 0.56` in `serai-node` * Correct Windows build dependencies * Correct `llvm/lib` path on macOS * Correct how macOS 13 and 14 have different homebrew paths * Use `sw_vers` instead of `uname` on macOS Yields the macOS version instead of the kernel's version. * Replace hard-coded path with the intended env variable to fix macOS 13 * Add `libclang-dev` as dependency to the Debian Dockerfile * Set the `CODE` storage slot * Update to a version of substrate without `wasmtimer` Turns out `wasmtimer` is WASM only. This should restore the node's functioning on non-WASM environments. * Restore `clang` as a dependency due to the Debian Dockerfile as we require a C++ compiler * Move from Debian bookworm to trixie * Restore `chain_getBlockBin` to the RPC * Always generate a new key for the P2P network * Mention every account on-chain before they publish a transaction `CheckNonce` required accounts have a provider in order to even have their nonce considered. This shims that by claiming every account has a provider at the start of a block, if it signs a transaction. The actual execution could presumably diverge between block building (which sets the provider before each transaction) and execution (which sets the providers at the start of the block). It doesn't diverge in our current configuration and it won't be propagated to `next` (which doesn't use `CheckNonce`). Also uses explicit indexes for the `serai_abi::{Call, Event}` `enum`s. * Adopt `patch-polkadot-sdk` with fixed peering * Manually insert the authority discovery key into the keystore I did try pulling in `pallet-authority-discovery` for this, updating `SessionKeys`, but that was insufficient for whatever reason. * Update to latest `substrate-wasm-builder` * Fix timeline for incrementing providers e1671dd71b219bf7439c28f1c5bdf988b1e00ff5 incremented the providers for every single transaction's sender before execution, noting the solution was fragile but it worked for us at this time. It did not work for us at this time. The new solution replaces `inc_providers` with direct access to the `Account` `StorageMap` to increment the providers, achieving the desired goal, _without_ emitting an event (which is ordered, and the disparate order between building and execution was causing mismatches of the state root). This solution is also fragile and may also be insufficient. None of this code exists anymore on `next` however. It just has to work sufficiently for now. * clippy
2025-10-05 10:58:08 -04:00
publish_tx(serai, &SeraiGenesisLiquidity::oraclize_values(*values, sig.to_bytes().into()))
.await;
}