serai/coins/monero/tests/runner.rs
Luke Parker a646ec5aaa
Squashed commit of the following:
commit e0a9e8825d6c22c797fb84e26ed6ef10136ca9c2
Author: Luke Parker <lukeparker5132@gmail.com>
Date:   Fri Jan 6 04:24:08 2023 -0500

    Remove Scanner::address

    It either needed to return an Option, panic on misconfiguration, or return a
    distinct Scanner type based on burning bug immunity to offer this API properly.
    Panicking wouldn't be proper, and the Option<Address> would've been... awkward.
    The new register_subaddress function, maintaining the needed functionality,
    also provides further clarity on the intended side effect of the previously
    present Scanner::address function.

commit 7359360ab2fc8c9255c6f58250c214252ce217a4
Author: Luke Parker <lukeparker5132@gmail.com>
Date:   Fri Jan 6 01:35:02 2023 -0500

    fmt/clippy from last commit

commit 80d912fc19cd268f3b019a9d9961a48b2c45e828
Author: Luke Parker <lukeparker5132@gmail.com>
Date:   Thu Jan 5 19:36:49 2023 -0500

    Add Substrate "assets" pallet

    While over-engineered for our purposes, it's still usable.

    Also cleans the runtime a bit.

commit 2ed2944b6598d75bdc3c995aaf39b717846207de
Author: Luke Parker <lukeparker5132@gmail.com>
Date:   Wed Jan 4 23:09:58 2023 -0500

    Remove the timestamp pallet

    It was needed for contracts, which has since been removed. We now no longer
    need it.

commit 7fc1fc2dccecebe1d94cb7b4c00f2b5cb271c87b
Author: Luke Parker <lukeparker5132@gmail.com>
Date:   Wed Jan 4 22:52:41 2023 -0500

    Initial validator sets pallet (#187)

    * Initial work on a Validator Sets pallet

    * Update Validator Set docs per current discussions

    * Update validator-sets primitives and storage handling

    * Add validator set pallets to deny.toml

    * Remove Curve from primitives

    Since we aren't reusing keys across coins, there's no reason for it to be
    on-chain (as previously planned).

    * Update documentation on Validator Sets

    * Use Twox64Concat instead of Identity

    Ensures an even distribution of keys. While xxhash is breakable, these keys
    aren't manipulatable by users.

    * Add math ops on Amount and define a coin as 1e8

    * Add validator-sets to the runtime and remove contracts

    Also removes the randomness pallet which was only required by the contracts
    runtime.

    Does not remove the contracts folder yet so they can still be referred to while
    validator-sets is under development. Does remove them from Cargo.toml.

    * Add vote function to validator-sets

    * Remove contracts folder

    * Create an event for the Validator Sets pallet

    * Remove old contracts crates from deny.toml

    * Remove line from staking branch

    * Remove staking from runtime

    * Correct VS Config in runtime

    * cargo update

    * Resolve a few PR comments on terminology

    * Create a serai-primitives crate

    Move types such as Amount/Coin out of validator-sets. Will be expanded in the
    future.

    * Fixes for last commit

    * Don't reserve set 0

    * Further fixes

    * Add files meant for last commit

    * Remove Staking transfer

commit 3309295911d22177bd68972d138aea2f8658eb5f
Author: Luke Parker <lukeparker5132@gmail.com>
Date:   Wed Jan 4 06:17:00 2023 -0500

    Reorder coins in README by market cap

commit db5d19cad33ccf067d876b7f5b7cca47c228e2fc
Author: Luke Parker <lukeparker5132@gmail.com>
Date:   Wed Jan 4 06:07:58 2023 -0500

    Update README

commit 606484d744b1c6cc408382994c77f1def25d3e7d
Author: Luke Parker <lukeparker5132@gmail.com>
Date:   Wed Jan 4 03:17:36 2023 -0500

    cargo update

commit 3a319b229f
Author: akildemir <aeg_asd@hotmail.com>
Date:   Wed Jan 4 16:26:25 2023 +0300

    update address public API design

commit d9fa88fa76
Author: akildemir <aeg_asd@hotmail.com>
Date:   Mon Jan 2 13:35:06 2023 +0300

    fix clippy error

commit cc722e897b
Merge: cafa9b3 eeca440
Author: akildemir <aeg_asd@hotmail.com>
Date:   Mon Jan 2 11:39:04 2023 +0300

    Merge https://github.com/serai-dex/serai into develop

commit cafa9b361e
Author: akildemir <aeg_asd@hotmail.com>
Date:   Mon Jan 2 11:38:26 2023 +0300

    fix build errors

commit ce5b5f2b37
Merge: f502d67 49c4acf
Author: akildemir <aeg_asd@hotmail.com>
Date:   Sun Jan 1 15:16:25 2023 +0300

    Merge https://github.com/serai-dex/serai into develop

commit f502d67282
Author: akildemir <aeg_asd@hotmail.com>
Date:   Thu Dec 22 13:13:09 2022 +0300

    fix pr issues

commit 26ffb226d4
Author: akildemir <aeg_asd@hotmail.com>
Date:   Thu Dec 22 13:11:43 2022 +0300

    remove extraneous rpc call

commit 0e829f8531
Author: akildemir <aeg_asd@hotmail.com>
Date:   Thu Dec 15 13:56:53 2022 +0300

    add scan tests

commit 5123c7f121
Author: akildemir <aeg_asd@hotmail.com>
Date:   Thu Dec 15 13:56:13 2022 +0300

    add new address functions & comments
2023-01-06 04:33:17 -05:00

280 lines
8.6 KiB
Rust

use core::ops::Deref;
use std::collections::HashSet;
use lazy_static::lazy_static;
use zeroize::Zeroizing;
use rand_core::OsRng;
use curve25519_dalek::{constants::ED25519_BASEPOINT_TABLE, scalar::Scalar};
use tokio::sync::Mutex;
use monero_serai::{
Protocol, random_scalar,
wallet::{
ViewPair, Scanner,
address::{Network, AddressType, AddressSpec, AddressMeta, MoneroAddress},
SpendableOutput,
},
rpc::Rpc,
};
pub fn random_address() -> (Scalar, ViewPair, MoneroAddress) {
let spend = random_scalar(&mut OsRng);
let spend_pub = &spend * &ED25519_BASEPOINT_TABLE;
let view = Zeroizing::new(random_scalar(&mut OsRng));
(
spend,
ViewPair::new(spend_pub, view.clone()),
MoneroAddress {
meta: AddressMeta::new(Network::Mainnet, AddressType::Standard),
spend: spend_pub,
view: view.deref() * &ED25519_BASEPOINT_TABLE,
},
)
}
// TODO: Support transactions already on-chain
// TODO: Don't have a side effect of mining blocks more blocks than needed under race conditions
// TODO: mine as much as needed instead of default 10 blocks
pub async fn mine_until_unlocked(rpc: &Rpc, addr: &str, tx_hash: [u8; 32]) {
// mine until tx is in a block
let mut height = rpc.get_height().await.unwrap();
let mut found = false;
while !found {
let block = rpc.get_block(height - 1).await.unwrap();
found = match block.txs.iter().find(|&&x| x == tx_hash) {
Some(_) => true,
None => {
rpc.generate_blocks(addr, 1).await.unwrap();
height += 1;
false
}
}
}
// mine 9 more blocks to unlock the tx
rpc.generate_blocks(addr, 9).await.unwrap();
}
// Mines 60 blocks and returns an unlocked miner TX output.
pub async fn get_miner_tx_output(rpc: &Rpc, view: &ViewPair) -> SpendableOutput {
let mut scanner = Scanner::from_view(view.clone(), Some(HashSet::new()));
// Mine 60 blocks to unlock a miner TX
let start = rpc.get_height().await.unwrap();
rpc
.generate_blocks(&view.address(Network::Mainnet, AddressSpec::Standard).to_string(), 60)
.await
.unwrap();
let block = rpc.get_block(start).await.unwrap();
scanner.scan(rpc, &block).await.unwrap().swap_remove(0).ignore_timelock().swap_remove(0)
}
pub async fn rpc() -> Rpc {
let rpc = Rpc::new("http://127.0.0.1:18081".to_string()).unwrap();
// Only run once
if rpc.get_height().await.unwrap() != 1 {
return rpc;
}
let addr = MoneroAddress {
meta: AddressMeta::new(Network::Mainnet, AddressType::Standard),
spend: &random_scalar(&mut OsRng) * &ED25519_BASEPOINT_TABLE,
view: &random_scalar(&mut OsRng) * &ED25519_BASEPOINT_TABLE,
}
.to_string();
// Mine 40 blocks to ensure decoy availability
rpc.generate_blocks(&addr, 40).await.unwrap();
assert!(!matches!(rpc.get_protocol().await.unwrap(), Protocol::Unsupported(_)));
rpc
}
lazy_static! {
pub static ref SEQUENTIAL: Mutex<()> = Mutex::new(());
}
#[macro_export]
macro_rules! async_sequential {
($(async fn $name: ident() $body: block)*) => {
$(
#[tokio::test]
async fn $name() {
let guard = runner::SEQUENTIAL.lock().await;
let local = tokio::task::LocalSet::new();
local.run_until(async move {
if let Err(err) = tokio::task::spawn_local(async move { $body }).await {
drop(guard);
Err(err).unwrap()
}
}).await;
}
)*
}
}
#[macro_export]
macro_rules! test {
(
$name: ident,
(
$first_tx: expr,
$first_checks: expr,
),
$((
$tx: expr,
$checks: expr,
)$(,)?),*
) => {
async_sequential! {
async fn $name() {
use core::{ops::Deref, any::Any};
use std::collections::HashSet;
#[cfg(feature = "multisig")]
use std::collections::HashMap;
use zeroize::Zeroizing;
use rand_core::OsRng;
use curve25519_dalek::constants::ED25519_BASEPOINT_TABLE;
#[cfg(feature = "multisig")]
use transcript::{Transcript, RecommendedTranscript};
#[cfg(feature = "multisig")]
use frost::{
curve::Ed25519,
tests::{THRESHOLD, key_gen},
};
use monero_serai::{
random_scalar,
wallet::{
address::{Network, AddressSpec}, ViewPair, Scanner, SignableTransaction,
SignableTransactionBuilder,
},
};
use runner::{random_address, rpc, mine_until_unlocked, get_miner_tx_output};
type Builder = SignableTransactionBuilder;
// Run each function as both a single signer and as a multisig
#[allow(clippy::redundant_closure_call)]
for multisig in [false, true] {
// Only run the multisig variant if multisig is enabled
if multisig {
#[cfg(not(feature = "multisig"))]
continue;
}
let spend = Zeroizing::new(random_scalar(&mut OsRng));
#[cfg(feature = "multisig")]
let keys = key_gen::<_, Ed25519>(&mut OsRng);
let spend_pub = if !multisig {
spend.deref() * &ED25519_BASEPOINT_TABLE
} else {
#[cfg(not(feature = "multisig"))]
panic!("Multisig branch called without the multisig feature");
#[cfg(feature = "multisig")]
keys[&1].group_key().0
};
let rpc = rpc().await;
let view = ViewPair::new(spend_pub, Zeroizing::new(random_scalar(&mut OsRng)));
let addr = view.address(Network::Mainnet, AddressSpec::Standard);
let miner_tx = get_miner_tx_output(&rpc, &view).await;
let builder = SignableTransactionBuilder::new(
rpc.get_protocol().await.unwrap(),
rpc.get_fee().await.unwrap(),
Some(random_address().2),
);
let sign = |tx: SignableTransaction| {
let rpc = rpc.clone();
let spend = spend.clone();
#[cfg(feature = "multisig")]
let keys = keys.clone();
async move {
if !multisig {
tx.sign(&mut OsRng, &rpc, &spend).await.unwrap()
} else {
#[cfg(not(feature = "multisig"))]
panic!("Multisig branch called without the multisig feature");
#[cfg(feature = "multisig")]
{
let mut machines = HashMap::new();
for i in 1 ..= THRESHOLD {
machines.insert(
i,
tx
.clone()
.multisig(
&rpc,
keys[&i].clone(),
RecommendedTranscript::new(b"Monero Serai Test Transaction"),
rpc.get_height().await.unwrap() - 10,
)
.await
.unwrap(),
);
}
frost::tests::sign_without_caching(&mut OsRng, machines, &[])
}
}
}
};
// TODO: Generate a distinct wallet for each transaction to prevent overlap
let next_addr = addr;
let temp = Box::new({
let mut builder = builder.clone();
builder.add_input(miner_tx);
let (tx, state) = ($first_tx)(rpc.clone(), builder, next_addr).await;
let signed = sign(tx).await;
rpc.publish_transaction(&signed).await.unwrap();
mine_until_unlocked(&rpc, &random_address().2.to_string(), signed.hash()).await;
let tx = rpc.get_transaction(signed.hash()).await.unwrap();
let scanner =
Scanner::from_view(view.clone(), Some(HashSet::new()));
($first_checks)(rpc.clone(), tx, scanner, state).await
});
#[allow(unused_variables, unused_mut, unused_assignments)]
let mut carried_state: Box<dyn Any> = temp;
$(
let (tx, state) = ($tx)(
rpc.clone(),
builder.clone(),
next_addr,
*carried_state.downcast().unwrap()
).await;
let signed = sign(tx).await;
rpc.publish_transaction(&signed).await.unwrap();
mine_until_unlocked(&rpc, &random_address().2.to_string(), signed.hash()).await;
let tx = rpc.get_transaction(signed.hash()).await.unwrap();
#[allow(unused_assignments)]
{
let scanner =
Scanner::from_view(view.clone(), Some(HashSet::new()));
carried_state =
Box::new(($checks)(rpc.clone(), tx, scanner, state).await);
}
)*
}
}
}
}
}