Move Vote program out of the SDK

This commit is contained in:
Greg Fitzgerald
2019-03-02 14:51:26 -07:00
committed by Michael Vines
parent b99e3eafdd
commit 1edf6c361e
31 changed files with 207 additions and 151 deletions

View File

@ -14,6 +14,7 @@ log = "0.4.2"
solana-logger = { path = "../../../logger", version = "0.12.0" }
solana-sdk = { path = "../../../sdk", version = "0.12.0" }
solana-rewards-api = { path = "../rewards_api", version = "0.12.0" }
solana-vote-api = { path = "../vote_api", version = "0.12.0" }
[dev-dependencies]
solana-runtime = { path = "../../../runtime", version = "0.12.0" }

View File

@ -8,7 +8,7 @@ use solana_sdk::account::KeyedAccount;
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::solana_entrypoint;
use solana_sdk::vote_program::{self, VoteState};
use solana_vote_api::vote_state::VoteState;
const INTEREST_PER_CREDIT_DIVISOR: u64 = 100; // Staker earns 1/INTEREST_PER_CREDIT_DIVISOR of interest per credit
const MINIMUM_CREDITS_PER_REDEMPTION: u64 = 1; // Raise this to either minimize congestion or lengthen the interest period
@ -35,7 +35,7 @@ fn redeem_vote_credits(keyed_accounts: &mut [KeyedAccount]) -> Result<(), Progra
Err(ProgramError::InvalidArgument)?;
}
if !vote_program::check_id(&keyed_accounts[0].account.owner) {
if !solana_vote_api::check_id(&keyed_accounts[0].account.owner) {
error!("account[0] is not assigned to the VOTE_PROGRAM");
Err(ProgramError::InvalidArgument)?;
}
@ -87,7 +87,8 @@ mod tests {
use solana_rewards_api::rewards_state::RewardsState;
use solana_sdk::account::Account;
use solana_sdk::signature::{Keypair, KeypairUtil};
use solana_sdk::vote_program::{self, Vote};
use solana_vote_api::vote_instruction::Vote;
use solana_vote_api::vote_state;
fn create_rewards_account(tokens: u64) -> Account {
let space = RewardsState::max_size();
@ -113,8 +114,8 @@ mod tests {
let mut staker_account = Account::new(100, 0, Pubkey::default());
let vote_id = Keypair::new().pubkey();
let mut vote_account = vote_program::create_vote_account(100);
vote_program::initialize_and_deserialize(
let mut vote_account = vote_state::create_vote_account(100);
vote_state::initialize_and_deserialize(
&staker_id,
&mut staker_account,
&vote_id,
@ -122,17 +123,17 @@ mod tests {
)
.unwrap();
for i in 0..vote_program::MAX_LOCKOUT_HISTORY {
for i in 0..vote_state::MAX_LOCKOUT_HISTORY {
let vote = Vote::new(i as u64);
let vote_state =
vote_program::vote_and_deserialize(&vote_id, &mut vote_account, vote.clone())
vote_state::vote_and_deserialize(&vote_id, &mut vote_account, vote.clone())
.unwrap();
assert_eq!(vote_state.credits(), 0);
}
let vote = Vote::new(vote_program::MAX_LOCKOUT_HISTORY as u64 + 1);
let vote = Vote::new(vote_state::MAX_LOCKOUT_HISTORY as u64 + 1);
let vote_state =
vote_program::vote_and_deserialize(&vote_id, &mut vote_account, vote.clone()).unwrap();
vote_state::vote_and_deserialize(&vote_id, &mut vote_account, vote.clone()).unwrap();
assert_eq!(vote_state.credits(), 1);
let rewards_id = Keypair::new().pubkey();

View File

@ -1,12 +1,11 @@
use solana_rewards_api;
use solana_rewards_api::rewards_transaction::RewardsTransaction;
use solana_runtime::bank::{Bank, Result};
use solana_sdk::genesis_block::GenesisBlock;
use solana_sdk::hash::hash;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::{Keypair, KeypairUtil};
use solana_sdk::vote_program::{self, VoteState};
use solana_sdk::vote_transaction::VoteTransaction;
use solana_vote_api::vote_state::{self, VoteState};
use solana_vote_api::vote_transaction::VoteTransaction;
struct RewardsBank<'a> {
bank: &'a Bank,
@ -81,12 +80,12 @@ fn test_redeem_vote_credits_via_bank() {
.unwrap();
// The validator submits votes to accumulate credits.
for i in 0..vote_program::MAX_LOCKOUT_HISTORY {
for i in 0..vote_state::MAX_LOCKOUT_HISTORY {
let vote_state = rewards_bank.submit_vote(&vote_keypair, i as u64).unwrap();
assert_eq!(vote_state.credits(), 0);
}
let vote_state = rewards_bank
.submit_vote(&vote_keypair, vote_program::MAX_LOCKOUT_HISTORY as u64 + 1)
.submit_vote(&vote_keypair, vote_state::MAX_LOCKOUT_HISTORY as u64 + 1)
.unwrap();
assert_eq!(vote_state.credits(), 1);

View File

@ -13,6 +13,7 @@ bincode = "1.1.2"
serde = "1.0.89"
serde_derive = "1.0.89"
solana-sdk = { path = "../../../sdk", version = "0.12.0" }
solana-vote-api = { path = "../vote_api", version = "0.12.0" }
[lib]
name = "solana_rewards_api"

View File

@ -10,7 +10,7 @@ use solana_sdk::signature::{Keypair, KeypairUtil};
use solana_sdk::system_transaction::SystemTransaction;
use solana_sdk::transaction::Transaction;
use solana_sdk::transaction_builder::TransactionBuilder;
use solana_sdk::vote_program::VoteInstruction;
use solana_vote_api::vote_instruction::VoteInstruction;
pub struct RewardsTransaction {}

View File

@ -14,6 +14,7 @@ log = "0.4.2"
solana-logger = { path = "../../../logger", version = "0.12.0" }
solana-metrics = { path = "../../../metrics", version = "0.12.0" }
solana-sdk = { path = "../../../sdk", version = "0.12.0" }
solana-vote-api = { path = "../vote_api", version = "0.12.0" }
[dev-dependencies]
solana-runtime = { path = "../../../runtime", version = "0.12.0" }

View File

@ -7,7 +7,8 @@ use solana_sdk::account::KeyedAccount;
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::solana_entrypoint;
use solana_sdk::vote_program::{self, VoteInstruction};
use solana_vote_api::vote_instruction::VoteInstruction;
use solana_vote_api::vote_state;
solana_entrypoint!(entrypoint);
fn entrypoint(
@ -22,9 +23,9 @@ fn entrypoint(
trace!("keyed_accounts: {:?}", keyed_accounts);
match deserialize(data).map_err(|_| ProgramError::InvalidUserdata)? {
VoteInstruction::InitializeAccount => vote_program::initialize_account(keyed_accounts),
VoteInstruction::InitializeAccount => vote_state::initialize_account(keyed_accounts),
VoteInstruction::DelegateStake(delegate_id) => {
vote_program::delegate_stake(keyed_accounts, delegate_id)
vote_state::delegate_stake(keyed_accounts, delegate_id)
}
VoteInstruction::Vote(vote) => {
debug!("{:?} by {}", vote, keyed_accounts[0].signer_key().unwrap());
@ -33,8 +34,8 @@ fn entrypoint(
.add_field("count", solana_metrics::influxdb::Value::Integer(1))
.to_owned(),
);
vote_program::process_vote(keyed_accounts, vote)
vote_state::process_vote(keyed_accounts, vote)
}
VoteInstruction::ClearCredits => vote_program::clear_credits(keyed_accounts),
VoteInstruction::ClearCredits => vote_state::clear_credits(keyed_accounts),
}
}

View File

@ -7,8 +7,9 @@ use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::{Keypair, KeypairUtil};
use solana_sdk::system_instruction::SystemInstruction;
use solana_sdk::transaction_builder::{BuilderInstruction, TransactionBuilder};
use solana_sdk::vote_program::{self, Vote, VoteInstruction, VoteState};
use solana_sdk::vote_transaction::VoteTransaction;
use solana_vote_api::vote_instruction::{Vote, VoteInstruction};
use solana_vote_api::vote_state::VoteState;
use solana_vote_api::vote_transaction::VoteTransaction;
struct VoteBank<'a> {
bank: &'a Bank,
@ -16,7 +17,7 @@ struct VoteBank<'a> {
impl<'a> VoteBank<'a> {
fn new(bank: &'a Bank) -> Self {
bank.add_native_program("solana_vote_program", &vote_program::id());
bank.add_native_program("solana_vote_program", &solana_vote_api::id());
Self { bank }
}
@ -74,7 +75,7 @@ fn test_vote_via_bank_with_no_signature() {
let mallory_id = mallory_keypair.pubkey();
let blockhash = bank.last_blockhash();
let vote_ix = BuilderInstruction::new(
vote_program::id(),
solana_vote_api::id(),
&VoteInstruction::Vote(Vote::new(0)),
vec![(vote_id, false)], // <--- attack!! No signature.
);

View File

@ -0,0 +1,20 @@
[package]
name = "solana-vote-api"
version = "0.12.0"
description = "Solana Vote program API"
authors = ["Solana Maintainers <maintainers@solana.com>"]
repository = "https://github.com/solana-labs/solana"
license = "Apache-2.0"
homepage = "https://solana.com/"
edition = "2018"
[dependencies]
bincode = "1.1.2"
log = "0.4.2"
serde = "1.0.89"
serde_derive = "1.0.89"
solana-sdk = { path = "../../../sdk", version = "0.12.0" }
[lib]
name = "solana_vote_api"
crate-type = ["lib"]

View File

@ -0,0 +1,18 @@
pub mod vote_instruction;
pub mod vote_state;
pub mod vote_transaction;
use solana_sdk::pubkey::Pubkey;
pub const VOTE_PROGRAM_ID: [u8; 32] = [
132, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0,
];
pub fn check_id(program_id: &Pubkey) -> bool {
program_id.as_ref() == VOTE_PROGRAM_ID
}
pub fn id() -> Pubkey {
Pubkey::new(&VOTE_PROGRAM_ID)
}

View File

@ -0,0 +1,54 @@
use crate::id;
use serde_derive::{Deserialize, Serialize};
use solana_sdk::pubkey::Pubkey;
use solana_sdk::transaction_builder::BuilderInstruction;
#[derive(Serialize, Default, Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct Vote {
// TODO: add signature of the state here as well
/// A vote for height slot_height
pub slot_height: u64,
}
impl Vote {
pub fn new(slot_height: u64) -> Self {
Self { slot_height }
}
}
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub enum VoteInstruction {
/// Initialize the VoteState for this `vote account`
/// * Transaction::keys[0] - the staker id that is also assumed to be the delegate by default
/// * Transaction::keys[1] - the new "vote account" to be associated with the delegate
InitializeAccount,
/// `Delegate` or `Assign` A staking account to a particular node
DelegateStake(Pubkey),
Vote(Vote),
/// Clear the credits in the vote account
/// * Transaction::keys[0] - the "vote account"
ClearCredits,
}
impl VoteInstruction {
pub fn new_clear_credits(vote_id: Pubkey) -> BuilderInstruction {
BuilderInstruction::new(id(), &VoteInstruction::ClearCredits, vec![(vote_id, true)])
}
pub fn new_delegate_stake(vote_id: Pubkey, delegate_id: Pubkey) -> BuilderInstruction {
BuilderInstruction::new(
id(),
&VoteInstruction::DelegateStake(delegate_id),
vec![(vote_id, true)],
)
}
pub fn new_initialize_account(vote_id: Pubkey, staker_id: Pubkey) -> BuilderInstruction {
BuilderInstruction::new(
id(),
&VoteInstruction::InitializeAccount,
vec![(staker_id, true), (vote_id, false)],
)
}
pub fn new_vote(vote_id: Pubkey, vote: Vote) -> BuilderInstruction {
BuilderInstruction::new(id(), &VoteInstruction::Vote(vote), vec![(vote_id, true)])
}
}

View File

@ -0,0 +1,462 @@
//! Vote stte
//! Receive and processes votes from validators
use crate::vote_instruction::Vote;
use crate::{check_id, id};
use bincode::{deserialize, serialize_into, serialized_size, ErrorKind};
use log::*;
use serde_derive::{Deserialize, Serialize};
use solana_sdk::account::{Account, KeyedAccount};
use solana_sdk::native_program::ProgramError;
use solana_sdk::pubkey::Pubkey;
use std::collections::VecDeque;
// Maximum number of votes to keep around
pub const MAX_LOCKOUT_HISTORY: usize = 31;
pub const INITIAL_LOCKOUT: usize = 2;
#[derive(Serialize, Default, Deserialize, Debug, PartialEq, Eq, Clone)]
pub struct Lockout {
pub slot_height: u64,
pub confirmation_count: u32,
}
impl Lockout {
pub fn new(vote: &Vote) -> Self {
Self {
slot_height: vote.slot_height,
confirmation_count: 1,
}
}
// The number of slots for which this vote is locked
pub fn lockout(&self) -> u64 {
(INITIAL_LOCKOUT as u64).pow(self.confirmation_count)
}
// The slot height at which this vote expires (cannot vote for any slot
// less than this)
pub fn expiration_slot_height(&self) -> u64 {
self.slot_height + self.lockout()
}
}
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub struct VoteState {
pub votes: VecDeque<Lockout>,
pub delegate_id: Pubkey,
pub root_slot: Option<u64>,
credits: u64,
}
impl VoteState {
pub fn new(delegate_id: Pubkey) -> Self {
let votes = VecDeque::new();
let credits = 0;
let root_slot = None;
Self {
votes,
delegate_id,
credits,
root_slot,
}
}
pub fn max_size() -> usize {
// Upper limit on the size of the Vote State. Equal to
// sizeof(VoteState) when votes.len() is MAX_LOCKOUT_HISTORY
let mut vote_state = Self::default();
vote_state.votes = VecDeque::from(vec![Lockout::default(); MAX_LOCKOUT_HISTORY]);
vote_state.root_slot = Some(std::u64::MAX);
serialized_size(&vote_state).unwrap() as usize
}
pub fn deserialize(input: &[u8]) -> Result<Self, ProgramError> {
deserialize(input).map_err(|_| ProgramError::InvalidUserdata)
}
pub fn serialize(&self, output: &mut [u8]) -> Result<(), ProgramError> {
serialize_into(output, self).map_err(|err| match *err {
ErrorKind::SizeLimit => ProgramError::UserdataTooSmall,
_ => ProgramError::GenericError,
})
}
pub fn process_vote(&mut self, vote: Vote) {
// Ignore votes for slots earlier than we already have votes for
if self
.votes
.back()
.map_or(false, |old_vote| old_vote.slot_height >= vote.slot_height)
{
return;
}
let vote = Lockout::new(&vote);
// TODO: Integrity checks
// Verify the vote's bank hash matches what is expected
self.pop_expired_votes(vote.slot_height);
// Once the stack is full, pop the oldest vote and distribute rewards
if self.votes.len() == MAX_LOCKOUT_HISTORY {
let vote = self.votes.pop_front().unwrap();
self.root_slot = Some(vote.slot_height);
self.credits += 1;
}
self.votes.push_back(vote);
self.double_lockouts();
}
/// Number of "credits" owed to this account from the mining pool. Submit this
/// VoteState to the Rewards program to trade credits for lamports.
pub fn credits(&self) -> u64 {
self.credits
}
/// Clear any credits.
pub fn clear_credits(&mut self) {
self.credits = 0;
}
fn pop_expired_votes(&mut self, slot_height: u64) {
loop {
if self
.votes
.back()
.map_or(false, |v| v.expiration_slot_height() < slot_height)
{
self.votes.pop_back();
} else {
break;
}
}
}
fn double_lockouts(&mut self) {
let stack_depth = self.votes.len();
for (i, v) in self.votes.iter_mut().enumerate() {
// Don't increase the lockout for this vote until we get more confirmations
// than the max number of confirmations this vote has seen
if stack_depth > i + v.confirmation_count as usize {
v.confirmation_count += 1;
} else {
break;
}
}
}
}
pub fn delegate_stake(
keyed_accounts: &mut [KeyedAccount],
node_id: Pubkey,
) -> Result<(), ProgramError> {
if !check_id(&keyed_accounts[0].account.owner) {
error!("account[0] is not assigned to the VOTE_PROGRAM");
Err(ProgramError::InvalidArgument)?;
}
if keyed_accounts[0].signer_key().is_none() {
error!("account[0] should sign the transaction");
Err(ProgramError::InvalidArgument)?;
}
let vote_state = VoteState::deserialize(&keyed_accounts[0].account.userdata);
if let Ok(mut vote_state) = vote_state {
vote_state.delegate_id = node_id;
vote_state.serialize(&mut keyed_accounts[0].account.userdata)?;
} else {
error!("account[0] does not valid userdata");
Err(ProgramError::InvalidUserdata)?;
}
Ok(())
}
/// Initialize the vote_state for a staking account
/// Assumes that the account is being init as part of a account creation or balance transfer and
/// that the transaction must be signed by the staker's keys
pub fn initialize_account(keyed_accounts: &mut [KeyedAccount]) -> Result<(), ProgramError> {
if !check_id(&keyed_accounts[1].account.owner) {
error!("account[1] is not assigned to the VOTE_PROGRAM");
Err(ProgramError::InvalidArgument)?;
}
if keyed_accounts[0].signer_key().is_none() {
error!("account[0] should sign the transaction");
Err(ProgramError::InvalidArgument)?;
}
let staker_id = keyed_accounts[0].signer_key().unwrap();
let vote_state = VoteState::deserialize(&keyed_accounts[1].account.userdata);
if let Ok(vote_state) = vote_state {
if vote_state.delegate_id == Pubkey::default() {
let vote_state = VoteState::new(*staker_id);
vote_state.serialize(&mut keyed_accounts[1].account.userdata)?;
} else {
error!("account[1] userdata already initialized");
Err(ProgramError::InvalidUserdata)?;
}
} else {
error!("account[1] does not have valid userdata");
Err(ProgramError::InvalidUserdata)?;
}
Ok(())
}
pub fn process_vote(keyed_accounts: &mut [KeyedAccount], vote: Vote) -> Result<(), ProgramError> {
if !check_id(&keyed_accounts[0].account.owner) {
error!("account[0] is not assigned to the VOTE_PROGRAM");
Err(ProgramError::InvalidArgument)?;
}
if keyed_accounts[0].signer_key().is_none() {
error!("account[0] should sign the transaction");
Err(ProgramError::InvalidArgument)?;
}
let mut vote_state = VoteState::deserialize(&keyed_accounts[0].account.userdata)?;
vote_state.process_vote(vote);
vote_state.serialize(&mut keyed_accounts[0].account.userdata)?;
Ok(())
}
pub fn clear_credits(keyed_accounts: &mut [KeyedAccount]) -> Result<(), ProgramError> {
if !check_id(&keyed_accounts[0].account.owner) {
error!("account[0] is not assigned to the VOTE_PROGRAM");
Err(ProgramError::InvalidArgument)?;
}
let mut vote_state = VoteState::deserialize(&keyed_accounts[0].account.userdata)?;
vote_state.clear_credits();
vote_state.serialize(&mut keyed_accounts[0].account.userdata)?;
Ok(())
}
pub fn create_vote_account(tokens: u64) -> Account {
let space = VoteState::max_size();
Account::new(tokens, space, id())
}
pub fn initialize_and_deserialize(
from_id: &Pubkey,
from_account: &mut Account,
vote_id: &Pubkey,
vote_account: &mut Account,
) -> Result<VoteState, ProgramError> {
let mut keyed_accounts = [
KeyedAccount::new(from_id, true, from_account),
KeyedAccount::new(vote_id, false, vote_account),
];
initialize_account(&mut keyed_accounts)?;
let vote_state = VoteState::deserialize(&vote_account.userdata).unwrap();
Ok(vote_state)
}
pub fn vote_and_deserialize(
vote_id: &Pubkey,
vote_account: &mut Account,
vote: Vote,
) -> Result<VoteState, ProgramError> {
let mut keyed_accounts = [KeyedAccount::new(vote_id, true, vote_account)];
process_vote(&mut keyed_accounts, vote)?;
let vote_state = VoteState::deserialize(&vote_account.userdata).unwrap();
Ok(vote_state)
}
#[cfg(test)]
mod tests {
use super::*;
use solana_sdk::signature::{Keypair, KeypairUtil};
#[test]
fn test_initialize_staking_account() {
let staker_id = Keypair::new().pubkey();
let mut staker_account = Account::new(100, 0, Pubkey::default());
let mut bogus_staker_account = Account::new(100, 0, Pubkey::default());
let staking_account_id = Keypair::new().pubkey();
let mut staking_account = create_vote_account(100);
let bogus_account_id = Keypair::new().pubkey();
let mut bogus_account = Account::new(100, 0, id());
let mut keyed_accounts = [
KeyedAccount::new(&staker_id, false, &mut bogus_staker_account),
KeyedAccount::new(&bogus_account_id, false, &mut bogus_account),
];
//staker is not signer
let res = initialize_account(&mut keyed_accounts);
assert_eq!(res, Err(ProgramError::InvalidArgument));
//space was never initialized, deserialize will fail
keyed_accounts[0] = KeyedAccount::new(&staker_id, true, &mut staker_account);
let res = initialize_account(&mut keyed_accounts);
assert_eq!(res, Err(ProgramError::InvalidUserdata));
//init should pass
keyed_accounts[1] = KeyedAccount::new(&staking_account_id, false, &mut staking_account);
let res = initialize_account(&mut keyed_accounts);
assert_eq!(res, Ok(()));
// reinit should fail
let res = initialize_account(&mut keyed_accounts);
assert_eq!(res, Err(ProgramError::InvalidUserdata));
}
#[test]
fn test_vote_serialize() {
let mut buffer: Vec<u8> = vec![0; VoteState::max_size()];
let mut vote_state = VoteState::default();
vote_state
.votes
.resize(MAX_LOCKOUT_HISTORY, Lockout::default());
vote_state.serialize(&mut buffer).unwrap();
assert_eq!(VoteState::deserialize(&buffer).unwrap(), vote_state);
}
#[test]
fn test_voter_registration() {
let from_id = Keypair::new().pubkey();
let mut from_account = Account::new(100, 0, Pubkey::default());
let vote_id = Keypair::new().pubkey();
let mut vote_account = create_vote_account(100);
let vote_state =
initialize_and_deserialize(&from_id, &mut from_account, &vote_id, &mut vote_account)
.unwrap();
assert_eq!(vote_state.delegate_id, from_id);
assert!(vote_state.votes.is_empty());
}
#[test]
fn test_vote() {
let from_id = Keypair::new().pubkey();
let mut from_account = Account::new(100, 0, Pubkey::default());
let vote_id = Keypair::new().pubkey();
let mut vote_account = create_vote_account(100);
initialize_and_deserialize(&from_id, &mut from_account, &vote_id, &mut vote_account)
.unwrap();
let vote = Vote::new(1);
let vote_state = vote_and_deserialize(&vote_id, &mut vote_account, vote.clone()).unwrap();
assert_eq!(vote_state.votes, vec![Lockout::new(&vote)]);
assert_eq!(vote_state.credits(), 0);
}
#[test]
fn test_vote_signature() {
let from_id = Keypair::new().pubkey();
let mut from_account = Account::new(100, 0, Pubkey::default());
let vote_id = Keypair::new().pubkey();
let mut vote_account = create_vote_account(100);
initialize_and_deserialize(&from_id, &mut from_account, &vote_id, &mut vote_account)
.unwrap();
let vote = Vote::new(1);
let mut keyed_accounts = [KeyedAccount::new(&vote_id, false, &mut vote_account)];
let res = process_vote(&mut keyed_accounts, vote);
assert_eq!(res, Err(ProgramError::InvalidArgument));
}
#[test]
fn test_vote_without_initialization() {
let vote_id = Keypair::new().pubkey();
let mut vote_account = create_vote_account(100);
let vote = Vote::new(1);
let vote_state = vote_and_deserialize(&vote_id, &mut vote_account, vote.clone()).unwrap();
assert_eq!(vote_state.delegate_id, Pubkey::default());
assert_eq!(vote_state.votes, vec![Lockout::new(&vote)]);
}
#[test]
fn test_vote_lockout() {
let voter_id = Keypair::new().pubkey();
let mut vote_state = VoteState::new(voter_id);
for i in 0..(MAX_LOCKOUT_HISTORY + 1) {
vote_state.process_vote(Vote::new((INITIAL_LOCKOUT as usize * i) as u64));
}
// The last vote should have been popped b/c it reached a depth of MAX_LOCKOUT_HISTORY
assert_eq!(vote_state.votes.len(), MAX_LOCKOUT_HISTORY);
assert_eq!(vote_state.root_slot, Some(0));
check_lockouts(&vote_state);
// One more vote that confirms the entire stack,
// the root_slot should change to the
// second vote
let top_vote = vote_state.votes.front().unwrap().slot_height;
vote_state.process_vote(Vote::new(
vote_state.votes.back().unwrap().expiration_slot_height(),
));
assert_eq!(Some(top_vote), vote_state.root_slot);
// Expire everything except the first vote
let vote = Vote::new(vote_state.votes.front().unwrap().expiration_slot_height());
vote_state.process_vote(vote);
// First vote and new vote are both stored for a total of 2 votes
assert_eq!(vote_state.votes.len(), 2);
}
#[test]
fn test_vote_double_lockout_after_expiration() {
let voter_id = Keypair::new().pubkey();
let mut vote_state = VoteState::new(voter_id);
for i in 0..3 {
let vote = Vote::new(i as u64);
vote_state.process_vote(vote);
}
// Check the lockouts for first and second votes. Lockouts should be
// INITIAL_LOCKOUT^3 and INITIAL_LOCKOUT^2 respectively
check_lockouts(&vote_state);
// Expire the third vote (which was a vote for slot 2). The height of the
// vote stack is unchanged, so none of the previous votes should have
// doubled in lockout
vote_state.process_vote(Vote::new((2 + INITIAL_LOCKOUT + 1) as u64));
check_lockouts(&vote_state);
// Vote again, this time the vote stack depth increases, so the lockouts should
// double for everybody
vote_state.process_vote(Vote::new((2 + INITIAL_LOCKOUT + 2) as u64));
check_lockouts(&vote_state);
}
#[test]
fn test_vote_credits() {
let voter_id = Keypair::new().pubkey();
let mut vote_state = VoteState::new(voter_id);
for i in 0..MAX_LOCKOUT_HISTORY {
vote_state.process_vote(Vote::new(i as u64));
}
assert_eq!(vote_state.credits, 0);
vote_state.process_vote(Vote::new(MAX_LOCKOUT_HISTORY as u64 + 1));
assert_eq!(vote_state.credits, 1);
vote_state.process_vote(Vote::new(MAX_LOCKOUT_HISTORY as u64 + 2));
assert_eq!(vote_state.credits(), 2);
vote_state.process_vote(Vote::new(MAX_LOCKOUT_HISTORY as u64 + 3));
assert_eq!(vote_state.credits(), 3);
vote_state.clear_credits();
assert_eq!(vote_state.credits(), 0);
}
fn check_lockouts(vote_state: &VoteState) {
for (i, vote) in vote_state.votes.iter().enumerate() {
let num_lockouts = vote_state.votes.len() - i;
assert_eq!(
vote.lockout(),
INITIAL_LOCKOUT.pow(num_lockouts as u32) as u64
);
}
}
}

View File

@ -0,0 +1,105 @@
//! The `vote_transaction` module provides functionality for creating vote transactions.
use crate::vote_instruction::{Vote, VoteInstruction};
use crate::vote_state::VoteState;
use crate::{check_id, id};
use bincode::deserialize;
use solana_sdk::hash::Hash;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::{Keypair, KeypairUtil};
use solana_sdk::system_instruction::SystemInstruction;
use solana_sdk::system_program;
use solana_sdk::transaction::{Instruction, Transaction};
use solana_sdk::transaction_builder::TransactionBuilder;
pub struct VoteTransaction {}
impl VoteTransaction {
pub fn new_vote<T: KeypairUtil>(
voting_keypair: &T,
slot_height: u64,
recent_blockhash: Hash,
fee: u64,
) -> Transaction {
let vote = Vote { slot_height };
TransactionBuilder::new(fee)
.push(VoteInstruction::new_vote(voting_keypair.pubkey(), vote))
.sign(&[voting_keypair], recent_blockhash)
}
/// Fund or create the staking account with tokens
pub fn fund_staking_account(
from_keypair: &Keypair,
vote_account_id: Pubkey,
recent_blockhash: Hash,
num_tokens: u64,
fee: u64,
) -> Transaction {
let create_tx = SystemInstruction::CreateAccount {
tokens: num_tokens,
space: VoteState::max_size() as u64,
program_id: id(),
};
Transaction::new_with_instructions(
&[from_keypair],
&[vote_account_id],
recent_blockhash,
fee,
vec![system_program::id(), id()],
vec![
Instruction::new(0, &create_tx, vec![0, 1]),
Instruction::new(1, &VoteInstruction::InitializeAccount, vec![0, 1]),
],
)
}
/// Choose a node id to `delegate` or `assign` this vote account to
pub fn delegate_vote_account<T: KeypairUtil>(
vote_keypair: &T,
recent_blockhash: Hash,
node_id: Pubkey,
fee: u64,
) -> Transaction {
TransactionBuilder::new(fee)
.push(VoteInstruction::new_delegate_stake(
vote_keypair.pubkey(),
node_id,
))
.sign(&[vote_keypair], recent_blockhash)
}
fn get_vote(tx: &Transaction, ix_index: usize) -> Option<(Pubkey, Vote, Hash)> {
if !check_id(&tx.program_id(ix_index)) {
return None;
}
let instruction = deserialize(&tx.userdata(ix_index)).unwrap();
if let VoteInstruction::Vote(vote) = instruction {
Some((tx.account_keys[0], vote, tx.recent_blockhash))
} else {
None
}
}
pub fn get_votes(tx: &Transaction) -> Vec<(Pubkey, Vote, Hash)> {
(0..tx.instructions.len())
.filter_map(|i| Self::get_vote(tx, i))
.collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_votes() {
let keypair = Keypair::new();
let slot_height = 1;
let recent_blockhash = Hash::default();
let transaction = VoteTransaction::new_vote(&keypair, slot_height, recent_blockhash, 0);
assert_eq!(
VoteTransaction::get_votes(&transaction),
vec![(keypair.pubkey(), Vote::new(slot_height), recent_blockhash)]
);
}
}