Skip to content

Commit

Permalink
test: added mainnet-tools which mocks all mainnet cardano tools
Browse files Browse the repository at this point in the history
  • Loading branch information
dkijania committed Jun 27, 2022
1 parent cfd942f commit 1a55dd7
Show file tree
Hide file tree
Showing 11 changed files with 337 additions and 16 deletions.
26 changes: 26 additions & 0 deletions mainnet-tools/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[package]
name = "mainnet-tools"
version = "0.1.0"
authors = ["dkijania <[email protected]>"]
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
hex = "0.4"
bech32 = "0.8.1"
structopt = "0.3"
thiserror = "1.0"
futures = "0.3.8"
serde_json = "1.0"
signals-handler = { path = "../signals-handler" }
serde = { version = "1", features = ["derive"] }
tokio = { version = "1.2", features = ["macros","rt","process"] }
jormungandr-lib = { git = "https://github.com/input-output-hk/jormungandr.git", branch = "catalyst-fund9" }
catalyst-toolbox = { git = "https://github.com/input-output-hk/catalyst-toolbox.git", branch = "catalyst-fund9", features = [ "test-api" ]}
chain-addr = { git = "https://github.com/input-output-hk/chain-libs.git", branch = "catalyst-fund9", features = [ "property-test-api" ] }
chain-crypto = { git = "https://github.com/input-output-hk/chain-libs.git", branch = "catalyst-fund9", features = [ "property-test-api" ] }
tempdir = "0.3.7"
thor = { git = "https://github.com/input-output-hk/jormungandr.git", branch = "catalyst-fund9" }
rand = "0.8"
assert_fs = "1.0"
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use futures::future::FutureExt;
use std::fs::File;
use std::io::Write;
use std::path::{Path, PathBuf};

use futures::future::FutureExt;
use structopt::StructOpt;
use thiserror::Error;

Expand Down
7 changes: 7 additions & 0 deletions mainnet-tools/src/bin/voting-tools-mock.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
use mainnet_tools::voting_tools::VotingToolsCommand;
use structopt::StructOpt;

pub fn main() {
std::env::set_var("RUST_BACKTRACE", "full");
VotingToolsCommand::from_args().exec()
}
54 changes: 54 additions & 0 deletions mainnet-tools/src/db_sync/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use catalyst_toolbox::snapshot::VotingRegistration;
use jormungandr_lib::interfaces::BlockDate;
use std::collections::hash_map::Entry;
use std::collections::HashMap;

#[derive(Default)]
pub struct DbSyncInstance {
state: HashMap<BlockDate, Vec<VotingRegistration>>,
settings: Settings,
}

impl DbSyncInstance {
pub fn notify(&mut self, block_date: BlockDate, registration: VotingRegistration) {
match self.state.entry(block_date) {
Entry::Vacant(e) => {
e.insert(vec![registration]);
}
Entry::Occupied(mut e) => {
e.get_mut().push(registration);
}
}
}

pub fn query_all_registration_transactions(&self) -> Vec<VotingRegistration> {
self.state
.values()
.cloned()
.fold(vec![], |mut vec, mut value| {
vec.append(&mut value);
vec
})
}

pub fn settings(&self) -> &Settings {
&self.settings
}
}

#[derive(Debug, Clone)]
pub struct Settings {
pub db_name: String,
pub db_user: String,
pub db_host: String,
}

impl Default for Settings {
fn default() -> Self {
Self {
db_name: "mock".to_string(),
db_user: "mock".to_string(),
db_host: "mock".to_string(),
}
}
}
4 changes: 4 additions & 0 deletions mainnet-tools/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
pub mod db_sync;
pub mod network;
pub mod voting_tools;
pub mod wallet;
33 changes: 33 additions & 0 deletions mainnet-tools/src/network/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use crate::db_sync::DbSyncInstance;
use catalyst_toolbox::snapshot::VotingRegistration;
use jormungandr_lib::interfaces::BlockDate;

pub struct MainnetNetwork<'a> {
block_date: BlockDate,
observers: Vec<&'a mut DbSyncInstance>,
}

impl Default for MainnetNetwork<'_> {
fn default() -> Self {
Self {
block_date: BlockDate::new(0, 0),
observers: vec![],
}
}
}

impl<'a> MainnetNetwork<'a> {
pub fn accept(&mut self, registration: VotingRegistration) {
self.notify_all(self.block_date, registration);
}

pub fn sync_with(&mut self, observer: &'a mut DbSyncInstance) {
self.observers.push(observer);
}

fn notify_all(&mut self, block_date: BlockDate, registration: VotingRegistration) {
for observer in &mut self.observers {
observer.notify(block_date, registration.clone());
}
}
}
60 changes: 60 additions & 0 deletions mainnet-tools/src/voting_tools/command.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
use super::content;
use std::path::Path;
use std::path::PathBuf;
use structopt::StructOpt;

pub const PATH_TO_DYNAMIC_CONTENT: &str = "PATH_TO_DYNAMIC_CONTENT";

#[derive(StructOpt, Debug)]
pub struct VotingToolsCommand {
#[structopt(long = "mainnet")]
pub mainnet: bool,

#[structopt(long = "testnet-magic")]
pub testnet_magic: Option<u64>,

#[structopt(long = "db")]
pub db: String,

#[structopt(long = "db-user")]
pub db_user: String,

#[structopt(long = "db-host")]
pub db_host: PathBuf,

#[structopt(long = "out-file")]
pub out_file: PathBuf,

#[structopt(long = "scale")]
pub scale: u64,

#[structopt(long = "slot-no")]
pub slot_no: Option<u64>,
}

impl VotingToolsCommand {
pub fn exec(&self) {
println!("Params: {:?}", self);
println!("sleeping 5 sec..");
std::thread::sleep(std::time::Duration::from_secs(5));
println!("saving {:?}", self.out_file);

match std::env::var(PATH_TO_DYNAMIC_CONTENT) {
Ok(value) => {
std::fs::copy(value, &self.out_file).unwrap();
}
Err(_) => {
write_snapshot(
serde_json::to_string(&content::default()).unwrap(),
&self.out_file,
);
}
};
}
}

pub fn write_snapshot<P: AsRef<Path>>(content: String, path: P) {
use std::io::Write;
let mut file = std::fs::File::create(&path).unwrap();
file.write_all(content.as_bytes()).unwrap();
}
50 changes: 50 additions & 0 deletions mainnet-tools/src/voting_tools/content.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
use catalyst_toolbox::snapshot::registration::Delegations;
use catalyst_toolbox::snapshot::VotingRegistration;
use jormungandr_lib::crypto::account::Identifier;

pub fn default() -> Vec<VotingRegistration> {
vec![
VotingRegistration {
reward_address: "0xe1ffff2912572257b59dca84c965e4638a09f1524af7a15787eb0d8a46"
.to_string(),
stake_public_key: "0xe7d6616840734686855ec80ee9658f5ead9e29e494ec6889a5d1988b50eb8d0f"
.to_string(),
voting_power: 177689370111.into(),
delegations: Delegations::Legacy(
Identifier::from_hex(
"0xc21ddb4abb04bd5ce21091eef1676e44889d806e6e1a6a9a7dc25c0eba54cc33",
)
.unwrap(),
),
voting_purpose: 0,
},
VotingRegistration {
reward_address: "0xe1fffc8bcb1578a15413bf11413639fa270a9ffa36d9a0c4d2c93536fe"
.to_string(),
stake_public_key: "0x2f9a90d87321a255efd038fea5df2a2349ea2c32fa584b73f2a46f655f235919"
.to_string(),
voting_power: 9420156337.into(),
delegations: Delegations::Legacy(
Identifier::from_hex(
"0x3f656a1ba4ea8b33c81961fee6f15f09600f024435b1a7ada1e5b77b03a41a6d",
)
.unwrap(),
),
voting_purpose: 0,
},
VotingRegistration {
reward_address: "0xe1fff825e1bf009d35d9160f6340250b581f5d37c17538e960c0410b20"
.to_string(),
stake_public_key: "0x66ae1553036548b99b93c783811bb281be5a196a12d950bda4ac9b83630afbd1"
.to_string(),
voting_power: 82168168290u64.into(),
delegations: Delegations::Legacy(
Identifier::from_hex(
"0x125860fc4870bb480d1d2a97f101e1c5c845c0222400fdaba7bcca93e79bd66e",
)
.unwrap(),
),
voting_purpose: 0,
},
]
}
52 changes: 52 additions & 0 deletions mainnet-tools/src/voting_tools/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
mod command;
mod content;

use crate::db_sync::DbSyncInstance;
use crate::voting_tools::command::PATH_TO_DYNAMIC_CONTENT;
use assert_fs::fixture::PathChild;
use assert_fs::TempDir;
pub use command::VotingToolsCommand;
use std::env;
use std::io::Write;
use std::path::Path;
use std::path::PathBuf;

#[derive(Debug, Clone)]
pub struct VotingToolsMock {
path: PathBuf,
}

impl Default for VotingToolsMock {
fn default() -> Self {
Self {
path: Path::new("voting-tools-mock").to_path_buf(),
}
}
}

impl VotingToolsMock {
pub fn connect_to_db_sync(self, db_sync: &DbSyncInstance, temp_dir: &TempDir) -> Self {
let voting_registrations = db_sync.query_all_registration_transactions();
let snapshot_tmp = temp_dir.child("snapshot.tmp");

env::set_var(
PATH_TO_DYNAMIC_CONTENT,
snapshot_tmp.path().to_str().unwrap(),
);

println!("{:?}", snapshot_tmp.path());

let mut file = std::fs::File::create(&snapshot_tmp.path()).unwrap();
file.write_all(
serde_json::to_string(&voting_registrations)
.unwrap()
.as_bytes(),
)
.unwrap();
self
}

pub fn path(&self) -> PathBuf {
self.path.to_path_buf()
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
mod sender;

use bech32::ToBase32;
use catalyst_toolbox::snapshot::registration::{Delegations, VotingRegistration};
use chain_addr::Discrimination;
use jormungandr_lib::crypto::account::Identifier;
use jormungandr_lib::crypto::account::SigningKey;
use vitup::config::Block0Initial;
use jormungandr_lib::interfaces::Address;
use sender::RegistrationSender;

pub struct MainnetWallet {
inner: thor::Wallet,
catalyst: thor::Wallet,
reward_address: String,
stake_public_key: String,
stake: u64,
Expand All @@ -14,7 +19,7 @@ impl MainnetWallet {
pub fn new(stake: u64) -> Self {
let mut rng = rand::thread_rng();
Self {
inner: thor::Wallet::new_account(&mut rng, Discrimination::Production),
catalyst: thor::Wallet::new_account(&mut rng, Discrimination::Production),
stake,
reward_address: "0x".to_owned()
+ &SigningKey::generate_extended(&mut rng)
Expand All @@ -31,29 +36,42 @@ impl MainnetWallet {
self.reward_address.clone()
}

pub fn reward_address_as_bech32(&self) -> String {
let bytes = hex::decode(self.reward_address.clone().trim_start_matches("0x")).unwrap();
bech32::encode("stake", &bytes.to_base32(), bech32::Variant::Bech32).unwrap()
}

pub fn stake_public_key(&self) -> String {
self.stake_public_key.clone()
}

pub fn catalyst_secret_key(&self) -> chain_crypto::SecretKey<chain_crypto::Ed25519Extended> {
self.inner.secret_key()
self.catalyst.secret_key()
}

pub fn as_voting_registration(&self) -> VotingRegistration {
VotingRegistration {
pub fn catalyst_public_key(&self) -> Identifier {
self.catalyst.secret_key().to_public().into()
}

pub fn catalyst_address(&self) -> Address {
self.catalyst.address()
}

pub fn send_voting_registration(&self, delegations: Delegations) -> RegistrationSender {
RegistrationSender::new(VotingRegistration {
stake_public_key: self.stake_public_key(),
voting_power: self.stake.into(),
reward_address: self.reward_address(),
delegations: Delegations::Legacy(self.inner.identifier().into()),
delegations,
voting_purpose: 0,
}
})
}

pub fn as_initial_entry(&self) -> Block0Initial {
Block0Initial::External {
address: self.inner.address().to_string(),
funds: self.stake,
role: Default::default(),
}
pub fn send_direct_voting_registration(&self) -> RegistrationSender {
self.send_voting_registration(Delegations::Legacy(self.catalyst.identifier().into()))
}

pub fn stake(&self) -> u64 {
self.stake
}
}
Loading

0 comments on commit 1a55dd7

Please sign in to comment.