Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Governance: refactor #719

Merged
merged 20 commits into from
Nov 30, 2022
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 9 additions & 4 deletions apps/src/lib/cli/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,8 @@ pub struct Context {
pub global_config: GlobalConfig,
/// The ledger configuration for a specific chain ID
pub config: Config,
/// Native token's address
pub native_token: Address,
}

impl Context {
Expand All @@ -66,10 +68,12 @@ impl Context {
let genesis_file_path = global_args
.base_dir
.join(format!("{}.toml", global_config.default_chain_id.as_str()));
let wallet = Wallet::load_or_new_from_genesis(
&chain_dir,
genesis_config::open_genesis_config(&genesis_file_path)?,
);
let genesis = genesis_config::read_genesis_config(&genesis_file_path);
let native_token = genesis.native_token;
let default_genesis =
genesis_config::open_genesis_config(genesis_file_path)?;
let wallet =
Wallet::load_or_new_from_genesis(&chain_dir, default_genesis);

// If the WASM dir specified, put it in the config
match global_args.wasm_dir.as_ref() {
Expand All @@ -88,6 +92,7 @@ impl Context {
wallet,
global_config,
config,
native_token,
})
}

Expand Down
11 changes: 11 additions & 0 deletions apps/src/lib/client/rpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,17 @@ pub async fn query_proposal(_ctx: Context, args: args::QueryProposal) {
println!("{:4}Status: pending", "");
} else if start_epoch <= current_epoch && current_epoch <= end_epoch
{
let votes = get_proposal_votes(client, start_epoch, id).await;
let partial_proposal_result =
compute_tally(client, start_epoch, votes).await;
println!(
"{:4}Yay votes: {}",
"", partial_proposal_result.total_yay_power
);
println!(
"{:4}Nay votes: {}",
"", partial_proposal_result.total_nay_power
);
println!("{:4}Status: on-going", "");
} else {
let votes = get_proposal_votes(client, start_epoch, id).await;
Expand Down
18 changes: 11 additions & 7 deletions apps/src/lib/client/tx.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use itertools::Either::*;
use namada::ledger::governance::storage as gov_storage;
use namada::ledger::pos::{BondId, Bonds, Unbonds};
use namada::proto::Tx;
use namada::types::address::{nam, Address};
use namada::types::address::Address;
use namada::types::governance::{
OfflineProposal, OfflineVote, Proposal, ProposalVote,
};
Expand All @@ -23,7 +23,7 @@ use namada::types::transaction::governance::{
};
use namada::types::transaction::nft::{CreateNft, MintNft};
use namada::types::transaction::{pos, InitAccount, InitValidator, UpdateVp};
use namada::types::{address, storage, token};
use namada::types::{storage, token};
use namada::{ledger, vm};

use super::rpc;
Expand Down Expand Up @@ -639,9 +639,13 @@ pub async fn submit_init_proposal(mut ctx: Context, args: args::InitProposal) {
safe_exit(1)
};

let balance = rpc::get_token_balance(&client, &nam(), &proposal.author)
.await
.unwrap_or_default();
let balance = rpc::get_token_balance(
&client,
&ctx.native_token,
&proposal.author,
)
.await
.unwrap_or_default();
if balance
< token::Amount::from(governance_parameters.min_proposal_fund)
{
Expand Down Expand Up @@ -836,7 +840,7 @@ async fn is_safe_voting_window(

match proposal_end_epoch {
Some(proposal_end_epoch) => {
!namada::ledger::governance::vp::is_valid_validator_voting_period(
!namada::ledger::governance::utils::is_valid_validator_voting_period(
current_epoch,
proposal_start_epoch,
proposal_end_epoch,
Expand Down Expand Up @@ -911,7 +915,7 @@ pub async fn submit_bond(ctx: Context, args: args::Bond) {
// Check bond's source (source for delegation or validator for self-bonds)
// balance
let bond_source = source.as_ref().unwrap_or(&validator);
let balance_key = token::balance_key(&address::nam(), bond_source);
let balance_key = token::balance_key(&ctx.native_token, bond_source);
let client = HttpClient::new(args.tx.ledger_address.clone()).unwrap();
match rpc::query_storage_value::<token::Amount>(&client, &balance_key).await
{
Expand Down
22 changes: 10 additions & 12 deletions apps/src/lib/client/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -612,18 +612,16 @@ pub fn init_network(
})
}

if let Some(token) = &mut config.token {
token.iter_mut().for_each(|(name, config)| {
if config.address.is_none() {
let address = address::gen_established_address("token");
config.address = Some(address.to_string());
wallet.add_address(name.clone(), address);
}
if config.vp.is_none() {
config.vp = Some("vp_token".to_string());
}
})
}
config.token.iter_mut().for_each(|(name, config)| {
if config.address.is_none() {
let address = address::gen_established_address("token");
config.address = Some(address.to_string());
wallet.add_address(name.clone(), address);
}
if config.vp.is_none() {
config.vp = Some("vp_token".to_string());
}
});

if let Some(implicit) = &mut config.implicit {
implicit.iter_mut().for_each(|(name, config)| {
Expand Down
125 changes: 82 additions & 43 deletions apps/src/lib/config/genesis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,10 +104,13 @@ pub mod genesis_config {
pub struct GenesisConfig {
// Genesis timestamp
pub genesis_time: Rfc3339String,
// Name of the native token - this must one of the tokens included in
// the `token` field
pub native_token: String,
// Initial validator set
pub validator: HashMap<String, ValidatorConfig>,
// Token accounts present at genesis
pub token: Option<HashMap<String, TokenAccountConfig>>,
pub token: HashMap<String, TokenAccountConfig>,
// Established accounts present at genesis
pub established: Option<HashMap<String, EstablishedAccountConfig>>,
// Implicit accounts present at genesis
Expand Down Expand Up @@ -479,32 +482,53 @@ pub mod genesis_config {
}

pub fn load_genesis_config(config: GenesisConfig) -> Genesis {
let wasms = config.wasm;
let validators: HashMap<String, Validator> = config
.validator
.iter()
.map(|(name, cfg)| (name.clone(), load_validator(cfg, &wasms)))
.collect();
let established_accounts: HashMap<String, EstablishedAccount> = config
.established
.unwrap_or_default()
let GenesisConfig {
genesis_time,
native_token,
validator,
token,
established,
implicit,
parameters,
pos_params,
gov_params,
wasm,
} = config;

let native_token = Address::decode(
token
.get(&native_token)
.expect(
"Native token's alias must be present in the declared \
tokens",
)
.address
.as_ref()
.expect("Missing native token address"),
)
.expect("Invalid address");

let validators: HashMap<String, Validator> = validator
.iter()
.map(|(name, cfg)| (name.clone(), load_established(cfg, &wasms)))
.map(|(name, cfg)| (name.clone(), load_validator(cfg, &wasm)))
.collect();
let implicit_accounts: HashMap<String, ImplicitAccount> = config
.implicit
let established_accounts: HashMap<String, EstablishedAccount> =
established
.unwrap_or_default()
.iter()
.map(|(name, cfg)| (name.clone(), load_established(cfg, &wasm)))
.collect();
let implicit_accounts: HashMap<String, ImplicitAccount> = implicit
.unwrap_or_default()
.iter()
.map(|(name, cfg)| (name.clone(), load_implicit(cfg)))
.collect();
let token_accounts = config
.token
.unwrap_or_default()
let token_accounts = token
.iter()
.map(|(_name, cfg)| {
load_token(
cfg,
&wasms,
&wasm,
&validators,
&established_accounts,
&implicit_accounts,
Expand All @@ -514,53 +538,66 @@ pub mod genesis_config {

let parameters = Parameters {
epoch_duration: EpochDuration {
min_num_of_blocks: config.parameters.min_num_of_blocks,
min_num_of_blocks: parameters.min_num_of_blocks,
min_duration: namada::types::time::Duration::seconds(
config.parameters.min_duration,
parameters.min_duration,
)
.into(),
},
max_expected_time_per_block:
namada::types::time::Duration::seconds(
config.parameters.max_expected_time_per_block,
parameters.max_expected_time_per_block,
)
.into(),
vp_whitelist: config.parameters.vp_whitelist.unwrap_or_default(),
tx_whitelist: config.parameters.tx_whitelist.unwrap_or_default(),
vp_whitelist: parameters.vp_whitelist.unwrap_or_default(),
tx_whitelist: parameters.tx_whitelist.unwrap_or_default(),
};

let GovernanceParamsConfig {
min_proposal_fund,
max_proposal_code_size,
min_proposal_period,
max_proposal_content_size,
min_proposal_grace_epochs,
max_proposal_period,
} = gov_params;
let gov_params = GovParams {
min_proposal_fund: config.gov_params.min_proposal_fund,
max_proposal_code_size: config.gov_params.max_proposal_code_size,
min_proposal_period: config.gov_params.min_proposal_period,
max_proposal_period: config.gov_params.max_proposal_period,
max_proposal_content_size: config
.gov_params
.max_proposal_content_size,
min_proposal_grace_epochs: config
.gov_params
.min_proposal_grace_epochs,
min_proposal_fund,
max_proposal_code_size,
min_proposal_period,
max_proposal_content_size,
min_proposal_grace_epochs,
max_proposal_period,
};

let PosParamsConfig {
max_validator_slots,
pipeline_len,
unbonding_len,
votes_per_token,
block_proposer_reward,
block_vote_reward,
duplicate_vote_slash_rate,
light_client_attack_slash_rate,
} = pos_params;
let pos_params = PosParams {
max_validator_slots: config.pos_params.max_validator_slots,
pipeline_len: config.pos_params.pipeline_len,
unbonding_len: config.pos_params.unbonding_len,
votes_per_token: BasisPoints::new(
config.pos_params.votes_per_token,
),
block_proposer_reward: config.pos_params.block_proposer_reward,
block_vote_reward: config.pos_params.block_vote_reward,
max_validator_slots,
pipeline_len,
unbonding_len,
votes_per_token: BasisPoints::new(votes_per_token),
block_proposer_reward,
block_vote_reward,
duplicate_vote_slash_rate: BasisPoints::new(
config.pos_params.duplicate_vote_slash_rate,
duplicate_vote_slash_rate,
),
light_client_attack_slash_rate: BasisPoints::new(
config.pos_params.light_client_attack_slash_rate,
light_client_attack_slash_rate,
),
};

let mut genesis = Genesis {
genesis_time: config.genesis_time.try_into().unwrap(),
genesis_time: genesis_time.try_into().unwrap(),
native_token,
validators: validators.into_values().collect(),
token_accounts,
established_accounts: established_accounts.into_values().collect(),
Expand Down Expand Up @@ -608,6 +645,7 @@ pub mod genesis_config {
#[borsh_init(init)]
pub struct Genesis {
pub genesis_time: DateTimeUtc,
pub native_token: Address,
pub validators: Vec<Validator>,
pub token_accounts: Vec<TokenAccount>,
pub established_accounts: Vec<EstablishedAccount>,
Expand Down Expand Up @@ -839,6 +877,7 @@ pub fn genesis() -> Genesis {
parameters,
pos_params: PosParams::default(),
gov_params: GovParams::default(),
native_token: address::nam(),
}
}

Expand Down
6 changes: 6 additions & 0 deletions apps/src/lib/node/ledger/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use crate::config::TendermintMode;
use crate::facade::tendermint_proto::abci::CheckTxType;
use crate::facade::tower_abci::{response, split, Server};
use crate::node::ledger::broadcaster::Broadcaster;
use crate::node::ledger::config::genesis;
use crate::node::ledger::shell::{Error, MempoolTxType, Shell};
use crate::node::ledger::shims::abcipp_shim::AbcippShim;
use crate::node::ledger::shims::abcipp_shim_types::shim::{Request, Response};
Expand Down Expand Up @@ -423,13 +424,18 @@ fn start_abci_broadcaster_shell(
// Construct our ABCI application.
let tendermint_mode = config.tendermint.tendermint_mode.clone();
let ledger_address = config.shell.ledger_address;
#[cfg(not(feature = "dev"))]
let genesis = genesis::genesis(&config.shell.base_dir, &config.chain_id);
#[cfg(feature = "dev")]
let genesis = genesis::genesis();
let (shell, abci_service) = AbcippShim::new(
config,
wasm_dir,
broadcaster_sender,
&db_cache,
vp_wasm_compilation_cache,
tx_wasm_compilation_cache,
genesis.native_token,
);

// Channel for signalling shut down to ABCI server
Expand Down
2 changes: 1 addition & 1 deletion apps/src/lib/node/ledger/protocol/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ pub enum Error {
#[error("IBC Token native VP: {0}")]
IbcTokenNativeVpError(namada::ledger::ibc::vp::IbcTokenError),
#[error("Governance native VP error: {0}")]
GovernanceNativeVpError(namada::ledger::governance::vp::Error),
GovernanceNativeVpError(namada::ledger::governance::Error),
#[error("SlashFund native VP error: {0}")]
SlashFundNativeVpError(namada::ledger::slash_fund::Error),
#[error("Ethereum bridge native VP error: {0}")]
Expand Down
Loading