VoteProgram -> VoteState

This commit is contained in:
Greg Fitzgerald 2019-02-01 15:50:11 -07:00 committed by Grimes
parent 6058bfb687
commit 9c07a8c26a
7 changed files with 67 additions and 78 deletions

View File

@ -10,7 +10,7 @@ use solana::thin_client::{poll_gossip_for_leader, ThinClient};
use solana::voting_keypair::{RemoteVoteSigner, VotingKeypair}; use solana::voting_keypair::{RemoteVoteSigner, VotingKeypair};
use solana_sdk::pubkey::Pubkey; use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::{Keypair, KeypairUtil}; use solana_sdk::signature::{Keypair, KeypairUtil};
use solana_sdk::vote_program::VoteProgram; use solana_sdk::vote_program::VoteState;
use solana_sdk::vote_transaction::VoteTransaction; use solana_sdk::vote_transaction::VoteTransaction;
use solana_vote_signer::rpc::{LocalVoteSigner, VoteSigner}; use solana_vote_signer::rpc::{LocalVoteSigner, VoteSigner};
use std::fs::File; use std::fs::File;
@ -112,7 +112,7 @@ fn create_and_fund_vote_account(
info!("Checking for vote account registration"); info!("Checking for vote account registration");
let vote_account_user_data = client.get_account_userdata(&vote_account); let vote_account_user_data = client.get_account_userdata(&vote_account);
if let Ok(Some(vote_account_user_data)) = vote_account_user_data { if let Ok(Some(vote_account_user_data)) = vote_account_user_data {
if let Ok(vote_state) = VoteProgram::deserialize(&vote_account_user_data) { if let Ok(vote_state) = VoteState::deserialize(&vote_account_user_data) {
if vote_state.node_id == pubkey { if vote_state.node_id == pubkey {
return Ok(()); return Ok(());
} }

View File

@ -7,7 +7,7 @@ use solana_sdk::account::KeyedAccount;
use solana_sdk::native_program::ProgramError; use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey; use solana_sdk::pubkey::Pubkey;
use solana_sdk::solana_entrypoint; use solana_sdk::solana_entrypoint;
use solana_sdk::vote_program::{self, Vote, VoteInstruction, VoteProgram}; use solana_sdk::vote_program::{self, Vote, VoteInstruction, VoteState};
fn register(keyed_accounts: &mut [KeyedAccount]) -> Result<(), ProgramError> { fn register(keyed_accounts: &mut [KeyedAccount]) -> Result<(), ProgramError> {
if !vote_program::check_id(&keyed_accounts[1].account.owner) { if !vote_program::check_id(&keyed_accounts[1].account.owner) {
@ -15,9 +15,7 @@ fn register(keyed_accounts: &mut [KeyedAccount]) -> Result<(), ProgramError> {
Err(ProgramError::InvalidArgument)?; Err(ProgramError::InvalidArgument)?;
} }
// TODO: a single validator could register multiple "vote accounts" let vote_state = VoteState::new(*keyed_accounts[0].signer_key().unwrap());
// which would clutter the "accounts" structure. See github issue 1654.
let vote_state = VoteProgram::new(*keyed_accounts[0].signer_key().unwrap());
vote_state.serialize(&mut keyed_accounts[1].account.userdata)?; vote_state.serialize(&mut keyed_accounts[1].account.userdata)?;
Ok(()) Ok(())
@ -29,7 +27,7 @@ fn process_vote(keyed_accounts: &mut [KeyedAccount], vote: Vote) -> Result<(), P
Err(ProgramError::InvalidArgument)?; Err(ProgramError::InvalidArgument)?;
} }
let mut vote_state = VoteProgram::deserialize(&keyed_accounts[0].account.userdata)?; let mut vote_state = VoteState::deserialize(&keyed_accounts[0].account.userdata)?;
// TODO: Integrity checks // TODO: Integrity checks
// a) Verify the vote's bank hash matches what is expected // a) Verify the vote's bank hash matches what is expected
@ -66,7 +64,7 @@ fn entrypoint(
match deserialize(data).map_err(|_| ProgramError::InvalidUserdata)? { match deserialize(data).map_err(|_| ProgramError::InvalidUserdata)? {
VoteInstruction::RegisterAccount => register(keyed_accounts), VoteInstruction::RegisterAccount => register(keyed_accounts),
VoteInstruction::NewVote(vote) => { VoteInstruction::Vote(vote) => {
debug!("{:?} by {}", vote, keyed_accounts[0].signer_key().unwrap()); debug!("{:?} by {}", vote, keyed_accounts[0].signer_key().unwrap());
solana_metrics::submit( solana_metrics::submit(
solana_metrics::influxdb::Point::new("vote-native") solana_metrics::influxdb::Point::new("vote-native")
@ -85,85 +83,79 @@ mod tests {
use solana_sdk::signature::{Keypair, KeypairUtil}; use solana_sdk::signature::{Keypair, KeypairUtil};
use solana_sdk::vote_program; use solana_sdk::vote_program;
fn create_vote_program(tokens: u64) -> Account { fn create_vote_account(tokens: u64) -> Account {
let space = vote_program::get_max_size(); let space = vote_program::get_max_size();
Account::new(tokens, space, vote_program::id()) Account::new(tokens, space, vote_program::id())
} }
fn register_and_deserialize( fn register_and_deserialize(
voter_id: &Pubkey, from_id: &Pubkey,
voter_account: &mut Account, from_account: &mut Account,
vote_state_id: &Pubkey, vote_id: &Pubkey,
vote_state_account: &mut Account, vote_account: &mut Account,
) -> Result<VoteProgram, ProgramError> { ) -> Result<VoteState, ProgramError> {
let mut keyed_accounts = [ let mut keyed_accounts = [
KeyedAccount::new(voter_id, true, voter_account), KeyedAccount::new(from_id, true, from_account),
KeyedAccount::new(vote_state_id, false, vote_state_account), KeyedAccount::new(vote_id, false, vote_account),
]; ];
register(&mut keyed_accounts)?; register(&mut keyed_accounts)?;
let vote_state = VoteProgram::deserialize(&vote_state_account.userdata).unwrap(); let vote_state = VoteState::deserialize(&vote_account.userdata).unwrap();
Ok(vote_state) Ok(vote_state)
} }
fn vote_and_deserialize( fn vote_and_deserialize(
vote_state_id: &Pubkey, vote_id: &Pubkey,
vote_state_account: &mut Account, vote_account: &mut Account,
vote: Vote, vote: Vote,
) -> Result<VoteProgram, ProgramError> { ) -> Result<VoteState, ProgramError> {
let mut keyed_accounts = [KeyedAccount::new(vote_state_id, true, vote_state_account)]; let mut keyed_accounts = [KeyedAccount::new(vote_id, true, vote_account)];
process_vote(&mut keyed_accounts, vote)?; process_vote(&mut keyed_accounts, vote)?;
let vote_state = VoteProgram::deserialize(&vote_state_account.userdata).unwrap(); let vote_state = VoteState::deserialize(&vote_account.userdata).unwrap();
Ok(vote_state) Ok(vote_state)
} }
#[test] #[test]
fn test_voter_registration() { fn test_voter_registration() {
let voter_id = Keypair::new().pubkey(); let from_id = Keypair::new().pubkey();
let mut voter_account = Account::new(100, 0, Pubkey::default()); let mut from_account = Account::new(100, 0, Pubkey::default());
let vote_state_id = Keypair::new().pubkey(); let vote_id = Keypair::new().pubkey();
let mut vote_state_account = create_vote_program(100); let mut vote_account = create_vote_account(100);
let vote_state = register_and_deserialize( let vote_state =
&voter_id, register_and_deserialize(&from_id, &mut from_account, &vote_id, &mut vote_account)
&mut voter_account, .unwrap();
&vote_state_id, assert_eq!(vote_state.node_id, from_id);
&mut vote_state_account,
)
.unwrap();
assert_eq!(vote_state.node_id, voter_id);
assert!(vote_state.votes.is_empty()); assert!(vote_state.votes.is_empty());
} }
#[test] #[test]
fn test_vote() { fn test_vote() {
let voter_id = Keypair::new().pubkey(); let from_id = Keypair::new().pubkey();
let mut voter_account = Account::new(100, 0, Pubkey::default()); let mut from_account = Account::new(100, 0, Pubkey::default());
let vote_state_id = Keypair::new().pubkey(); let vote_id = Keypair::new().pubkey();
let mut vote_state_account = create_vote_program(100); let mut vote_account = create_vote_account(100);
let mut keyed_accounts = [ let mut keyed_accounts = [
KeyedAccount::new(&voter_id, true, &mut voter_account), KeyedAccount::new(&from_id, true, &mut from_account),
KeyedAccount::new(&vote_state_id, false, &mut vote_state_account), KeyedAccount::new(&vote_id, false, &mut vote_account),
]; ];
register(&mut keyed_accounts).unwrap(); register(&mut keyed_accounts).unwrap();
let vote = Vote::new(1); let vote = Vote::new(1);
let vote_state = let vote_state = vote_and_deserialize(&vote_id, &mut vote_account, vote.clone()).unwrap();
vote_and_deserialize(&vote_state_id, &mut vote_state_account, vote.clone()).unwrap();
assert_eq!(vote_state.votes, vec![vote]); assert_eq!(vote_state.votes, vec![vote]);
} }
#[test] #[test]
// TODO: Should this work?
fn test_vote_without_registration() { fn test_vote_without_registration() {
let vote_state_id = Keypair::new().pubkey(); let vote_id = Keypair::new().pubkey();
let mut vote_state_account = create_vote_program(100); let mut vote_account = create_vote_account(100);
let vote = Vote::new(1); let vote = Vote::new(1);
let vote_state = let vote_state = vote_and_deserialize(&vote_id, &mut vote_account, vote.clone()).unwrap();
vote_and_deserialize(&vote_state_id, &mut vote_state_account, vote.clone()).unwrap(); assert_eq!(vote_state.node_id, Pubkey::default());
assert_eq!(vote_state.votes, vec![vote]); assert_eq!(vote_state.votes, vec![vote]);
} }
} }

View File

@ -43,34 +43,34 @@ pub enum VoteInstruction {
/// * Transaction::keys[1] - the new "vote account" to be associated with the validator /// * Transaction::keys[1] - the new "vote account" to be associated with the validator
/// identified by keys[0] for voting /// identified by keys[0] for voting
RegisterAccount, RegisterAccount,
NewVote(Vote), Vote(Vote),
} }
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq)] #[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct VoteProgram { pub struct VoteState {
pub votes: VecDeque<Vote>, pub votes: VecDeque<Vote>,
pub node_id: Pubkey, pub node_id: Pubkey,
} }
pub fn get_max_size() -> usize { pub fn get_max_size() -> usize {
// Upper limit on the size of the Vote State. Equal to // Upper limit on the size of the Vote State. Equal to
// sizeof(VoteProgram) when votes.len() is MAX_VOTE_HISTORY // sizeof(VoteState) when votes.len() is MAX_VOTE_HISTORY
let mut vote_program = VoteProgram::default(); let mut vote_program = VoteState::default();
vote_program.votes = VecDeque::from(vec![Vote::default(); MAX_VOTE_HISTORY]); vote_program.votes = VecDeque::from(vec![Vote::default(); MAX_VOTE_HISTORY]);
serialized_size(&vote_program).unwrap() as usize serialized_size(&vote_program).unwrap() as usize
} }
impl VoteProgram { impl VoteState {
pub fn new(node_id: Pubkey) -> Self { pub fn new(node_id: Pubkey) -> Self {
let votes = VecDeque::new(); let votes = VecDeque::new();
Self { votes, node_id } Self { votes, node_id }
} }
pub fn deserialize(input: &[u8]) -> Result<VoteProgram, ProgramError> { pub fn deserialize(input: &[u8]) -> Result<Self, ProgramError> {
deserialize(input).map_err(|_| ProgramError::InvalidUserdata) deserialize(input).map_err(|_| ProgramError::InvalidUserdata)
} }
pub fn serialize(self: &VoteProgram, output: &mut [u8]) -> Result<(), ProgramError> { pub fn serialize(&self, output: &mut [u8]) -> Result<(), ProgramError> {
serialize_into(output, self).map_err(|err| match *err { serialize_into(output, self).map_err(|err| match *err {
ErrorKind::SizeLimit => ProgramError::UserdataTooSmall, ErrorKind::SizeLimit => ProgramError::UserdataTooSmall,
_ => ProgramError::GenericError, _ => ProgramError::GenericError,
@ -85,9 +85,9 @@ mod tests {
#[test] #[test]
fn test_serde() { fn test_serde() {
let mut buffer: Vec<u8> = vec![0; get_max_size()]; let mut buffer: Vec<u8> = vec![0; get_max_size()];
let mut vote_program = VoteProgram::default(); let mut vote_program = VoteState::default();
vote_program.votes = (0..MAX_VOTE_HISTORY).map(|_| Vote::default()).collect(); vote_program.votes = (0..MAX_VOTE_HISTORY).map(|_| Vote::default()).collect();
vote_program.serialize(&mut buffer).unwrap(); vote_program.serialize(&mut buffer).unwrap();
assert_eq!(VoteProgram::deserialize(&buffer).unwrap(), vote_program); assert_eq!(VoteState::deserialize(&buffer).unwrap(), vote_program);
} }
} }

View File

@ -13,15 +13,15 @@ pub struct VoteTransaction {}
impl VoteTransaction { impl VoteTransaction {
pub fn new_vote<T: KeypairUtil>( pub fn new_vote<T: KeypairUtil>(
vote_account: &T, voting_keypair: &T,
tick_height: u64, tick_height: u64,
last_id: Hash, last_id: Hash,
fee: u64, fee: u64,
) -> Transaction { ) -> Transaction {
let vote = Vote { tick_height }; let vote = Vote { tick_height };
let instruction = VoteInstruction::NewVote(vote); let instruction = VoteInstruction::Vote(vote);
Transaction::new( Transaction::new(
vote_account, voting_keypair,
&[], &[],
vote_program::id(), vote_program::id(),
&instruction, &instruction,
@ -31,28 +31,25 @@ impl VoteTransaction {
} }
pub fn new_account( pub fn new_account(
validator_id: &Keypair, from_keypair: &Keypair,
vote_account_id: Pubkey, vote_account_id: Pubkey,
last_id: Hash, last_id: Hash,
num_tokens: u64, num_tokens: u64,
fee: u64, fee: u64,
) -> Transaction { ) -> Transaction {
let create_tx = SystemInstruction::CreateAccount {
tokens: num_tokens,
space: vote_program::get_max_size() as u64,
program_id: vote_program::id(),
};
Transaction::new_with_instructions( Transaction::new_with_instructions(
&[validator_id], &[from_keypair],
&[vote_account_id], &[vote_account_id],
last_id, last_id,
fee, fee,
vec![system_program::id(), vote_program::id()], vec![system_program::id(), vote_program::id()],
vec![ vec![
Instruction::new( Instruction::new(0, &create_tx, vec![0, 1]),
0,
&SystemInstruction::CreateAccount {
tokens: num_tokens,
space: vote_program::get_max_size() as u64,
program_id: vote_program::id(),
},
vec![0, 1],
),
Instruction::new(1, &VoteInstruction::RegisterAccount, vec![0, 1]), Instruction::new(1, &VoteInstruction::RegisterAccount, vec![0, 1]),
], ],
) )
@ -63,7 +60,7 @@ impl VoteTransaction {
for i in 0..tx.instructions.len() { for i in 0..tx.instructions.len() {
let tx_program_id = tx.program_id(i); let tx_program_id = tx.program_id(i);
if vote_program::check_id(&tx_program_id) { if vote_program::check_id(&tx_program_id) {
if let Ok(Some(VoteInstruction::NewVote(vote))) = deserialize(&tx.userdata(i)) { if let Ok(Some(VoteInstruction::Vote(vote))) = deserialize(&tx.userdata(i)) {
votes.push((tx.account_keys[0], vote, tx.last_id)) votes.push((tx.account_keys[0], vote, tx.last_id))
} }
} }

View File

@ -8,7 +8,7 @@ use crate::service::Service;
use solana_metrics::{influxdb, submit}; use solana_metrics::{influxdb, submit};
use solana_sdk::pubkey::Pubkey; use solana_sdk::pubkey::Pubkey;
use solana_sdk::timing; use solana_sdk::timing;
use solana_sdk::vote_program::{self, VoteProgram}; use solana_sdk::vote_program::{self, VoteState};
use std::result; use std::result;
use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc; use std::sync::Arc;
@ -38,7 +38,7 @@ impl ComputeLeaderConfirmationService {
// Hold an accounts_db read lock as briefly as possible, just long enough to collect all // Hold an accounts_db read lock as briefly as possible, just long enough to collect all
// the vote states // the vote states
let vote_states: Vec<VoteProgram> = bank let vote_states: Vec<VoteState> = bank
.accounts .accounts
.accounts_db .accounts_db
.read() .read()
@ -47,7 +47,7 @@ impl ComputeLeaderConfirmationService {
.values() .values()
.filter_map(|account| { .filter_map(|account| {
if vote_program::check_id(&account.owner) { if vote_program::check_id(&account.owner) {
if let Ok(vote_state) = VoteProgram::deserialize(&account.userdata) { if let Ok(vote_state) = VoteState::deserialize(&account.userdata) {
if leader_id != vote_state.node_id { if leader_id != vote_state.node_id {
return Some(vote_state); return Some(vote_state);
} }

View File

@ -12,7 +12,7 @@ use solana_sdk::hash::{hash, Hash};
use solana_sdk::pubkey::Pubkey; use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::{Keypair, KeypairUtil}; use solana_sdk::signature::{Keypair, KeypairUtil};
use solana_sdk::system_transaction::SystemTransaction; use solana_sdk::system_transaction::SystemTransaction;
use solana_sdk::vote_program::{self, VoteProgram}; use solana_sdk::vote_program::{self, VoteState};
use solana_sdk::vote_transaction::VoteTransaction; use solana_sdk::vote_transaction::VoteTransaction;
use std::io::Cursor; use std::io::Cursor;
use std::sync::Arc; use std::sync::Arc;
@ -335,7 +335,7 @@ impl LeaderScheduler {
.values() .values()
.filter_map(|account| { .filter_map(|account| {
if vote_program::check_id(&account.owner) { if vote_program::check_id(&account.owner) {
if let Ok(vote_state) = VoteProgram::deserialize(&account.userdata) { if let Ok(vote_state) = VoteState::deserialize(&account.userdata) {
return vote_state return vote_state
.votes .votes
.back() .back()

View File

@ -473,7 +473,7 @@ mod tests {
use bincode::{deserialize, serialize}; use bincode::{deserialize, serialize};
use solana_sdk::signature::{Keypair, KeypairUtil}; use solana_sdk::signature::{Keypair, KeypairUtil};
use solana_sdk::system_instruction::SystemInstruction; use solana_sdk::system_instruction::SystemInstruction;
use solana_sdk::vote_program::VoteProgram; use solana_sdk::vote_program::VoteState;
use solana_sdk::vote_transaction::VoteTransaction; use solana_sdk::vote_transaction::VoteTransaction;
use std::fs::remove_dir_all; use std::fs::remove_dir_all;
@ -592,7 +592,7 @@ mod tests {
.expect("Expected valid response for account userdata") .expect("Expected valid response for account userdata")
.expect("Expected valid account userdata to exist after account creation"); .expect("Expected valid account userdata to exist after account creation");
let vote_state = VoteProgram::deserialize(&account_user_data); let vote_state = VoteState::deserialize(&account_user_data);
if vote_state.map(|vote_state| vote_state.node_id) == Ok(validator_keypair.pubkey()) { if vote_state.map(|vote_state| vote_state.node_id) == Ok(validator_keypair.pubkey()) {
break; break;