_id => _pubkey variable renaming (#4419)

* wallet: rename *_account_id to *_account_pubkey

* s/from_id/from_pubkey/g

* s/node_id/node_pubkey/g

* s/stake_id/stake_pubkey/g

* s/voter_id/voter_pubkey/g

* s/vote_id/vote_pubkey/g

* s/delegate_id/delegate_pubkey/g

* s/account_id/account_pubkey/g

* s/to_id/to_pubkey/g

* s/my_id/my_pubkey/g

* cargo fmt

* s/staker_id/staker_pubkey/g

* s/mining_pool_id/mining_pool_pubkey/g

* s/leader_id/leader_pubkey/g

* cargo fmt

* s/funding_id/funding_pubkey/g
This commit is contained in:
Michael Vines 2019-05-23 23:20:04 -07:00 committed by GitHub
parent 94beb4b8c2
commit cfe5afd34c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
42 changed files with 697 additions and 620 deletions

View File

@ -715,11 +715,11 @@ pub fn create_token_accounts(client: &Client, signers: &[Arc<Keypair>], accounts
let mut to_create_txs: Vec<_> = chunk let mut to_create_txs: Vec<_> = chunk
.par_iter() .par_iter()
.map(|(signer, new)| { .map(|(signer, new)| {
let owner_id = &signer.pubkey(); let owner_pubkey = &signer.pubkey();
let space = mem::size_of::<ExchangeState>() as u64; let space = mem::size_of::<ExchangeState>() as u64;
let create_ix = let create_ix =
system_instruction::create_account(owner_id, new, 1, space, &id()); system_instruction::create_account(owner_pubkey, new, 1, space, &id());
let request_ix = exchange_instruction::account_request(owner_id, new); let request_ix = exchange_instruction::account_request(owner_pubkey, new);
( (
signer, signer,
Transaction::new_unsigned_instructions(vec![create_ix, request_ix]), Transaction::new_unsigned_instructions(vec![create_ix, request_ix]),

View File

@ -588,12 +588,12 @@ pub fn generate_keypairs(seed_keypair: &Keypair, count: usize) -> Vec<Keypair> {
pub fn generate_and_fund_keypairs<T: Client>( pub fn generate_and_fund_keypairs<T: Client>(
client: &T, client: &T,
drone_addr: Option<SocketAddr>, drone_addr: Option<SocketAddr>,
funding_id: &Keypair, funding_pubkey: &Keypair,
tx_count: usize, tx_count: usize,
lamports_per_account: u64, lamports_per_account: u64,
) -> (Vec<Keypair>, u64) { ) -> (Vec<Keypair>, u64) {
info!("Creating {} keypairs...", tx_count * 2); info!("Creating {} keypairs...", tx_count * 2);
let mut keypairs = generate_keypairs(funding_id, tx_count * 2); let mut keypairs = generate_keypairs(funding_pubkey, tx_count * 2);
info!("Get lamports..."); info!("Get lamports...");
@ -606,11 +606,11 @@ pub fn generate_and_fund_keypairs<T: Client>(
if lamports_per_account > last_keypair_balance { if lamports_per_account > last_keypair_balance {
let extra = lamports_per_account - last_keypair_balance; let extra = lamports_per_account - last_keypair_balance;
let total = extra * (keypairs.len() as u64); let total = extra * (keypairs.len() as u64);
if client.get_balance(&funding_id.pubkey()).unwrap_or(0) < total { if client.get_balance(&funding_pubkey.pubkey()).unwrap_or(0) < total {
airdrop_lamports(client, &drone_addr.unwrap(), funding_id, total); airdrop_lamports(client, &drone_addr.unwrap(), funding_pubkey, total);
} }
info!("adding more lamports {}", extra); info!("adding more lamports {}", extra);
fund_keys(client, funding_id, &keypairs, extra); fund_keys(client, funding_pubkey, &keypairs, extra);
} }
// 'generate_keypairs' generates extra keys to be able to have size-aligned funding batches for fund_keys. // 'generate_keypairs' generates extra keys to be able to have size-aligned funding batches for fund_keys.

View File

@ -290,8 +290,8 @@ An array consisting of vote accounts:
Each VoteState will be a JSON object with the following sub fields: Each VoteState will be a JSON object with the following sub fields:
* `votes`, array of most recent vote lockouts * `votes`, array of most recent vote lockouts
* `node_id`, the pubkey of the node that votes using this account * `node_pubkey`, the pubkey of the node that votes using this account
* `authorized_voter_id`, the pubkey of the authorized vote signer for this account * `authorized_voter_pubkey`, the pubkey of the authorized vote signer for this account
* `commission`, a 32-bit integer used as a fraction (commission/MAX_U32) for rewards payout * `commission`, a 32-bit integer used as a fraction (commission/MAX_U32) for rewards payout
* `root_slot`, the most recent slot this account has achieved maximum lockout * `root_slot`, the most recent slot this account has achieved maximum lockout
* `credits`, credits accrued by this account for reaching lockouts * `credits`, credits accrued by this account for reaching lockouts
@ -302,7 +302,7 @@ Each VoteState will be a JSON object with the following sub fields:
curl -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1, "method":"getEpochVoteAccounts"}' http://localhost:8899 curl -X POST -H "Content-Type: application/json" -d '{"jsonrpc":"2.0","id":1, "method":"getEpochVoteAccounts"}' http://localhost:8899
// Result // Result
{"jsonrpc":"2.0","result":[[[84,115,89,23,41,83,221,72,58,23,53,245,195,188,140,161,242,189,200,164,139,214,12,180,84,161,28,151,24,243,159,125],10000000,{"authorized_voter_id":[84,115,89,23,41,83,221,72,58,23,53,245,195,188,140,161,242,189,200,164,139,214,12,180,84,161,28,151,24,243,159,125],"commission":0,"credits":0,"node_id":[49,139,227,211,47,39,69,86,131,244,160,144,228,169,84,143,142,253,83,81,212,110,254,12,242,71,219,135,30,60,157,213],"root_slot":null,"votes":[{"confirmation_count":1,"slot":0}]}]],"id":1} {"jsonrpc":"2.0","result":[[[84,115,89,23,41,83,221,72,58,23,53,245,195,188,140,161,242,189,200,164,139,214,12,180,84,161,28,151,24,243,159,125],10000000,{"authorized_voter_pubkey":[84,115,89,23,41,83,221,72,58,23,53,245,195,188,140,161,242,189,200,164,139,214,12,180,84,161,28,151,24,243,159,125],"commission":0,"credits":0,"node_pubkey":[49,139,227,211,47,39,69,86,131,244,160,144,228,169,84,143,142,253,83,81,212,110,254,12,242,71,219,135,30,60,157,213],"root_slot":null,"votes":[{"confirmation_count":1,"slot":0}]}]],"id":1}
``` ```
--- ---

View File

@ -85,7 +85,7 @@ contains the following state information:
* Account::lamports - The staked lamports. * Account::lamports - The staked lamports.
* `voter_id` - The pubkey of the VoteState instance the lamports are * `voter_pubkey` - The pubkey of the VoteState instance the lamports are
delegated to. delegated to.
* `credits_observed` - The total credits claimed over the lifetime of the * `credits_observed` - The total credits claimed over the lifetime of the
@ -109,7 +109,7 @@ program.
* `account[0]` - RW - The StakeState::Delegate instance. * `account[0]` - RW - The StakeState::Delegate instance.
`StakeState::Delegate::credits_observed` is initialized to `VoteState::credits`. `StakeState::Delegate::credits_observed` is initialized to `VoteState::credits`.
`StakeState::Delegate::voter_id` is initialized to `account[1]` `StakeState::Delegate::voter_pubkey` is initialized to `account[1]`
* `account[1]` - R - The VoteState instance. * `account[1]` - R - The VoteState instance.
@ -127,7 +127,7 @@ reward.
* `account[1]` - RW - The StakeState::Delegate instance that is redeeming votes * `account[1]` - RW - The StakeState::Delegate instance that is redeeming votes
credits. credits.
* `account[2]` - R - The VoteState instance, must be the same as * `account[2]` - R - The VoteState instance, must be the same as
`StakeState::voter_id` `StakeState::voter_pubkey`
Reward is payed out for the difference between `VoteState::credits` to Reward is payed out for the difference between `VoteState::credits` to
`StakeState::Delgate.credits_observed`, and `credits_observed` is updated to `StakeState::Delgate.credits_observed`, and `credits_observed` is updated to
@ -181,7 +181,7 @@ the VoteState program or submitting votes to the program.
The total stake allocated to a VoteState program can be calculated by the sum of The total stake allocated to a VoteState program can be calculated by the sum of
all the StakeState programs that have the VoteState pubkey as the all the StakeState programs that have the VoteState pubkey as the
`StakeState::Delegate::voter_id`. `StakeState::Delegate::voter_pubkey`.
## Example Callflow ## Example Callflow
@ -194,12 +194,12 @@ nodes since stake is used as weight in the network control and data planes. One
way to implement this would be for the StakeState to delegate to a pool of way to implement this would be for the StakeState to delegate to a pool of
validators instead of a single one. validators instead of a single one.
Instead of a single `vote_id` and `credits_observed` entry in the StakeState Instead of a single `vote_pubkey` and `credits_observed` entry in the StakeState
program, the program can be initialized with a vector of tuples. program, the program can be initialized with a vector of tuples.
```rust,ignore ```rust,ignore
Voter { Voter {
voter_id: Pubkey, voter_pubkey: Pubkey,
credits_observed: u64, credits_observed: u64,
weight: u8, weight: u8,
} }

View File

@ -46,6 +46,6 @@ The different protocol strategies to address the above challenges:
* Current root * Current root
* The set of all completed slots in the confirmed epochs (an epoch that was calculated based on a bank <= current root) past the current root * The set of all completed slots in the confirmed epochs (an epoch that was calculated based on a bank <= current root) past the current root
Observers of this gossip message with higher epochs (repairmen) send blobs to catch the lagging node up with the rest of the cluster. The repairmen are responsible for sending the slots within the epochs that are confrimed by the advertised `root` in gossip. The repairmen divide the responsibility of sending each of the missing slots in these epochs based on a random seed (simple blob.index iteration by N, seeded with the repairman's node_id). Ideally, each repairman in an N node cluster (N nodes whose epochs are higher than that of the repairee) sends 1/N of the missing blobs. Both data and coding blobs for missing slots are sent. Repairmen do not send blobs again to the same validator until they see the message in gossip updated, at which point they perform another iteration of this protocol. Observers of this gossip message with higher epochs (repairmen) send blobs to catch the lagging node up with the rest of the cluster. The repairmen are responsible for sending the slots within the epochs that are confrimed by the advertised `root` in gossip. The repairmen divide the responsibility of sending each of the missing slots in these epochs based on a random seed (simple blob.index iteration by N, seeded with the repairman's node_pubkey). Ideally, each repairman in an N node cluster (N nodes whose epochs are higher than that of the repairee) sends 1/N of the missing blobs. Both data and coding blobs for missing slots are sent. Repairmen do not send blobs again to the same validator until they see the message in gossip updated, at which point they perform another iteration of this protocol.
Gossip messages are updated every time a validator receives a complete slot within the epoch. Completed slots are detected by blocktree and sent over a channel to RepairService. It is important to note that we know that by the time a slot X is complete, the epoch schedule must exist for the epoch that contains slot X because WindowService will reject blobs for unconfirmed epochs. When a newly completed slot is detected, we also update the current root if it has changed since the last update. The root is made available to RepairService through Blocktree, which holds the latest root. Gossip messages are updated every time a validator receives a complete slot within the epoch. Completed slots are detected by blocktree and sent over a channel to RepairService. It is important to note that we know that by the time a slot X is complete, the epoch schedule must exist for the epoch that contains slot X because WindowService will reject blobs for unconfirmed epochs. When a newly completed slot is detected, we also update the current root if it has changed since the last update. The root is made available to RepairService through Blocktree, which holds the latest root.

View File

@ -22,11 +22,11 @@ The Vote account contains the following state information:
* votes - The submitted votes. * votes - The submitted votes.
* `delegate_id` - An identity that may operate with the weight of this * `delegate_pubkey` - An identity that may operate with the weight of this
account's stake. It is typically the identity of a fullnode, but may be any account's stake. It is typically the identity of a fullnode, but may be any
identity involved in stake-weighted computations. identity involved in stake-weighted computations.
* `authorized_voter_id` - Only this identity is authorized to submit votes. * `authorized_voter_pubkey` - Only this identity is authorized to submit votes.
* `credits` - The amount of unclaimed rewards. * `credits` - The amount of unclaimed rewards.

View File

@ -306,10 +306,10 @@ while [[ $iteration -le $iterations ]]; do
( (
source multinode-demo/common.sh source multinode-demo/common.sh
set -x set -x
client_id=/tmp/client-id.json-$$ client_keypair=/tmp/client-id.json-$$
$solana_keygen -o $client_id || exit $? $solana_keygen -o $client_keypair || exit $?
$solana_gossip spy --num-nodes-exactly $numNodes || exit $? $solana_gossip spy --num-nodes-exactly $numNodes || exit $?
rm -rf $client_id rm -rf $client_keypair
) || flag_error ) || flag_error
echo "--- RPC API: bootstrap-leader getTransactionCount ($iteration)" echo "--- RPC API: bootstrap-leader getTransactionCount ($iteration)"

View File

@ -54,7 +54,7 @@ fn bench_consume_buffered(bencher: &mut Bencher) {
let GenesisBlockInfo { genesis_block, .. } = create_genesis_block(100_000); let GenesisBlockInfo { genesis_block, .. } = create_genesis_block(100_000);
let bank = Arc::new(Bank::new(&genesis_block)); let bank = Arc::new(Bank::new(&genesis_block));
let ledger_path = get_tmp_ledger_path!(); let ledger_path = get_tmp_ledger_path!();
let my_id = Pubkey::new_rand(); let my_pubkey = Pubkey::new_rand();
{ {
let blocktree = Arc::new( let blocktree = Arc::new(
Blocktree::open(&ledger_path).expect("Expected to be able to open database ledger"), Blocktree::open(&ledger_path).expect("Expected to be able to open database ledger"),
@ -74,8 +74,11 @@ fn bench_consume_buffered(bencher: &mut Bencher) {
// This tests the performance of buffering packets. // This tests the performance of buffering packets.
// If the packet buffers are copied, performance will be poor. // If the packet buffers are copied, performance will be poor.
bencher.iter(move || { bencher.iter(move || {
let _ignored = let _ignored = BankingStage::consume_buffered_packets(
BankingStage::consume_buffered_packets(&my_id, &poh_recorder, packets.as_slice()); &my_pubkey,
&poh_recorder,
packets.as_slice(),
);
}); });
exit.store(true, Ordering::Relaxed); exit.store(true, Ordering::Relaxed);

View File

@ -144,7 +144,7 @@ impl BankingStage {
} }
pub fn consume_buffered_packets( pub fn consume_buffered_packets(
my_id: &Pubkey, my_pubkey: &Pubkey,
poh_recorder: &Arc<Mutex<PohRecorder>>, poh_recorder: &Arc<Mutex<PohRecorder>>,
buffered_packets: &[PacketsAndOffsets], buffered_packets: &[PacketsAndOffsets],
) -> Result<UnprocessedPackets> { ) -> Result<UnprocessedPackets> {
@ -194,7 +194,7 @@ impl BankingStage {
&bank, &bank,
&msgs, &msgs,
&unprocessed_indexes, &unprocessed_indexes,
my_id, my_pubkey,
next_leader, next_leader,
); );
Self::push_unprocessed( Self::push_unprocessed(
@ -226,12 +226,12 @@ impl BankingStage {
} }
fn consume_or_forward_packets( fn consume_or_forward_packets(
leader_id: Option<Pubkey>, leader_pubkey: Option<Pubkey>,
bank_is_available: bool, bank_is_available: bool,
would_be_leader: bool, would_be_leader: bool,
my_id: &Pubkey, my_pubkey: &Pubkey,
) -> BufferedPacketsDecision { ) -> BufferedPacketsDecision {
leader_id.map_or( leader_pubkey.map_or(
// If leader is not known, return the buffered packets as is // If leader is not known, return the buffered packets as is
BufferedPacketsDecision::Hold, BufferedPacketsDecision::Hold,
// else process the packets // else process the packets
@ -242,7 +242,7 @@ impl BankingStage {
} else if would_be_leader { } else if would_be_leader {
// If the node will be the leader soon, hold the packets for now // If the node will be the leader soon, hold the packets for now
BufferedPacketsDecision::Hold BufferedPacketsDecision::Hold
} else if x != *my_id { } else if x != *my_pubkey {
// If the current node is not the leader, forward the buffered packets // If the current node is not the leader, forward the buffered packets
BufferedPacketsDecision::Forward BufferedPacketsDecision::Forward
} else { } else {
@ -282,8 +282,8 @@ impl BankingStage {
} }
BufferedPacketsDecision::Forward => { BufferedPacketsDecision::Forward => {
if enable_forwarding { if enable_forwarding {
next_leader.map_or(Ok(buffered_packets.to_vec()), |leader_id| { next_leader.map_or(Ok(buffered_packets.to_vec()), |leader_pubkey| {
rcluster_info.lookup(&leader_id).map_or( rcluster_info.lookup(&leader_pubkey).map_or(
Ok(buffered_packets.to_vec()), Ok(buffered_packets.to_vec()),
|leader| { |leader| {
let _ = Self::forward_buffered_packets( let _ = Self::forward_buffered_packets(
@ -665,14 +665,14 @@ impl BankingStage {
bank: &Arc<Bank>, bank: &Arc<Bank>,
msgs: &Packets, msgs: &Packets,
transaction_indexes: &[usize], transaction_indexes: &[usize],
my_id: &Pubkey, my_pubkey: &Pubkey,
next_leader: Option<Pubkey>, next_leader: Option<Pubkey>,
) -> Vec<usize> { ) -> Vec<usize> {
// Check if we are the next leader. If so, let's not filter the packets // Check if we are the next leader. If so, let's not filter the packets
// as we'll filter it again while processing the packets. // as we'll filter it again while processing the packets.
// Filtering helps if we were going to forward the packets to some other node // Filtering helps if we were going to forward the packets to some other node
if let Some(leader) = next_leader { if let Some(leader) = next_leader {
if leader == *my_id { if leader == *my_pubkey {
return transaction_indexes.to_vec(); return transaction_indexes.to_vec();
} }
} }
@ -753,7 +753,7 @@ impl BankingStage {
if processed < verified_txs_len { if processed < verified_txs_len {
let next_leader = poh.lock().unwrap().next_slot_leader(); let next_leader = poh.lock().unwrap().next_slot_leader();
let my_id = cluster_info.read().unwrap().id(); let my_pubkey = cluster_info.read().unwrap().id();
// Walk thru rest of the transactions and filter out the invalid (e.g. too old) ones // Walk thru rest of the transactions and filter out the invalid (e.g. too old) ones
while let Some((msgs, vers)) = mms_iter.next() { while let Some((msgs, vers)) = mms_iter.next() {
let packet_indexes = Self::generate_packet_indexes(vers); let packet_indexes = Self::generate_packet_indexes(vers);
@ -761,7 +761,7 @@ impl BankingStage {
&bank, &bank,
&msgs, &msgs,
&packet_indexes, &packet_indexes,
&my_id, &my_pubkey,
next_leader, next_leader,
); );
Self::push_unprocessed(&mut unprocessed_packets, msgs, unprocessed_indexes); Self::push_unprocessed(&mut unprocessed_packets, msgs, unprocessed_indexes);
@ -1391,40 +1391,65 @@ mod tests {
#[test] #[test]
fn test_should_process_or_forward_packets() { fn test_should_process_or_forward_packets() {
let my_id = Pubkey::new_rand(); let my_pubkey = Pubkey::new_rand();
let my_id1 = Pubkey::new_rand(); let my_pubkey1 = Pubkey::new_rand();
assert_eq!( assert_eq!(
BankingStage::consume_or_forward_packets(None, true, false, &my_id), BankingStage::consume_or_forward_packets(None, true, false, &my_pubkey),
BufferedPacketsDecision::Hold BufferedPacketsDecision::Hold
); );
assert_eq!( assert_eq!(
BankingStage::consume_or_forward_packets(None, false, false, &my_id), BankingStage::consume_or_forward_packets(None, false, false, &my_pubkey),
BufferedPacketsDecision::Hold BufferedPacketsDecision::Hold
); );
assert_eq!( assert_eq!(
BankingStage::consume_or_forward_packets(None, false, false, &my_id1), BankingStage::consume_or_forward_packets(None, false, false, &my_pubkey1),
BufferedPacketsDecision::Hold BufferedPacketsDecision::Hold
); );
assert_eq!( assert_eq!(
BankingStage::consume_or_forward_packets(Some(my_id1.clone()), false, false, &my_id), BankingStage::consume_or_forward_packets(
Some(my_pubkey1.clone()),
false,
false,
&my_pubkey
),
BufferedPacketsDecision::Forward BufferedPacketsDecision::Forward
); );
assert_eq!( assert_eq!(
BankingStage::consume_or_forward_packets(Some(my_id1.clone()), false, true, &my_id), BankingStage::consume_or_forward_packets(
Some(my_pubkey1.clone()),
false,
true,
&my_pubkey
),
BufferedPacketsDecision::Hold BufferedPacketsDecision::Hold
); );
assert_eq!( assert_eq!(
BankingStage::consume_or_forward_packets(Some(my_id1.clone()), true, false, &my_id), BankingStage::consume_or_forward_packets(
Some(my_pubkey1.clone()),
true,
false,
&my_pubkey
),
BufferedPacketsDecision::Consume BufferedPacketsDecision::Consume
); );
assert_eq!( assert_eq!(
BankingStage::consume_or_forward_packets(Some(my_id1.clone()), false, false, &my_id1), BankingStage::consume_or_forward_packets(
Some(my_pubkey1.clone()),
false,
false,
&my_pubkey1
),
BufferedPacketsDecision::Hold BufferedPacketsDecision::Hold
); );
assert_eq!( assert_eq!(
BankingStage::consume_or_forward_packets(Some(my_id1.clone()), true, false, &my_id1), BankingStage::consume_or_forward_packets(
Some(my_pubkey1.clone()),
true,
false,
&my_pubkey1
),
BufferedPacketsDecision::Consume BufferedPacketsDecision::Consume
); );
} }

View File

@ -65,14 +65,14 @@ pub trait BlockstreamEvents {
&self, &self,
slot: u64, slot: u64,
tick_height: u64, tick_height: u64,
leader_id: &Pubkey, leader_pubkey: &Pubkey,
entries: &Entry, entries: &Entry,
) -> Result<()>; ) -> Result<()>;
fn emit_block_event( fn emit_block_event(
&self, &self,
slot: u64, slot: u64,
tick_height: u64, tick_height: u64,
leader_id: &Pubkey, leader_pubkey: &Pubkey,
blockhash: Hash, blockhash: Hash,
) -> Result<()>; ) -> Result<()>;
} }
@ -90,7 +90,7 @@ where
&self, &self,
slot: u64, slot: u64,
tick_height: u64, tick_height: u64,
leader_id: &Pubkey, leader_pubkey: &Pubkey,
entry: &Entry, entry: &Entry,
) -> Result<()> { ) -> Result<()> {
let transactions: Vec<Vec<u8>> = serialize_transactions(entry); let transactions: Vec<Vec<u8>> = serialize_transactions(entry);
@ -105,7 +105,7 @@ where
Utc::now().to_rfc3339_opts(SecondsFormat::Nanos, true), Utc::now().to_rfc3339_opts(SecondsFormat::Nanos, true),
slot, slot,
tick_height, tick_height,
leader_id, leader_pubkey,
json_entry, json_entry,
); );
self.output.write(payload)?; self.output.write(payload)?;
@ -116,7 +116,7 @@ where
&self, &self,
slot: u64, slot: u64,
tick_height: u64, tick_height: u64,
leader_id: &Pubkey, leader_pubkey: &Pubkey,
blockhash: Hash, blockhash: Hash,
) -> Result<()> { ) -> Result<()> {
let payload = format!( let payload = format!(
@ -124,7 +124,7 @@ where
Utc::now().to_rfc3339_opts(SecondsFormat::Nanos, true), Utc::now().to_rfc3339_opts(SecondsFormat::Nanos, true),
slot, slot,
tick_height, tick_height,
leader_id, leader_pubkey,
blockhash, blockhash,
); );
self.output.write(payload)?; self.output.write(payload)?;
@ -206,19 +206,19 @@ mod test {
let tick_height_initial = 0; let tick_height_initial = 0;
let tick_height_final = tick_height_initial + ticks_per_slot + 2; let tick_height_final = tick_height_initial + ticks_per_slot + 2;
let mut curr_slot = 0; let mut curr_slot = 0;
let leader_id = Pubkey::new_rand(); let leader_pubkey = Pubkey::new_rand();
for tick_height in tick_height_initial..=tick_height_final { for tick_height in tick_height_initial..=tick_height_final {
if tick_height == 5 { if tick_height == 5 {
blockstream blockstream
.emit_block_event(curr_slot, tick_height - 1, &leader_id, blockhash) .emit_block_event(curr_slot, tick_height - 1, &leader_pubkey, blockhash)
.unwrap(); .unwrap();
curr_slot += 1; curr_slot += 1;
} }
let entry = Entry::new(&mut blockhash, 1, vec![]); // just ticks let entry = Entry::new(&mut blockhash, 1, vec![]); // just ticks
blockhash = entry.hash; blockhash = entry.hash;
blockstream blockstream
.emit_entry_event(curr_slot, tick_height, &leader_id, &entry) .emit_entry_event(curr_slot, tick_height, &leader_pubkey, &entry)
.unwrap(); .unwrap();
expected_entries.push(entry.clone()); expected_entries.push(entry.clone());
entries.push(entry); entries.push(entry);

View File

@ -121,7 +121,7 @@ mod test {
#[test] #[test]
fn test_blockstream_service_process_entries() { fn test_blockstream_service_process_entries() {
let ticks_per_slot = 5; let ticks_per_slot = 5;
let leader_id = Pubkey::new_rand(); let leader_pubkey = Pubkey::new_rand();
// Set up genesis block and blocktree // Set up genesis block and blocktree
let GenesisBlockInfo { let GenesisBlockInfo {
@ -162,7 +162,7 @@ mod test {
.write_entries(1, 0, 0, ticks_per_slot, &entries) .write_entries(1, 0, 0, ticks_per_slot, &entries)
.unwrap(); .unwrap();
slot_full_sender.send((1, leader_id)).unwrap(); slot_full_sender.send((1, leader_pubkey)).unwrap();
BlockstreamService::process_entries( BlockstreamService::process_entries(
&slot_full_receiver, &slot_full_receiver,
&Arc::new(blocktree), &Arc::new(blocktree),

View File

@ -1,6 +1,6 @@
use solana_sdk::pubkey::Pubkey; use solana_sdk::pubkey::Pubkey;
pub trait Cluster { pub trait Cluster {
fn get_node_ids(&self) -> Vec<Pubkey>; fn get_node_pubkeys(&self) -> Vec<Pubkey>;
fn restart_node(&mut self, pubkey: Pubkey); fn restart_node(&mut self, pubkey: Pubkey);
} }

View File

@ -72,9 +72,9 @@ pub struct ClusterInfo {
pub gossip: CrdsGossip, pub gossip: CrdsGossip,
/// set the keypair that will be used to sign crds values generated. It is unset only in tests. /// set the keypair that will be used to sign crds values generated. It is unset only in tests.
pub(crate) keypair: Arc<Keypair>, pub(crate) keypair: Arc<Keypair>,
// TODO: remove gossip_leader_id once all usage of `set_leader()` and `leader_data()` is // TODO: remove gossip_leader_pubkey once all usage of `set_leader()` and `leader_data()` is
// purged // purged
gossip_leader_id: Pubkey, gossip_leader_pubkey: Pubkey,
/// The network entrypoint /// The network entrypoint
entrypoint: Option<ContactInfo>, entrypoint: Option<ContactInfo>,
} }
@ -175,7 +175,7 @@ impl ClusterInfo {
let mut me = Self { let mut me = Self {
gossip: CrdsGossip::default(), gossip: CrdsGossip::default(),
keypair, keypair,
gossip_leader_id: Pubkey::default(), gossip_leader_pubkey: Pubkey::default(),
entrypoint: None, entrypoint: None,
}; };
let id = contact_info.id; let id = contact_info.id;
@ -232,18 +232,18 @@ impl ClusterInfo {
// Deprecated: don't use leader_data(). // Deprecated: don't use leader_data().
pub fn leader_data(&self) -> Option<&ContactInfo> { pub fn leader_data(&self) -> Option<&ContactInfo> {
let leader_id = self.gossip_leader_id; let leader_pubkey = self.gossip_leader_pubkey;
if leader_id == Pubkey::default() { if leader_pubkey == Pubkey::default() {
return None; return None;
} }
self.lookup(&leader_id) self.lookup(&leader_pubkey)
} }
pub fn contact_info_trace(&self) -> String { pub fn contact_info_trace(&self) -> String {
let now = timestamp(); let now = timestamp();
let mut spy_nodes = 0; let mut spy_nodes = 0;
let mut replicators = 0; let mut replicators = 0;
let my_id = self.my_data().id; let my_pubkey = self.my_data().id;
let nodes: Vec<_> = self let nodes: Vec<_> = self
.all_peers() .all_peers()
.into_iter() .into_iter()
@ -268,7 +268,7 @@ impl ClusterInfo {
addr_to_string(&node.gossip), addr_to_string(&node.gossip),
now.saturating_sub(last_updated), now.saturating_sub(last_updated),
node.id, node.id,
if node.id == my_id { "(me)" } else { "" }.to_string(), if node.id == my_pubkey { "(me)" } else { "" }.to_string(),
addr_to_string(&node.tpu), addr_to_string(&node.tpu),
addr_to_string(&node.rpc), addr_to_string(&node.rpc),
) )
@ -296,13 +296,13 @@ impl ClusterInfo {
} }
/// Record the id of the current leader for use by `leader_tpu_via_blobs()` /// Record the id of the current leader for use by `leader_tpu_via_blobs()`
pub fn set_leader(&mut self, leader_id: &Pubkey) { pub fn set_leader(&mut self, leader_pubkey: &Pubkey) {
if *leader_id != self.gossip_leader_id { if *leader_pubkey != self.gossip_leader_pubkey {
warn!( warn!(
"{}: LEADER_UPDATE TO {} from {}", "{}: LEADER_UPDATE TO {} from {}",
self.gossip.id, leader_id, self.gossip_leader_id, self.gossip.id, leader_pubkey, self.gossip_leader_pubkey,
); );
self.gossip_leader_id = *leader_id; self.gossip_leader_pubkey = *leader_pubkey;
} }
} }
@ -730,7 +730,7 @@ impl ClusterInfo {
obj: &Arc<RwLock<Self>>, obj: &Arc<RwLock<Self>>,
peers: &[ContactInfo], peers: &[ContactInfo],
blob: &SharedBlob, blob: &SharedBlob,
slot_leader_id: Option<Pubkey>, slot_leader_pubkey: Option<Pubkey>,
s: &UdpSocket, s: &UdpSocket,
forwarded: bool, forwarded: bool,
) -> Result<()> { ) -> Result<()> {
@ -746,7 +746,7 @@ impl ClusterInfo {
trace!("retransmit orders {}", orders.len()); trace!("retransmit orders {}", orders.len());
let errs: Vec<_> = orders let errs: Vec<_> = orders
.par_iter() .par_iter()
.filter(|v| v.id != slot_leader_id.unwrap_or_default()) .filter(|v| v.id != slot_leader_pubkey.unwrap_or_default())
.map(|v| { .map(|v| {
debug!( debug!(
"{}: retransmit blob {} to {} {}", "{}: retransmit blob {} to {} {}",
@ -2283,8 +2283,8 @@ fn test_add_entrypoint() {
ContactInfo::new_localhost(&node_keypair.pubkey(), timestamp()), ContactInfo::new_localhost(&node_keypair.pubkey(), timestamp()),
node_keypair, node_keypair,
); );
let entrypoint_id = Pubkey::new_rand(); let entrypoint_pubkey = Pubkey::new_rand();
let entrypoint = ContactInfo::new_localhost(&entrypoint_id, timestamp()); let entrypoint = ContactInfo::new_localhost(&entrypoint_pubkey, timestamp());
cluster_info.set_entrypoint(entrypoint.clone()); cluster_info.set_entrypoint(entrypoint.clone());
let pulls = cluster_info.new_pull_requests(&HashMap::new()); let pulls = cluster_info.new_pull_requests(&HashMap::new());
assert_eq!(1, pulls.len()); assert_eq!(1, pulls.len());
@ -2305,7 +2305,11 @@ fn test_add_entrypoint() {
// now add this message back to the table and make sure after the next pull, the entrypoint is unset // now add this message back to the table and make sure after the next pull, the entrypoint is unset
let entrypoint_crdsvalue = CrdsValue::ContactInfo(entrypoint.clone()); let entrypoint_crdsvalue = CrdsValue::ContactInfo(entrypoint.clone());
let cluster_info = Arc::new(RwLock::new(cluster_info)); let cluster_info = Arc::new(RwLock::new(cluster_info));
ClusterInfo::handle_pull_response(&cluster_info, &entrypoint_id, vec![entrypoint_crdsvalue]); ClusterInfo::handle_pull_response(
&cluster_info,
&entrypoint_pubkey,
vec![entrypoint_crdsvalue],
);
let pulls = cluster_info let pulls = cluster_info
.write() .write()
.unwrap() .unwrap()

View File

@ -111,7 +111,7 @@ impl ClusterInfoRepairListener {
epoch_schedule: &EpochSchedule, epoch_schedule: &EpochSchedule,
) -> Result<()> { ) -> Result<()> {
let socket = UdpSocket::bind("0.0.0.0:0").unwrap(); let socket = UdpSocket::bind("0.0.0.0:0").unwrap();
let my_id = cluster_info.read().unwrap().id(); let my_pubkey = cluster_info.read().unwrap().id();
let mut my_gossiped_root = 0; let mut my_gossiped_root = 0;
loop { loop {
@ -127,7 +127,7 @@ impl ClusterInfoRepairListener {
for peer in peers { for peer in peers {
let last_update_ts = Self::get_last_ts(peer.id, peer_roots); let last_update_ts = Self::get_last_ts(peer.id, peer_roots);
let my_root = let my_root =
Self::read_my_gossiped_root(&my_id, cluster_info, &mut my_gossiped_root); Self::read_my_gossiped_root(&my_pubkey, cluster_info, &mut my_gossiped_root);
{ {
let r_cluster_info = cluster_info.read().unwrap(); let r_cluster_info = cluster_info.read().unwrap();
@ -155,7 +155,7 @@ impl ClusterInfoRepairListener {
// After updating all the peers, send out repairs to those that need it // After updating all the peers, send out repairs to those that need it
let _ = Self::serve_repairs( let _ = Self::serve_repairs(
&my_id, &my_pubkey,
blocktree, blocktree,
peer_roots, peer_roots,
&peers_needing_repairs, &peers_needing_repairs,
@ -170,7 +170,7 @@ impl ClusterInfoRepairListener {
} }
fn serve_repairs( fn serve_repairs(
my_id: &Pubkey, my_pubkey: &Pubkey,
blocktree: &Blocktree, blocktree: &Blocktree,
peer_roots: &HashMap<Pubkey, (u64, u64)>, peer_roots: &HashMap<Pubkey, (u64, u64)>,
repairees: &HashMap<Pubkey, EpochSlots>, repairees: &HashMap<Pubkey, EpochSlots>,
@ -179,19 +179,19 @@ impl ClusterInfoRepairListener {
my_gossiped_root: &mut u64, my_gossiped_root: &mut u64,
epoch_schedule: &EpochSchedule, epoch_schedule: &EpochSchedule,
) -> Result<()> { ) -> Result<()> {
for (repairee_id, repairee_epoch_slots) in repairees { for (repairee_pubkey, repairee_epoch_slots) in repairees {
let repairee_root = repairee_epoch_slots.root; let repairee_root = repairee_epoch_slots.root;
let repairee_tvu = { let repairee_tvu = {
let r_cluster_info = cluster_info.read().unwrap(); let r_cluster_info = cluster_info.read().unwrap();
let contact_info = r_cluster_info.get_contact_info_for_node(repairee_id); let contact_info = r_cluster_info.get_contact_info_for_node(repairee_pubkey);
contact_info.map(|c| c.tvu) contact_info.map(|c| c.tvu)
}; };
if let Some(repairee_tvu) = repairee_tvu { if let Some(repairee_tvu) = repairee_tvu {
// For every repairee, get the set of repairmen who are responsible for // For every repairee, get the set of repairmen who are responsible for
let mut eligible_repairmen = Self::find_eligible_repairmen( let mut eligible_repairmen = Self::find_eligible_repairmen(
my_id, my_pubkey,
repairee_root, repairee_root,
peer_roots, peer_roots,
NUM_BUFFER_SLOTS, NUM_BUFFER_SLOTS,
@ -199,14 +199,15 @@ impl ClusterInfoRepairListener {
Self::shuffle_repairmen( Self::shuffle_repairmen(
&mut eligible_repairmen, &mut eligible_repairmen,
repairee_id, repairee_pubkey,
repairee_epoch_slots.root, repairee_epoch_slots.root,
); );
let my_root = Self::read_my_gossiped_root(my_id, cluster_info, my_gossiped_root); let my_root =
Self::read_my_gossiped_root(my_pubkey, cluster_info, my_gossiped_root);
let _ = Self::serve_repairs_to_repairee( let _ = Self::serve_repairs_to_repairee(
my_id, my_pubkey,
my_root, my_root,
blocktree, blocktree,
&repairee_epoch_slots, &repairee_epoch_slots,
@ -223,7 +224,7 @@ impl ClusterInfoRepairListener {
} }
fn serve_repairs_to_repairee( fn serve_repairs_to_repairee(
my_id: &Pubkey, my_pubkey: &Pubkey,
my_root: u64, my_root: u64,
blocktree: &Blocktree, blocktree: &Blocktree,
repairee_epoch_slots: &EpochSlots, repairee_epoch_slots: &EpochSlots,
@ -266,7 +267,7 @@ impl ClusterInfoRepairListener {
// the cluster // the cluster
let num_blobs_in_slot = slot_meta.received as usize; let num_blobs_in_slot = slot_meta.received as usize;
if let Some(my_repair_indexes) = Self::calculate_my_repairman_index_for_slot( if let Some(my_repair_indexes) = Self::calculate_my_repairman_index_for_slot(
my_id, my_pubkey,
&eligible_repairmen, &eligible_repairmen,
num_blobs_in_slot, num_blobs_in_slot,
REPAIR_REDUNDANCY, REPAIR_REDUNDANCY,
@ -316,13 +317,13 @@ impl ClusterInfoRepairListener {
fn shuffle_repairmen( fn shuffle_repairmen(
eligible_repairmen: &mut Vec<&Pubkey>, eligible_repairmen: &mut Vec<&Pubkey>,
repairee_id: &Pubkey, repairee_pubkey: &Pubkey,
repairee_root: u64, repairee_root: u64,
) { ) {
// Make a seed from pubkey + repairee root // Make a seed from pubkey + repairee root
let mut seed = [0u8; mem::size_of::<Pubkey>()]; let mut seed = [0u8; mem::size_of::<Pubkey>()];
let repairee_id_bytes = repairee_id.as_ref(); let repairee_pubkey_bytes = repairee_pubkey.as_ref();
seed[..repairee_id_bytes.len()].copy_from_slice(repairee_id_bytes); seed[..repairee_pubkey_bytes.len()].copy_from_slice(repairee_pubkey_bytes);
LittleEndian::write_u64(&mut seed[0..], repairee_root); LittleEndian::write_u64(&mut seed[0..], repairee_root);
// Deterministically shuffle the eligible repairmen based on the seed // Deterministically shuffle the eligible repairmen based on the seed
@ -334,7 +335,7 @@ impl ClusterInfoRepairListener {
// such that each blob in the slot is the responsibility of `repair_redundancy` or // such that each blob in the slot is the responsibility of `repair_redundancy` or
// `repair_redundancy + 1` number of repairmen in the cluster. // `repair_redundancy + 1` number of repairmen in the cluster.
fn calculate_my_repairman_index_for_slot( fn calculate_my_repairman_index_for_slot(
my_id: &Pubkey, my_pubkey: &Pubkey,
eligible_repairmen: &[&Pubkey], eligible_repairmen: &[&Pubkey],
num_blobs_in_slot: usize, num_blobs_in_slot: usize,
repair_redundancy: usize, repair_redundancy: usize,
@ -350,7 +351,7 @@ impl ClusterInfoRepairListener {
// Calculate the indexes this node is responsible for // Calculate the indexes this node is responsible for
if let Some(my_position) = eligible_repairmen[..total_repairmen_for_slot] if let Some(my_position) = eligible_repairmen[..total_repairmen_for_slot]
.iter() .iter()
.position(|id| *id == my_id) .position(|id| *id == my_pubkey)
{ {
let start_index = my_position % num_blobs_in_slot; let start_index = my_position % num_blobs_in_slot;
Some(BlobIndexesToRepairIterator::new( Some(BlobIndexesToRepairIterator::new(
@ -367,7 +368,7 @@ impl ClusterInfoRepairListener {
} }
fn find_eligible_repairmen<'a>( fn find_eligible_repairmen<'a>(
my_id: &'a Pubkey, my_pubkey: &'a Pubkey,
repairee_root: u64, repairee_root: u64,
repairman_roots: &'a HashMap<Pubkey, (u64, u64)>, repairman_roots: &'a HashMap<Pubkey, (u64, u64)>,
num_buffer_slots: usize, num_buffer_slots: usize,
@ -387,19 +388,19 @@ impl ClusterInfoRepairListener {
}) })
.collect(); .collect();
repairmen.push(my_id); repairmen.push(my_pubkey);
repairmen repairmen
} }
fn read_my_gossiped_root( fn read_my_gossiped_root(
my_id: &Pubkey, my_pubkey: &Pubkey,
cluster_info: &Arc<RwLock<ClusterInfo>>, cluster_info: &Arc<RwLock<ClusterInfo>>,
old_root: &mut u64, old_root: &mut u64,
) -> u64 { ) -> u64 {
let new_root = cluster_info let new_root = cluster_info
.read() .read()
.unwrap() .unwrap()
.get_gossiped_root_for_node(&my_id, None); .get_gossiped_root_for_node(&my_pubkey, None);
if let Some(new_root) = new_root { if let Some(new_root) = new_root {
*old_root = new_root; *old_root = new_root;
@ -519,7 +520,7 @@ mod tests {
blocktree.set_root(num_slots - 1, 0).unwrap(); blocktree.set_root(num_slots - 1, 0).unwrap();
// Set up my information // Set up my information
let my_id = Pubkey::new_rand(); let my_pubkey = Pubkey::new_rand();
let my_socket = UdpSocket::bind("0.0.0.0:0").unwrap(); let my_socket = UdpSocket::bind("0.0.0.0:0").unwrap();
// Set up a mock repairee with a socket listening for incoming repairs // Set up a mock repairee with a socket listening for incoming repairs
@ -536,7 +537,7 @@ mod tests {
let num_repairmen = blobs_per_slot - 1; let num_repairmen = blobs_per_slot - 1;
let mut eligible_repairmen: Vec<_> = let mut eligible_repairmen: Vec<_> =
(0..num_repairmen).map(|_| Pubkey::new_rand()).collect(); (0..num_repairmen).map(|_| Pubkey::new_rand()).collect();
eligible_repairmen.push(my_id); eligible_repairmen.push(my_pubkey);
let eligible_repairmen_refs: Vec<_> = eligible_repairmen.iter().collect(); let eligible_repairmen_refs: Vec<_> = eligible_repairmen.iter().collect();
// Have all the repairman send the repairs // Have all the repairman send the repairs
@ -595,7 +596,7 @@ mod tests {
blocktree.set_root(slots_per_epoch * 2 - 1, 0).unwrap(); blocktree.set_root(slots_per_epoch * 2 - 1, 0).unwrap();
// Set up my information // Set up my information
let my_id = Pubkey::new_rand(); let my_pubkey = Pubkey::new_rand();
let my_socket = UdpSocket::bind("0.0.0.0:0").unwrap(); let my_socket = UdpSocket::bind("0.0.0.0:0").unwrap();
// Set up a mock repairee with a socket listening for incoming repairs // Set up a mock repairee with a socket listening for incoming repairs
@ -613,11 +614,11 @@ mod tests {
EpochSlots::new(mock_repairee.id, repairee_root, repairee_slots.clone(), 1); EpochSlots::new(mock_repairee.id, repairee_root, repairee_slots.clone(), 1);
ClusterInfoRepairListener::serve_repairs_to_repairee( ClusterInfoRepairListener::serve_repairs_to_repairee(
&my_id, &my_pubkey,
total_slots - 1, total_slots - 1,
&blocktree, &blocktree,
&repairee_epoch_slots, &repairee_epoch_slots,
&vec![&my_id], &vec![&my_pubkey],
&my_socket, &my_socket,
&mock_repairee.tvu_address, &mock_repairee.tvu_address,
1 as usize, 1 as usize,
@ -634,11 +635,11 @@ mod tests {
let repairee_epoch_slots = let repairee_epoch_slots =
EpochSlots::new(mock_repairee.id, stakers_slot_offset, repairee_slots, 1); EpochSlots::new(mock_repairee.id, stakers_slot_offset, repairee_slots, 1);
ClusterInfoRepairListener::serve_repairs_to_repairee( ClusterInfoRepairListener::serve_repairs_to_repairee(
&my_id, &my_pubkey,
total_slots - 1, total_slots - 1,
&blocktree, &blocktree,
&repairee_epoch_slots, &repairee_epoch_slots,
&vec![&my_id], &vec![&my_pubkey],
&my_socket, &my_socket,
&mock_repairee.tvu_address, &mock_repairee.tvu_address,
1 as usize, 1 as usize,

View File

@ -263,7 +263,7 @@ mod test {
fn test_new_mark_creation_time() { fn test_new_mark_creation_time() {
let mut crds = Crds::default(); let mut crds = Crds::default();
let entry = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0)); let entry = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
let node_id = entry.label().pubkey(); let node_pubkey = entry.label().pubkey();
let mut node = CrdsGossipPull::default(); let mut node = CrdsGossipPull::default();
crds.insert(entry.clone(), 0).unwrap(); crds.insert(entry.clone(), 0).unwrap();
let old = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0)); let old = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
@ -276,7 +276,7 @@ mod test {
// odds of getting the other request should be 1 in u64::max_value() // odds of getting the other request should be 1 in u64::max_value()
for _ in 0..10 { for _ in 0..10 {
let req = node.new_pull_request(&crds, &node_id, u64::max_value(), &HashMap::new()); let req = node.new_pull_request(&crds, &node_pubkey, u64::max_value(), &HashMap::new());
let (to, _, self_info) = req.unwrap(); let (to, _, self_info) = req.unwrap();
assert_eq!(to, old.label().pubkey()); assert_eq!(to, old.label().pubkey());
assert_eq!(self_info, entry); assert_eq!(self_info, entry);
@ -287,12 +287,12 @@ mod test {
fn test_process_pull_request() { fn test_process_pull_request() {
let mut node_crds = Crds::default(); let mut node_crds = Crds::default();
let entry = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0)); let entry = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
let node_id = entry.label().pubkey(); let node_pubkey = entry.label().pubkey();
let node = CrdsGossipPull::default(); let node = CrdsGossipPull::default();
node_crds.insert(entry.clone(), 0).unwrap(); node_crds.insert(entry.clone(), 0).unwrap();
let new = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0)); let new = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
node_crds.insert(new.clone(), 0).unwrap(); node_crds.insert(new.clone(), 0).unwrap();
let req = node.new_pull_request(&node_crds, &node_id, 0, &HashMap::new()); let req = node.new_pull_request(&node_crds, &node_pubkey, 0, &HashMap::new());
let mut dest_crds = Crds::default(); let mut dest_crds = Crds::default();
let mut dest = CrdsGossipPull::default(); let mut dest = CrdsGossipPull::default();
@ -319,7 +319,7 @@ mod test {
fn test_process_pull_request_response() { fn test_process_pull_request_response() {
let mut node_crds = Crds::default(); let mut node_crds = Crds::default();
let entry = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0)); let entry = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
let node_id = entry.label().pubkey(); let node_pubkey = entry.label().pubkey();
let mut node = CrdsGossipPull::default(); let mut node = CrdsGossipPull::default();
node_crds.insert(entry.clone(), 0).unwrap(); node_crds.insert(entry.clone(), 0).unwrap();
@ -347,7 +347,7 @@ mod test {
let mut done = false; let mut done = false;
for _ in 0..30 { for _ in 0..30 {
// there is a chance of a false positive with bloom filters // there is a chance of a false positive with bloom filters
let req = node.new_pull_request(&node_crds, &node_id, 0, &HashMap::new()); let req = node.new_pull_request(&node_crds, &node_pubkey, 0, &HashMap::new());
let (_, filter, caller) = req.unwrap(); let (_, filter, caller) = req.unwrap();
let rsp = dest.process_pull_request(&mut dest_crds, caller, filter, 0); let rsp = dest.process_pull_request(&mut dest_crds, caller, filter, 0);
// if there is a false positive this is empty // if there is a false positive this is empty
@ -357,7 +357,7 @@ mod test {
} }
assert_eq!(rsp.len(), 1); assert_eq!(rsp.len(), 1);
let failed = node.process_pull_response(&mut node_crds, &node_id, rsp, 1); let failed = node.process_pull_response(&mut node_crds, &node_pubkey, rsp, 1);
assert_eq!(failed, 0); assert_eq!(failed, 0);
assert_eq!( assert_eq!(
node_crds node_crds
@ -384,7 +384,7 @@ mod test {
let mut node_crds = Crds::default(); let mut node_crds = Crds::default();
let entry = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0)); let entry = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
let node_label = entry.label(); let node_label = entry.label();
let node_id = node_label.pubkey(); let node_pubkey = node_label.pubkey();
let mut node = CrdsGossipPull::default(); let mut node = CrdsGossipPull::default();
node_crds.insert(entry.clone(), 0).unwrap(); node_crds.insert(entry.clone(), 0).unwrap();
let old = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0)); let old = CrdsValue::ContactInfo(ContactInfo::new_localhost(&Pubkey::new_rand(), 0));
@ -395,7 +395,7 @@ mod test {
assert_eq!(node_crds.lookup(&node_label).unwrap().label(), node_label); assert_eq!(node_crds.lookup(&node_label).unwrap().label(), node_label);
// purge // purge
node.purge_active(&mut node_crds, &node_id, 1); node.purge_active(&mut node_crds, &node_pubkey, 1);
//verify self is still valid after purge //verify self is still valid after purge
assert_eq!(node_crds.lookup(&node_label).unwrap().label(), node_label); assert_eq!(node_crds.lookup(&node_label).unwrap().label(), node_label);

View File

@ -385,13 +385,13 @@ mod tests {
let cache = Arc::new(LeaderScheduleCache::new_from_bank(&bank)); let cache = Arc::new(LeaderScheduleCache::new_from_bank(&bank));
// Create new vote account // Create new vote account
let node_id = Pubkey::new_rand(); let node_pubkey = Pubkey::new_rand();
let vote_id = Pubkey::new_rand(); let vote_pubkey = Pubkey::new_rand();
setup_vote_and_stake_accounts( setup_vote_and_stake_accounts(
&bank, &bank,
&mint_keypair, &mint_keypair,
&vote_id, &vote_pubkey,
&node_id, &node_pubkey,
BOOTSTRAP_LEADER_LAMPORTS, BOOTSTRAP_LEADER_LAMPORTS,
); );
@ -412,14 +412,14 @@ mod tests {
let schedule = cache.compute_epoch_schedule(epoch, &bank).unwrap(); let schedule = cache.compute_epoch_schedule(epoch, &bank).unwrap();
let mut index = 0; let mut index = 0;
while schedule[index] != node_id { while schedule[index] != node_pubkey {
index += 1; index += 1;
assert_ne!(index, genesis_block.slots_per_epoch); assert_ne!(index, genesis_block.slots_per_epoch);
} }
expected_slot += index; expected_slot += index;
assert_eq!( assert_eq!(
cache.next_leader_slot(&node_id, 0, &bank, None), cache.next_leader_slot(&node_pubkey, 0, &bank, None),
Some(expected_slot), Some(expected_slot),
); );
} }

View File

@ -41,9 +41,9 @@ fn sort_stakes(stakes: &mut Vec<(Pubkey, u64)>) {
// Sort first by stake. If stakes are the same, sort by pubkey to ensure a // Sort first by stake. If stakes are the same, sort by pubkey to ensure a
// deterministic result. // deterministic result.
// Note: Use unstable sort, because we dedup right after to remove the equal elements. // Note: Use unstable sort, because we dedup right after to remove the equal elements.
stakes.sort_unstable_by(|(l_id, l_stake), (r_id, r_stake)| { stakes.sort_unstable_by(|(l_pubkey, l_stake), (r_pubkey, r_stake)| {
if r_stake == l_stake { if r_stake == l_stake {
r_id.cmp(&l_id) r_pubkey.cmp(&l_pubkey)
} else { } else {
r_stake.cmp(&l_stake) r_stake.cmp(&l_stake)
} }
@ -68,10 +68,10 @@ mod tests {
create_genesis_block_with_leader(0, &pubkey, BOOTSTRAP_LEADER_LAMPORTS).genesis_block; create_genesis_block_with_leader(0, &pubkey, BOOTSTRAP_LEADER_LAMPORTS).genesis_block;
let bank = Bank::new(&genesis_block); let bank = Bank::new(&genesis_block);
let ids_and_stakes: Vec<_> = staking_utils::staked_nodes(&bank).into_iter().collect(); let pubkeys_and_stakes: Vec<_> = staking_utils::staked_nodes(&bank).into_iter().collect();
let seed = [0u8; 32]; let seed = [0u8; 32];
let leader_schedule = LeaderSchedule::new( let leader_schedule = LeaderSchedule::new(
&ids_and_stakes, &pubkeys_and_stakes,
seed, seed,
genesis_block.slots_per_epoch, genesis_block.slots_per_epoch,
NUM_CONSECUTIVE_LEADER_SLOTS, NUM_CONSECUTIVE_LEADER_SLOTS,

View File

@ -36,14 +36,14 @@ pub struct ValidatorInfo {
} }
pub struct ReplicatorInfo { pub struct ReplicatorInfo {
pub replicator_storage_id: Pubkey, pub replicator_storage_pubkey: Pubkey,
pub ledger_path: String, pub ledger_path: String,
} }
impl ReplicatorInfo { impl ReplicatorInfo {
fn new(storage_id: Pubkey, ledger_path: String) -> Self { fn new(storage_pubkey: Pubkey, ledger_path: String) -> Self {
Self { Self {
replicator_storage_id: storage_id, replicator_storage_pubkey: storage_pubkey,
ledger_path, ledger_path,
} }
} }
@ -396,7 +396,7 @@ impl LocalCluster {
amount: u64, amount: u64,
) -> Result<()> { ) -> Result<()> {
let vote_account_pubkey = vote_account.pubkey(); let vote_account_pubkey = vote_account.pubkey();
let node_id = from_account.pubkey(); let node_pubkey = from_account.pubkey();
// Create the vote account if necessary // Create the vote account if necessary
if client.poll_get_balance(&vote_account_pubkey).unwrap_or(0) == 0 { if client.poll_get_balance(&vote_account_pubkey).unwrap_or(0) == 0 {
@ -407,7 +407,7 @@ impl LocalCluster {
vote_instruction::create_account( vote_instruction::create_account(
&from_account.pubkey(), &from_account.pubkey(),
&vote_account_pubkey, &vote_account_pubkey,
&node_id, &node_pubkey,
0, 0,
amount, amount,
), ),
@ -461,7 +461,7 @@ impl LocalCluster {
let vote_account_user_data = client.get_account_data(&vote_account_pubkey); let vote_account_user_data = client.get_account_data(&vote_account_pubkey);
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) = VoteState::deserialize(&vote_account_user_data) { if let Ok(vote_state) = VoteState::deserialize(&vote_account_user_data) {
if vote_state.node_id == node_id { if vote_state.node_pubkey == node_pubkey {
info!("vote account registered"); info!("vote account registered");
return Ok(()); return Ok(());
} }
@ -506,7 +506,7 @@ impl LocalCluster {
} }
impl Cluster for LocalCluster { impl Cluster for LocalCluster {
fn get_node_ids(&self) -> Vec<Pubkey> { fn get_node_pubkeys(&self) -> Vec<Pubkey> {
self.fullnodes.keys().cloned().collect() self.fullnodes.keys().cloned().collect()
} }

View File

@ -20,7 +20,7 @@ pub struct EpochStakes {
stakes: HashMap<Pubkey, u64>, stakes: HashMap<Pubkey, u64>,
self_staked: u64, self_staked: u64,
total_staked: u64, total_staked: u64,
delegate_id: Pubkey, delegate_pubkey: Pubkey,
} }
#[derive(Default, Debug)] #[derive(Default, Debug)]
@ -39,15 +39,15 @@ pub struct Locktower {
} }
impl EpochStakes { impl EpochStakes {
pub fn new(epoch: u64, stakes: HashMap<Pubkey, u64>, delegate_id: &Pubkey) -> Self { pub fn new(epoch: u64, stakes: HashMap<Pubkey, u64>, delegate_pubkey: &Pubkey) -> Self {
let total_staked = stakes.values().sum(); let total_staked = stakes.values().sum();
let self_staked = *stakes.get(&delegate_id).unwrap_or(&0); let self_staked = *stakes.get(&delegate_pubkey).unwrap_or(&0);
Self { Self {
epoch, epoch,
stakes, stakes,
total_staked, total_staked,
self_staked, self_staked,
delegate_id: *delegate_id, delegate_pubkey: *delegate_pubkey,
} }
} }
pub fn new_for_tests(lamports: u64) -> Self { pub fn new_for_tests(lamports: u64) -> Self {
@ -61,21 +61,21 @@ impl EpochStakes {
let stakes = accounts.iter().map(|(k, (v, _))| (*k, *v)).collect(); let stakes = accounts.iter().map(|(k, (v, _))| (*k, *v)).collect();
Self::new(epoch, stakes, &accounts[0].0) Self::new(epoch, stakes, &accounts[0].0)
} }
pub fn new_from_bank(bank: &Bank, my_id: &Pubkey) -> Self { pub fn new_from_bank(bank: &Bank, my_pubkey: &Pubkey) -> Self {
let bank_epoch = bank.get_epoch_and_slot_index(bank.slot()).0; let bank_epoch = bank.get_epoch_and_slot_index(bank.slot()).0;
let stakes = staking_utils::vote_account_stakes_at_epoch(bank, bank_epoch) let stakes = staking_utils::vote_account_stakes_at_epoch(bank, bank_epoch)
.expect("voting require a bank with stakes"); .expect("voting require a bank with stakes");
Self::new(bank_epoch, stakes, my_id) Self::new(bank_epoch, stakes, my_pubkey)
} }
} }
impl Locktower { impl Locktower {
pub fn new_from_forks(bank_forks: &BankForks, my_id: &Pubkey) -> Self { pub fn new_from_forks(bank_forks: &BankForks, my_pubkey: &Pubkey) -> Self {
let mut frozen_banks: Vec<_> = bank_forks.frozen_banks().values().cloned().collect(); let mut frozen_banks: Vec<_> = bank_forks.frozen_banks().values().cloned().collect();
frozen_banks.sort_by_key(|b| (b.parents().len(), b.slot())); frozen_banks.sort_by_key(|b| (b.parents().len(), b.slot()));
let epoch_stakes = { let epoch_stakes = {
if let Some(bank) = frozen_banks.last() { if let Some(bank) = frozen_banks.last() {
EpochStakes::new_from_bank(bank, my_id) EpochStakes::new_from_bank(bank, my_pubkey)
} else { } else {
return Self::default(); return Self::default();
} }
@ -124,8 +124,8 @@ impl Locktower {
} }
let mut vote_state = vote_state.unwrap(); let mut vote_state = vote_state.unwrap();
if key == self.epoch_stakes.delegate_id if key == self.epoch_stakes.delegate_pubkey
|| vote_state.node_id == self.epoch_stakes.delegate_id || vote_state.node_pubkey == self.epoch_stakes.delegate_pubkey
{ {
debug!("vote state {:?}", vote_state); debug!("vote state {:?}", vote_state);
debug!( debug!(
@ -220,7 +220,8 @@ impl Locktower {
bank.slot(), bank.slot(),
self.epoch_stakes.epoch self.epoch_stakes.epoch
); );
self.epoch_stakes = EpochStakes::new_from_bank(bank, &self.epoch_stakes.delegate_id); self.epoch_stakes =
EpochStakes::new_from_bank(bank, &self.epoch_stakes.delegate_pubkey);
datapoint_info!( datapoint_info!(
"locktower-epoch", "locktower-epoch",
("epoch", self.epoch_stakes.epoch, i64), ("epoch", self.epoch_stakes.epoch, i64),
@ -382,8 +383,8 @@ impl Locktower {
fn initialize_lockouts_from_bank(bank: &Bank, current_epoch: u64) -> VoteState { fn initialize_lockouts_from_bank(bank: &Bank, current_epoch: u64) -> VoteState {
let mut lockouts = VoteState::default(); let mut lockouts = VoteState::default();
if let Some(iter) = bank.epoch_vote_accounts(current_epoch) { if let Some(iter) = bank.epoch_vote_accounts(current_epoch) {
for (delegate_id, (_, account)) in iter { for (delegate_pubkey, (_, account)) in iter {
if *delegate_id == bank.collector_id() { if *delegate_pubkey == bank.collector_id() {
let state = VoteState::deserialize(&account.data).expect("votes"); let state = VoteState::deserialize(&account.data).expect("votes");
if lockouts.votes.len() < state.votes.len() { if lockouts.votes.len() < state.votes.len() {
lockouts = state; lockouts = state;

View File

@ -88,11 +88,12 @@ impl PohRecorder {
pub fn would_be_leader(&self, within_next_n_ticks: u64) -> bool { pub fn would_be_leader(&self, within_next_n_ticks: u64) -> bool {
let close_to_leader_tick = self.start_leader_at_tick.map_or(false, |leader_tick| { let close_to_leader_tick = self.start_leader_at_tick.map_or(false, |leader_tick| {
let leader_ideal_start_tick = let leader_pubkeyeal_start_tick =
leader_tick.saturating_sub(self.max_last_leader_grace_ticks); leader_tick.saturating_sub(self.max_last_leader_grace_ticks);
self.tick_height() <= self.last_leader_tick.unwrap_or(0) self.tick_height() <= self.last_leader_tick.unwrap_or(0)
&& self.tick_height() >= leader_ideal_start_tick.saturating_sub(within_next_n_ticks) && self.tick_height()
>= leader_pubkeyeal_start_tick.saturating_sub(within_next_n_ticks)
}); });
self.working_bank.is_some() || close_to_leader_tick self.working_bank.is_some() || close_to_leader_tick
@ -128,7 +129,7 @@ impl PohRecorder {
self.max_last_leader_grace_ticks self.max_last_leader_grace_ticks
); );
let leader_ideal_start_tick = let leader_pubkeyeal_start_tick =
target_tick.saturating_sub(self.max_last_leader_grace_ticks); target_tick.saturating_sub(self.max_last_leader_grace_ticks);
// Is the current tick in the same slot as the target tick? // Is the current tick in the same slot as the target tick?
// Check if either grace period has expired, // Check if either grace period has expired,
@ -140,7 +141,8 @@ impl PohRecorder {
{ {
return ( return (
true, true,
self.tick_height().saturating_sub(leader_ideal_start_tick), self.tick_height()
.saturating_sub(leader_pubkeyeal_start_tick),
); );
} }

View File

@ -72,7 +72,7 @@ impl ForkProgress {
impl ReplayStage { impl ReplayStage {
#[allow(clippy::new_ret_no_self, clippy::too_many_arguments)] #[allow(clippy::new_ret_no_self, clippy::too_many_arguments)]
pub fn new<T>( pub fn new<T>(
my_id: &Pubkey, my_pubkey: &Pubkey,
vote_account: &Pubkey, vote_account: &Pubkey,
voting_keypair: Option<&Arc<T>>, voting_keypair: Option<&Arc<T>>,
blocktree: Arc<Blocktree>, blocktree: Arc<Blocktree>,
@ -94,9 +94,9 @@ impl ReplayStage {
let subscriptions = subscriptions.clone(); let subscriptions = subscriptions.clone();
let bank_forks = bank_forks.clone(); let bank_forks = bank_forks.clone();
let poh_recorder = poh_recorder.clone(); let poh_recorder = poh_recorder.clone();
let my_id = *my_id; let my_pubkey = *my_pubkey;
let mut ticks_per_slot = 0; let mut ticks_per_slot = 0;
let mut locktower = Locktower::new_from_forks(&bank_forks.read().unwrap(), &my_id); let mut locktower = Locktower::new_from_forks(&bank_forks.read().unwrap(), &my_pubkey);
// Start the replay stage loop // Start the replay stage loop
let leader_schedule_cache = leader_schedule_cache.clone(); let leader_schedule_cache = leader_schedule_cache.clone();
let vote_account = *vote_account; let vote_account = *vote_account;
@ -124,7 +124,7 @@ impl ReplayStage {
Self::replay_active_banks( Self::replay_active_banks(
&blocktree, &blocktree,
&bank_forks, &bank_forks,
&my_id, &my_pubkey,
&mut ticks_per_slot, &mut ticks_per_slot,
&mut progress, &mut progress,
&slot_full_sender, &slot_full_sender,
@ -156,7 +156,7 @@ impl ReplayStage {
)?; )?;
Self::reset_poh_recorder( Self::reset_poh_recorder(
&my_id, &my_pubkey,
&blocktree, &blocktree,
&bank, &bank,
&poh_recorder, &poh_recorder,
@ -182,7 +182,7 @@ impl ReplayStage {
poh_tick_height + 1, poh_tick_height + 1,
); );
Self::start_leader( Self::start_leader(
&my_id, &my_pubkey,
&bank_forks, &bank_forks,
&poh_recorder, &poh_recorder,
&cluster_info, &cluster_info,
@ -211,7 +211,7 @@ impl ReplayStage {
(Self { t_replay }, slot_full_receiver, root_slot_receiver) (Self { t_replay }, slot_full_receiver, root_slot_receiver)
} }
pub fn start_leader( pub fn start_leader(
my_id: &Pubkey, my_pubkey: &Pubkey,
bank_forks: &Arc<RwLock<BankForks>>, bank_forks: &Arc<RwLock<BankForks>>,
poh_recorder: &Arc<Mutex<PohRecorder>>, poh_recorder: &Arc<Mutex<PohRecorder>>,
cluster_info: &Arc<RwLock<ClusterInfo>>, cluster_info: &Arc<RwLock<ClusterInfo>>,
@ -220,7 +220,7 @@ impl ReplayStage {
grace_ticks: u64, grace_ticks: u64,
leader_schedule_cache: &Arc<LeaderScheduleCache>, leader_schedule_cache: &Arc<LeaderScheduleCache>,
) { ) {
trace!("{} checking poh slot {}", my_id, poh_slot); trace!("{} checking poh slot {}", my_pubkey, poh_slot);
if bank_forks.read().unwrap().get(poh_slot).is_none() { if bank_forks.read().unwrap().get(poh_slot).is_none() {
let parent_slot = poh_recorder.lock().unwrap().start_slot(); let parent_slot = poh_recorder.lock().unwrap().start_slot();
let parent = { let parent = {
@ -235,16 +235,16 @@ impl ReplayStage {
.map(|next_leader| { .map(|next_leader| {
debug!( debug!(
"me: {} leader {} at poh slot {}", "me: {} leader {} at poh slot {}",
my_id, next_leader, poh_slot my_pubkey, next_leader, poh_slot
); );
cluster_info.write().unwrap().set_leader(&next_leader); cluster_info.write().unwrap().set_leader(&next_leader);
if next_leader == *my_id && reached_leader_tick { if next_leader == *my_pubkey && reached_leader_tick {
debug!("{} starting tpu for slot {}", my_id, poh_slot); debug!("{} starting tpu for slot {}", my_pubkey, poh_slot);
datapoint_warn!( datapoint_warn!(
"replay_stage-new_leader", "replay_stage-new_leader",
("count", poh_slot, i64), ("count", poh_slot, i64),
("grace", grace_ticks, i64)); ("grace", grace_ticks, i64));
let tpu_bank = Bank::new_from_parent(&parent, my_id, poh_slot); let tpu_bank = Bank::new_from_parent(&parent, my_pubkey, poh_slot);
bank_forks.write().unwrap().insert(tpu_bank); bank_forks.write().unwrap().insert(tpu_bank);
if let Some(tpu_bank) = bank_forks.read().unwrap().get(poh_slot).cloned() { if let Some(tpu_bank) = bank_forks.read().unwrap().get(poh_slot).cloned() {
assert_eq!( assert_eq!(
@ -253,7 +253,7 @@ impl ReplayStage {
); );
debug!( debug!(
"poh_recorder new working bank: me: {} next_slot: {} next_leader: {}", "poh_recorder new working bank: me: {} next_slot: {} next_leader: {}",
my_id, my_pubkey,
tpu_bank.slot(), tpu_bank.slot(),
next_leader next_leader
); );
@ -262,7 +262,7 @@ impl ReplayStage {
} }
}) })
.or_else(|| { .or_else(|| {
warn!("{} No next leader found", my_id); warn!("{} No next leader found", my_pubkey);
None None
}); });
} }
@ -345,7 +345,7 @@ impl ReplayStage {
} }
fn reset_poh_recorder( fn reset_poh_recorder(
my_id: &Pubkey, my_pubkey: &Pubkey,
blocktree: &Blocktree, blocktree: &Blocktree,
bank: &Arc<Bank>, bank: &Arc<Bank>,
poh_recorder: &Arc<Mutex<PohRecorder>>, poh_recorder: &Arc<Mutex<PohRecorder>>,
@ -353,7 +353,7 @@ impl ReplayStage {
leader_schedule_cache: &Arc<LeaderScheduleCache>, leader_schedule_cache: &Arc<LeaderScheduleCache>,
) { ) {
let next_leader_slot = let next_leader_slot =
leader_schedule_cache.next_leader_slot(&my_id, bank.slot(), &bank, Some(blocktree)); leader_schedule_cache.next_leader_slot(&my_pubkey, bank.slot(), &bank, Some(blocktree));
poh_recorder.lock().unwrap().reset( poh_recorder.lock().unwrap().reset(
bank.tick_height(), bank.tick_height(),
bank.last_blockhash(), bank.last_blockhash(),
@ -363,7 +363,7 @@ impl ReplayStage {
); );
debug!( debug!(
"{:?} voted and reset poh at {}. next leader slot {:?}", "{:?} voted and reset poh at {}. next leader slot {:?}",
my_id, my_pubkey,
bank.tick_height(), bank.tick_height(),
next_leader_slot next_leader_slot
); );
@ -372,7 +372,7 @@ impl ReplayStage {
fn replay_active_banks( fn replay_active_banks(
blocktree: &Arc<Blocktree>, blocktree: &Arc<Blocktree>,
bank_forks: &Arc<RwLock<BankForks>>, bank_forks: &Arc<RwLock<BankForks>>,
my_id: &Pubkey, my_pubkey: &Pubkey,
ticks_per_slot: &mut u64, ticks_per_slot: &mut u64,
progress: &mut HashMap<u64, ForkProgress>, progress: &mut HashMap<u64, ForkProgress>,
slot_full_sender: &Sender<(u64, Pubkey)>, slot_full_sender: &Sender<(u64, Pubkey)>,
@ -383,12 +383,12 @@ impl ReplayStage {
for bank_slot in &active_banks { for bank_slot in &active_banks {
let bank = bank_forks.read().unwrap().get(*bank_slot).unwrap().clone(); let bank = bank_forks.read().unwrap().get(*bank_slot).unwrap().clone();
*ticks_per_slot = bank.ticks_per_slot(); *ticks_per_slot = bank.ticks_per_slot();
if bank.collector_id() != *my_id { if bank.collector_id() != *my_pubkey {
Self::replay_blocktree_into_bank(&bank, &blocktree, progress)?; Self::replay_blocktree_into_bank(&bank, &blocktree, progress)?;
} }
let max_tick_height = (*bank_slot + 1) * bank.ticks_per_slot() - 1; let max_tick_height = (*bank_slot + 1) * bank.ticks_per_slot() - 1;
if bank.tick_height() == max_tick_height { if bank.tick_height() == max_tick_height {
Self::process_completed_bank(my_id, bank, slot_full_sender); Self::process_completed_bank(my_pubkey, bank, slot_full_sender);
} }
} }
Ok(()) Ok(())
@ -556,14 +556,14 @@ impl ReplayStage {
} }
fn process_completed_bank( fn process_completed_bank(
my_id: &Pubkey, my_pubkey: &Pubkey,
bank: Arc<Bank>, bank: Arc<Bank>,
slot_full_sender: &Sender<(u64, Pubkey)>, slot_full_sender: &Sender<(u64, Pubkey)>,
) { ) {
bank.freeze(); bank.freeze();
info!("bank frozen {}", bank.slot()); info!("bank frozen {}", bank.slot());
if let Err(e) = slot_full_sender.send((bank.slot(), bank.collector_id())) { if let Err(e) = slot_full_sender.send((bank.slot(), bank.collector_id())) {
trace!("{} slot_full alert failed: {:?}", my_id, e); trace!("{} slot_full alert failed: {:?}", my_pubkey, e);
} }
} }

View File

@ -496,8 +496,8 @@ impl Replicator {
let cluster_info = cluster_info.read().unwrap(); let cluster_info = cluster_info.read().unwrap();
let rpc_peers = cluster_info.rpc_peers(); let rpc_peers = cluster_info.rpc_peers();
debug!("rpc peers: {:?}", rpc_peers); debug!("rpc peers: {:?}", rpc_peers);
let node_idx = thread_rng().gen_range(0, rpc_peers.len()); let node_index = thread_rng().gen_range(0, rpc_peers.len());
RpcClient::new_socket(rpc_peers[node_idx].rpc) RpcClient::new_socket(rpc_peers[node_index].rpc)
}; };
let storage_blockhash = rpc_client let storage_blockhash = rpc_client
.retry_make_rpc_request(&RpcRequest::GetStorageBlockhash, None, 0) .retry_make_rpc_request(&RpcRequest::GetStorageBlockhash, None, 0)

View File

@ -548,7 +548,7 @@ mod tests {
#[test] #[test]
fn test_rpc_get_balance() { fn test_rpc_get_balance() {
let bob_pubkey = Pubkey::new_rand(); let bob_pubkey = Pubkey::new_rand();
let (io, meta, _blockhash, _alice, _leader_id) = start_rpc_handler_with_tx(&bob_pubkey); let (io, meta, _blockhash, _alice, _leader_pubkey) = start_rpc_handler_with_tx(&bob_pubkey);
let req = format!( let req = format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"getBalance","params":["{}"]}}"#, r#"{{"jsonrpc":"2.0","id":1,"method":"getBalance","params":["{}"]}}"#,
@ -566,7 +566,7 @@ mod tests {
#[test] #[test]
fn test_rpc_get_cluster_nodes() { fn test_rpc_get_cluster_nodes() {
let bob_pubkey = Pubkey::new_rand(); let bob_pubkey = Pubkey::new_rand();
let (io, meta, _blockhash, _alice, leader_id) = start_rpc_handler_with_tx(&bob_pubkey); let (io, meta, _blockhash, _alice, leader_pubkey) = start_rpc_handler_with_tx(&bob_pubkey);
let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getClusterNodes"}}"#); let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getClusterNodes"}}"#);
let res = io.handle_request_sync(&req, meta); let res = io.handle_request_sync(&req, meta);
@ -575,7 +575,7 @@ mod tests {
let expected = format!( let expected = format!(
r#"{{"jsonrpc":"2.0","result":[{{"id": "{}", "gossip": "127.0.0.1:1235", "tpu": "127.0.0.1:1234", "rpc": "127.0.0.1:8899"}}],"id":1}}"#, r#"{{"jsonrpc":"2.0","result":[{{"id": "{}", "gossip": "127.0.0.1:1235", "tpu": "127.0.0.1:1234", "rpc": "127.0.0.1:8899"}}],"id":1}}"#,
leader_id, leader_pubkey,
); );
let expected: Response = let expected: Response =
@ -586,7 +586,7 @@ mod tests {
#[test] #[test]
fn test_rpc_get_slot_leader() { fn test_rpc_get_slot_leader() {
let bob_pubkey = Pubkey::new_rand(); let bob_pubkey = Pubkey::new_rand();
let (io, meta, _blockhash, _alice, _leader_id) = start_rpc_handler_with_tx(&bob_pubkey); let (io, meta, _blockhash, _alice, _leader_pubkey) = start_rpc_handler_with_tx(&bob_pubkey);
let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getSlotLeader"}}"#); let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getSlotLeader"}}"#);
let res = io.handle_request_sync(&req, meta); let res = io.handle_request_sync(&req, meta);
@ -602,7 +602,7 @@ mod tests {
#[test] #[test]
fn test_rpc_get_tx_count() { fn test_rpc_get_tx_count() {
let bob_pubkey = Pubkey::new_rand(); let bob_pubkey = Pubkey::new_rand();
let (io, meta, _blockhash, _alice, _leader_id) = start_rpc_handler_with_tx(&bob_pubkey); let (io, meta, _blockhash, _alice, _leader_pubkey) = start_rpc_handler_with_tx(&bob_pubkey);
let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getTransactionCount"}}"#); let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getTransactionCount"}}"#);
let res = io.handle_request_sync(&req, meta); let res = io.handle_request_sync(&req, meta);
@ -617,7 +617,7 @@ mod tests {
#[test] #[test]
fn test_rpc_get_account_info() { fn test_rpc_get_account_info() {
let bob_pubkey = Pubkey::new_rand(); let bob_pubkey = Pubkey::new_rand();
let (io, meta, _blockhash, _alice, _leader_id) = start_rpc_handler_with_tx(&bob_pubkey); let (io, meta, _blockhash, _alice, _leader_pubkey) = start_rpc_handler_with_tx(&bob_pubkey);
let req = format!( let req = format!(
r#"{{"jsonrpc":"2.0","id":1,"method":"getAccountInfo","params":["{}"]}}"#, r#"{{"jsonrpc":"2.0","id":1,"method":"getAccountInfo","params":["{}"]}}"#,
@ -644,7 +644,7 @@ mod tests {
#[test] #[test]
fn test_rpc_confirm_tx() { fn test_rpc_confirm_tx() {
let bob_pubkey = Pubkey::new_rand(); let bob_pubkey = Pubkey::new_rand();
let (io, meta, blockhash, alice, _leader_id) = start_rpc_handler_with_tx(&bob_pubkey); let (io, meta, blockhash, alice, _leader_pubkey) = start_rpc_handler_with_tx(&bob_pubkey);
let tx = system_transaction::transfer(&alice, &bob_pubkey, 20, blockhash); let tx = system_transaction::transfer(&alice, &bob_pubkey, 20, blockhash);
let req = format!( let req = format!(
@ -663,7 +663,7 @@ mod tests {
#[test] #[test]
fn test_rpc_get_signature_status() { fn test_rpc_get_signature_status() {
let bob_pubkey = Pubkey::new_rand(); let bob_pubkey = Pubkey::new_rand();
let (io, meta, blockhash, alice, _leader_id) = start_rpc_handler_with_tx(&bob_pubkey); let (io, meta, blockhash, alice, _leader_pubkey) = start_rpc_handler_with_tx(&bob_pubkey);
let tx = system_transaction::transfer(&alice, &bob_pubkey, 20, blockhash); let tx = system_transaction::transfer(&alice, &bob_pubkey, 20, blockhash);
let req = format!( let req = format!(
@ -727,7 +727,7 @@ mod tests {
#[test] #[test]
fn test_rpc_get_recent_blockhash() { fn test_rpc_get_recent_blockhash() {
let bob_pubkey = Pubkey::new_rand(); let bob_pubkey = Pubkey::new_rand();
let (io, meta, blockhash, _alice, _leader_id) = start_rpc_handler_with_tx(&bob_pubkey); let (io, meta, blockhash, _alice, _leader_pubkey) = start_rpc_handler_with_tx(&bob_pubkey);
let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getRecentBlockhash"}}"#); let req = format!(r#"{{"jsonrpc":"2.0","id":1,"method":"getRecentBlockhash"}}"#);
let res = io.handle_request_sync(&req, meta); let res = io.handle_request_sync(&req, meta);
@ -745,7 +745,7 @@ mod tests {
#[test] #[test]
fn test_rpc_fail_request_airdrop() { fn test_rpc_fail_request_airdrop() {
let bob_pubkey = Pubkey::new_rand(); let bob_pubkey = Pubkey::new_rand();
let (io, meta, _blockhash, _alice, _leader_id) = start_rpc_handler_with_tx(&bob_pubkey); let (io, meta, _blockhash, _alice, _leader_pubkey) = start_rpc_handler_with_tx(&bob_pubkey);
// Expect internal error because no drone is available // Expect internal error because no drone is available
let req = format!( let req = format!(

View File

@ -50,7 +50,7 @@ pub fn staked_nodes_at_epoch(bank: &Bank, epoch_height: u64) -> Option<HashMap<P
.map(|vote_accounts| to_staked_nodes(to_vote_states(vote_accounts.into_iter()))) .map(|vote_accounts| to_staked_nodes(to_vote_states(vote_accounts.into_iter())))
} }
// input (vote_id, (stake, vote_account)) => (stake, vote_state) // input (vote_pubkey, (stake, vote_account)) => (stake, vote_state)
fn to_vote_states( fn to_vote_states(
node_staked_accounts: impl Iterator<Item = (impl Borrow<Pubkey>, impl Borrow<(u64, Account)>)>, node_staked_accounts: impl Iterator<Item = (impl Borrow<Pubkey>, impl Borrow<(u64, Account)>)>,
) -> impl Iterator<Item = (u64, VoteState)> { ) -> impl Iterator<Item = (u64, VoteState)> {
@ -67,7 +67,7 @@ fn to_staked_nodes(
) -> HashMap<Pubkey, u64> { ) -> HashMap<Pubkey, u64> {
let mut map: HashMap<Pubkey, u64> = HashMap::new(); let mut map: HashMap<Pubkey, u64> = HashMap::new();
node_staked_accounts.for_each(|(stake, state)| { node_staked_accounts.for_each(|(stake, state)| {
map.entry(state.node_id) map.entry(state.node_pubkey)
.and_modify(|s| *s += stake) .and_modify(|s| *s += stake)
.or_insert(stake); .or_insert(stake);
}); });
@ -158,8 +158,8 @@ pub(crate) mod tests {
pub(crate) fn setup_vote_and_stake_accounts( pub(crate) fn setup_vote_and_stake_accounts(
bank: &Bank, bank: &Bank,
from_account: &Keypair, from_account: &Keypair,
vote_id: &Pubkey, vote_pubkey: &Pubkey,
node_id: &Pubkey, node_pubkey: &Pubkey,
amount: u64, amount: u64,
) { ) {
fn process_instructions<T: KeypairUtil>( fn process_instructions<T: KeypairUtil>(
@ -178,7 +178,13 @@ pub(crate) mod tests {
process_instructions( process_instructions(
bank, bank,
&[from_account], &[from_account],
vote_instruction::create_account(&from_account.pubkey(), vote_id, node_id, 0, amount), vote_instruction::create_account(
&from_account.pubkey(),
vote_pubkey,
node_pubkey,
0,
amount,
),
); );
let stake_account_keypair = Keypair::new(); let stake_account_keypair = Keypair::new();
@ -200,7 +206,7 @@ pub(crate) mod tests {
vec![stake_instruction::delegate_stake( vec![stake_instruction::delegate_stake(
&from_account.pubkey(), &from_account.pubkey(),
&stake_account_pubkey, &stake_account_pubkey,
vote_id, vote_pubkey,
)], )],
); );
} }
@ -217,7 +223,7 @@ pub(crate) mod tests {
} = create_genesis_block(10_000); } = create_genesis_block(10_000);
let bank = Bank::new(&genesis_block); let bank = Bank::new(&genesis_block);
let vote_id = Pubkey::new_rand(); let vote_pubkey = Pubkey::new_rand();
// Give the validator some stake but don't setup a staking account // Give the validator some stake but don't setup a staking account
// Validator has no lamports staked, so they get filtered out. Only the bootstrap leader // Validator has no lamports staked, so they get filtered out. Only the bootstrap leader
@ -230,7 +236,7 @@ pub(crate) mod tests {
setup_vote_and_stake_accounts( setup_vote_and_stake_accounts(
&bank, &bank,
&mint_keypair, &mint_keypair,
&vote_id, &vote_pubkey,
&mint_keypair.pubkey(), &mint_keypair.pubkey(),
stake, stake,
); );

View File

@ -80,20 +80,20 @@ pub fn should_retransmit_and_persist(
blob: &Blob, blob: &Blob,
bank: Option<Arc<Bank>>, bank: Option<Arc<Bank>>,
leader_schedule_cache: &Arc<LeaderScheduleCache>, leader_schedule_cache: &Arc<LeaderScheduleCache>,
my_id: &Pubkey, my_pubkey: &Pubkey,
) -> bool { ) -> bool {
let slot_leader_id = match bank { let slot_leader_pubkey = match bank {
None => leader_schedule_cache.slot_leader_at(blob.slot(), None), None => leader_schedule_cache.slot_leader_at(blob.slot(), None),
Some(bank) => leader_schedule_cache.slot_leader_at(blob.slot(), Some(&bank)), Some(bank) => leader_schedule_cache.slot_leader_at(blob.slot(), Some(&bank)),
}; };
if blob.id() == *my_id { if blob.id() == *my_pubkey {
inc_new_counter_debug!("streamer-recv_window-circular_transmission", 1); inc_new_counter_debug!("streamer-recv_window-circular_transmission", 1);
false false
} else if slot_leader_id == None { } else if slot_leader_pubkey == None {
inc_new_counter_debug!("streamer-recv_window-unknown_leader", 1); inc_new_counter_debug!("streamer-recv_window-unknown_leader", 1);
true true
} else if slot_leader_id != Some(blob.id()) { } else if slot_leader_pubkey != Some(blob.id()) {
inc_new_counter_debug!("streamer-recv_window-wrong_leader", 1); inc_new_counter_debug!("streamer-recv_window-wrong_leader", 1);
false false
} else { } else {
@ -103,7 +103,7 @@ pub fn should_retransmit_and_persist(
fn recv_window<F>( fn recv_window<F>(
blocktree: &Arc<Blocktree>, blocktree: &Arc<Blocktree>,
my_id: &Pubkey, my_pubkey: &Pubkey,
r: &BlobReceiver, r: &BlobReceiver,
retransmit: &BlobSender, retransmit: &BlobSender,
genesis_blockhash: &Hash, genesis_blockhash: &Hash,
@ -126,9 +126,9 @@ where
&& blob.read().unwrap().genesis_blockhash() == *genesis_blockhash && blob.read().unwrap().genesis_blockhash() == *genesis_blockhash
}); });
retransmit_blobs(&blobs, retransmit, my_id)?; retransmit_blobs(&blobs, retransmit, my_pubkey)?;
trace!("{} num blobs received: {}", my_id, blobs.len()); trace!("{} num blobs received: {}", my_pubkey, blobs.len());
process_blobs(&blobs, blocktree)?; process_blobs(&blobs, blocktree)?;
@ -294,14 +294,14 @@ mod test {
#[test] #[test]
fn test_should_retransmit_and_persist() { fn test_should_retransmit_and_persist() {
let me_id = Pubkey::new_rand(); let me_id = Pubkey::new_rand();
let leader_id = Pubkey::new_rand(); let leader_pubkey = Pubkey::new_rand();
let bank = Arc::new(Bank::new( let bank = Arc::new(Bank::new(
&create_genesis_block_with_leader(100, &leader_id, 10).genesis_block, &create_genesis_block_with_leader(100, &leader_pubkey, 10).genesis_block,
)); ));
let cache = Arc::new(LeaderScheduleCache::new_from_bank(&bank)); let cache = Arc::new(LeaderScheduleCache::new_from_bank(&bank));
let mut blob = Blob::default(); let mut blob = Blob::default();
blob.set_id(&leader_id); blob.set_id(&leader_pubkey);
// without a Bank and blobs not from me, blob continues // without a Bank and blobs not from me, blob continues
assert_eq!( assert_eq!(

View File

@ -134,8 +134,8 @@ fn test_two_unbalanced_stakes() {
num_slots_per_epoch, num_slots_per_epoch,
); );
cluster.close_preserve_ledgers(); cluster.close_preserve_ledgers();
let leader_id = cluster.entry_point_info.id; let leader_pubkey = cluster.entry_point_info.id;
let leader_ledger = cluster.fullnode_infos[&leader_id].ledger_path.clone(); let leader_ledger = cluster.fullnode_infos[&leader_pubkey].ledger_path.clone();
cluster_tests::verify_ledger_ticks(&leader_ledger, num_ticks_per_slot as usize); cluster_tests::verify_ledger_ticks(&leader_ledger, num_ticks_per_slot as usize);
} }
@ -154,9 +154,12 @@ fn test_forwarding() {
let (cluster_nodes, _) = discover_cluster(&cluster.entry_point_info.gossip, 2).unwrap(); let (cluster_nodes, _) = discover_cluster(&cluster.entry_point_info.gossip, 2).unwrap();
assert!(cluster_nodes.len() >= 2); assert!(cluster_nodes.len() >= 2);
let leader_id = cluster.entry_point_info.id; let leader_pubkey = cluster.entry_point_info.id;
let validator_info = cluster_nodes.iter().find(|c| c.id != leader_id).unwrap(); let validator_info = cluster_nodes
.iter()
.find(|c| c.id != leader_pubkey)
.unwrap();
// Confirm that transactions were forwarded to and processed by the leader. // Confirm that transactions were forwarded to and processed by the leader.
cluster_tests::send_many_transactions(&validator_info, &cluster.funding_keypair, 20); cluster_tests::send_many_transactions(&validator_info, &cluster.funding_keypair, 20);
@ -175,7 +178,7 @@ fn test_restart_node() {
slots_per_epoch, slots_per_epoch,
..ClusterConfig::default() ..ClusterConfig::default()
}); });
let nodes = cluster.get_node_ids(); let nodes = cluster.get_node_pubkeys();
cluster_tests::sleep_n_epochs( cluster_tests::sleep_n_epochs(
1.0, 1.0,
&cluster.genesis_block.poh_config, &cluster.genesis_block.poh_config,

View File

@ -241,7 +241,7 @@ fn test_account_setup() {
cluster.replicator_infos.iter().for_each(|(_, value)| { cluster.replicator_infos.iter().for_each(|(_, value)| {
assert_eq!( assert_eq!(
client client
.poll_get_balance(&value.replicator_storage_id) .poll_get_balance(&value.replicator_storage_pubkey)
.unwrap(), .unwrap(),
1 1
); );

View File

@ -76,7 +76,7 @@ mod bpf {
let bank = Bank::new(&genesis_block); let bank = Bank::new(&genesis_block);
let bank_client = BankClient::new(bank); let bank_client = BankClient::new(bank);
let loader_id = load_program( let loader_pubkey = load_program(
&bank_client, &bank_client,
&alice_keypair, &alice_keypair,
&native_loader::id(), &native_loader::id(),
@ -84,7 +84,7 @@ mod bpf {
); );
// Call user program // Call user program
let program_id = load_program(&bank_client, &alice_keypair, &loader_id, elf); let program_id = load_program(&bank_client, &alice_keypair, &loader_pubkey, elf);
let instruction = let instruction =
create_invoke_instruction(alice_keypair.pubkey(), program_id, &1u8); create_invoke_instruction(alice_keypair.pubkey(), program_id, &1u8);
bank_client bank_client
@ -121,7 +121,7 @@ mod bpf {
let bank = Bank::new(&genesis_block); let bank = Bank::new(&genesis_block);
let bank_client = BankClient::new(bank); let bank_client = BankClient::new(bank);
let loader_id = load_program( let loader_pubkey = load_program(
&bank_client, &bank_client,
&alice_keypair, &alice_keypair,
&native_loader::id(), &native_loader::id(),
@ -129,7 +129,7 @@ mod bpf {
); );
// Call user program // Call user program
let program_id = load_program(&bank_client, &alice_keypair, &loader_id, elf); let program_id = load_program(&bank_client, &alice_keypair, &loader_pubkey, elf);
let account_metas = vec![ let account_metas = vec![
AccountMeta::new(alice_keypair.pubkey(), true), AccountMeta::new(alice_keypair.pubkey(), true),
AccountMeta::new(Keypair::new().pubkey(), false), AccountMeta::new(Keypair::new().pubkey(), false),

View File

@ -43,14 +43,14 @@ pub enum StakeInstruction {
} }
pub fn create_delegate_account( pub fn create_delegate_account(
from_id: &Pubkey, from_pubkey: &Pubkey,
staker_id: &Pubkey, staker_pubkey: &Pubkey,
lamports: u64, lamports: u64,
) -> Vec<Instruction> { ) -> Vec<Instruction> {
vec![ vec![
system_instruction::create_account( system_instruction::create_account(
from_id, from_pubkey,
staker_id, staker_pubkey,
lamports, lamports,
std::mem::size_of::<StakeState>() as u64, std::mem::size_of::<StakeState>() as u64,
&id(), &id(),
@ -59,22 +59,22 @@ pub fn create_delegate_account(
id(), id(),
&StakeInstruction::InitializeDelegate, &StakeInstruction::InitializeDelegate,
vec![ vec![
AccountMeta::new(*from_id, true), AccountMeta::new(*from_pubkey, true),
AccountMeta::new(*staker_id, false), AccountMeta::new(*staker_pubkey, false),
], ],
), ),
] ]
} }
pub fn create_mining_pool_account( pub fn create_mining_pool_account(
from_id: &Pubkey, from_pubkey: &Pubkey,
staker_id: &Pubkey, staker_pubkey: &Pubkey,
lamports: u64, lamports: u64,
) -> Vec<Instruction> { ) -> Vec<Instruction> {
vec![ vec![
system_instruction::create_account( system_instruction::create_account(
from_id, from_pubkey,
staker_id, staker_pubkey,
lamports, lamports,
std::mem::size_of::<StakeState>() as u64, std::mem::size_of::<StakeState>() as u64,
&id(), &id(),
@ -83,33 +83,37 @@ pub fn create_mining_pool_account(
id(), id(),
&StakeInstruction::InitializeMiningPool, &StakeInstruction::InitializeMiningPool,
vec![ vec![
AccountMeta::new(*from_id, true), AccountMeta::new(*from_pubkey, true),
AccountMeta::new(*staker_id, false), AccountMeta::new(*staker_pubkey, false),
], ],
), ),
] ]
} }
pub fn redeem_vote_credits( pub fn redeem_vote_credits(
from_id: &Pubkey, from_pubkey: &Pubkey,
mining_pool_id: &Pubkey, mining_pool_pubkey: &Pubkey,
stake_id: &Pubkey, stake_pubkey: &Pubkey,
vote_id: &Pubkey, vote_pubkey: &Pubkey,
) -> Instruction { ) -> Instruction {
let account_metas = vec![ let account_metas = vec![
AccountMeta::new(*from_id, true), AccountMeta::new(*from_pubkey, true),
AccountMeta::new(*mining_pool_id, false), AccountMeta::new(*mining_pool_pubkey, false),
AccountMeta::new(*stake_id, false), AccountMeta::new(*stake_pubkey, false),
AccountMeta::new(*vote_id, false), AccountMeta::new(*vote_pubkey, false),
]; ];
Instruction::new(id(), &StakeInstruction::RedeemVoteCredits, account_metas) Instruction::new(id(), &StakeInstruction::RedeemVoteCredits, account_metas)
} }
pub fn delegate_stake(from_id: &Pubkey, stake_id: &Pubkey, vote_id: &Pubkey) -> Instruction { pub fn delegate_stake(
from_pubkey: &Pubkey,
stake_pubkey: &Pubkey,
vote_pubkey: &Pubkey,
) -> Instruction {
let account_metas = vec![ let account_metas = vec![
AccountMeta::new(*from_id, true), AccountMeta::new(*from_pubkey, true),
AccountMeta::new(*stake_id, true), AccountMeta::new(*stake_pubkey, true),
AccountMeta::new(*vote_id, false), AccountMeta::new(*vote_pubkey, false),
]; ];
Instruction::new(id(), &StakeInstruction::DelegateStake, account_metas) Instruction::new(id(), &StakeInstruction::DelegateStake, account_metas)
} }

View File

@ -15,7 +15,7 @@ use solana_vote_api::vote_state::VoteState;
pub enum StakeState { pub enum StakeState {
Uninitialized, Uninitialized,
Delegate { Delegate {
voter_id: Pubkey, voter_pubkey: Pubkey,
credits_observed: u64, credits_observed: u64,
}, },
MiningPool, MiningPool,
@ -46,13 +46,13 @@ impl StakeState {
} }
// utility function, used by Stakes, tests // utility function, used by Stakes, tests
pub fn voter_id_from(account: &Account) -> Option<Pubkey> { pub fn voter_pubkey_from(account: &Account) -> Option<Pubkey> {
Self::from(account).and_then(|state: Self| state.voter_id()) Self::from(account).and_then(|state: Self| state.voter_pubkey())
} }
pub fn voter_id(&self) -> Option<Pubkey> { pub fn voter_pubkey(&self) -> Option<Pubkey> {
match self { match self {
StakeState::Delegate { voter_id, .. } => Some(*voter_id), StakeState::Delegate { voter_pubkey, .. } => Some(*voter_pubkey),
_ => None, _ => None,
} }
} }
@ -109,7 +109,7 @@ impl<'a> StakeAccount for KeyedAccount<'a> {
fn initialize_delegate(&mut self) -> Result<(), InstructionError> { fn initialize_delegate(&mut self) -> Result<(), InstructionError> {
if let StakeState::Uninitialized = self.state()? { if let StakeState::Uninitialized = self.state()? {
self.set_state(&StakeState::Delegate { self.set_state(&StakeState::Delegate {
voter_id: Pubkey::default(), voter_pubkey: Pubkey::default(),
credits_observed: 0, credits_observed: 0,
}) })
} else { } else {
@ -124,7 +124,7 @@ impl<'a> StakeAccount for KeyedAccount<'a> {
if let StakeState::Delegate { .. } = self.state()? { if let StakeState::Delegate { .. } = self.state()? {
let vote_state: VoteState = vote_account.state()?; let vote_state: VoteState = vote_account.state()?;
self.set_state(&StakeState::Delegate { self.set_state(&StakeState::Delegate {
voter_id: *vote_account.unsigned_key(), voter_pubkey: *vote_account.unsigned_key(),
credits_observed: vote_state.credits(), credits_observed: vote_state.credits(),
}) })
} else { } else {
@ -140,14 +140,14 @@ impl<'a> StakeAccount for KeyedAccount<'a> {
if let ( if let (
StakeState::MiningPool, StakeState::MiningPool,
StakeState::Delegate { StakeState::Delegate {
voter_id, voter_pubkey,
credits_observed, credits_observed,
}, },
) = (self.state()?, stake_account.state()?) ) = (self.state()?, stake_account.state()?)
{ {
let vote_state: VoteState = vote_account.state()?; let vote_state: VoteState = vote_account.state()?;
if voter_id != *vote_account.unsigned_key() { if voter_pubkey != *vote_account.unsigned_key() {
return Err(InstructionError::InvalidArgument); return Err(InstructionError::InvalidArgument);
} }
@ -168,7 +168,7 @@ impl<'a> StakeAccount for KeyedAccount<'a> {
vote_account.account.lamports += voters_reward; vote_account.account.lamports += voters_reward;
stake_account.set_state(&StakeState::Delegate { stake_account.set_state(&StakeState::Delegate {
voter_id, voter_pubkey,
credits_observed: vote_state.credits(), credits_observed: vote_state.credits(),
}) })
} else { } else {
@ -183,7 +183,7 @@ impl<'a> StakeAccount for KeyedAccount<'a> {
// utility function, used by Bank, tests, genesis // utility function, used by Bank, tests, genesis
pub fn create_delegate_stake_account( pub fn create_delegate_stake_account(
voter_id: &Pubkey, voter_pubkey: &Pubkey,
vote_state: &VoteState, vote_state: &VoteState,
lamports: u64, lamports: u64,
) -> Account { ) -> Account {
@ -191,7 +191,7 @@ pub fn create_delegate_stake_account(
stake_account stake_account
.set_state(&StakeState::Delegate { .set_state(&StakeState::Delegate {
voter_id: *voter_id, voter_pubkey: *voter_pubkey,
credits_observed: vote_state.credits(), credits_observed: vote_state.credits(),
}) })
.expect("set_state"); .expect("set_state");
@ -254,7 +254,7 @@ mod tests {
assert_eq!( assert_eq!(
stake_state, stake_state,
StakeState::Delegate { StakeState::Delegate {
voter_id: vote_keypair.pubkey(), voter_pubkey: vote_keypair.pubkey(),
credits_observed: vote_state.credits() credits_observed: vote_state.credits()
} }
); );
@ -438,7 +438,7 @@ mod tests {
let mut vote1_keyed_account = KeyedAccount::new(&vote1_pubkey, false, &mut vote1_account); let mut vote1_keyed_account = KeyedAccount::new(&vote1_pubkey, false, &mut vote1_account);
vote1_keyed_account.set_state(&vote_state).unwrap(); vote1_keyed_account.set_state(&vote_state).unwrap();
// wrong voter_id... // wrong voter_pubkey...
assert_eq!( assert_eq!(
mining_pool_keyed_account mining_pool_keyed_account
.redeem_vote_credits(&mut stake_keyed_account, &mut vote1_keyed_account), .redeem_vote_credits(&mut stake_keyed_account, &mut vote1_keyed_account),

View File

@ -16,7 +16,7 @@ use solana_sdk::system_instruction;
#[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)] #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Clone)]
pub enum VoteInstruction { pub enum VoteInstruction {
/// Initialize the VoteState for this `vote account` /// Initialize the VoteState for this `vote account`
/// takes a node_id and commission /// takes a node_pubkey and commission
InitializeAccount(Pubkey, u32), InitializeAccount(Pubkey, u32),
/// Authorize a voter to send signed votes. /// Authorize a voter to send signed votes.
@ -27,76 +27,79 @@ pub enum VoteInstruction {
} }
fn initialize_account( fn initialize_account(
from_id: &Pubkey, from_pubkey: &Pubkey,
vote_id: &Pubkey, vote_pubkey: &Pubkey,
node_id: &Pubkey, node_pubkey: &Pubkey,
commission: u32, commission: u32,
) -> Instruction { ) -> Instruction {
let account_metas = vec![ let account_metas = vec![
AccountMeta::new(*from_id, true), AccountMeta::new(*from_pubkey, true),
AccountMeta::new(*vote_id, false), AccountMeta::new(*vote_pubkey, false),
]; ];
Instruction::new( Instruction::new(
id(), id(),
&VoteInstruction::InitializeAccount(*node_id, commission), &VoteInstruction::InitializeAccount(*node_pubkey, commission),
account_metas, account_metas,
) )
} }
pub fn create_account( pub fn create_account(
from_id: &Pubkey, from_pubkey: &Pubkey,
vote_id: &Pubkey, vote_pubkey: &Pubkey,
node_id: &Pubkey, node_pubkey: &Pubkey,
commission: u32, commission: u32,
lamports: u64, lamports: u64,
) -> Vec<Instruction> { ) -> Vec<Instruction> {
let space = VoteState::size_of() as u64; let space = VoteState::size_of() as u64;
let create_ix = system_instruction::create_account(from_id, vote_id, lamports, space, &id()); let create_ix =
let init_ix = initialize_account(from_id, vote_id, node_id, commission); system_instruction::create_account(from_pubkey, vote_pubkey, lamports, space, &id());
let init_ix = initialize_account(from_pubkey, vote_pubkey, node_pubkey, commission);
vec![create_ix, init_ix] vec![create_ix, init_ix]
} }
fn metas_for_authorized_signer( fn metas_for_authorized_signer(
from_id: &Pubkey, from_pubkey: &Pubkey,
vote_id: &Pubkey, vote_pubkey: &Pubkey,
authorized_voter_id: &Pubkey, // currently authorized authorized_voter_pubkey: &Pubkey, // currently authorized
) -> Vec<AccountMeta> { ) -> Vec<AccountMeta> {
let mut account_metas = vec![AccountMeta::new(*from_id, true)]; // sender let mut account_metas = vec![AccountMeta::new(*from_pubkey, true)]; // sender
let is_own_signer = authorized_voter_id == vote_id; let is_own_signer = authorized_voter_pubkey == vote_pubkey;
account_metas.push(AccountMeta::new(*vote_id, is_own_signer)); // vote account account_metas.push(AccountMeta::new(*vote_pubkey, is_own_signer)); // vote account
if !is_own_signer { if !is_own_signer {
account_metas.push(AccountMeta::new(*authorized_voter_id, true)) // signer account_metas.push(AccountMeta::new(*authorized_voter_pubkey, true)) // signer
} }
account_metas account_metas
} }
pub fn authorize_voter( pub fn authorize_voter(
from_id: &Pubkey, from_pubkey: &Pubkey,
vote_id: &Pubkey, vote_pubkey: &Pubkey,
authorized_voter_id: &Pubkey, // currently authorized authorized_voter_pubkey: &Pubkey, // currently authorized
new_authorized_voter_id: &Pubkey, new_authorized_voter_pubkey: &Pubkey,
) -> Instruction { ) -> Instruction {
let account_metas = metas_for_authorized_signer(from_id, vote_id, authorized_voter_id); let account_metas =
metas_for_authorized_signer(from_pubkey, vote_pubkey, authorized_voter_pubkey);
Instruction::new( Instruction::new(
id(), id(),
&VoteInstruction::AuthorizeVoter(*new_authorized_voter_id), &VoteInstruction::AuthorizeVoter(*new_authorized_voter_pubkey),
account_metas, account_metas,
) )
} }
pub fn vote( pub fn vote(
from_id: &Pubkey, from_pubkey: &Pubkey,
vote_id: &Pubkey, vote_pubkey: &Pubkey,
authorized_voter_id: &Pubkey, authorized_voter_pubkey: &Pubkey,
recent_votes: Vec<Vote>, recent_votes: Vec<Vote>,
) -> Instruction { ) -> Instruction {
let mut account_metas = metas_for_authorized_signer(from_id, vote_id, authorized_voter_id); let mut account_metas =
metas_for_authorized_signer(from_pubkey, vote_pubkey, authorized_voter_pubkey);
// request slot_hashes syscall account after vote_id // request slot_hashes syscall account after vote_pubkey
account_metas.insert(2, AccountMeta::new(slot_hashes::id(), false)); account_metas.insert(2, AccountMeta::new(slot_hashes::id(), false));
Instruction::new(id(), &VoteInstruction::Vote(recent_votes), account_metas) Instruction::new(id(), &VoteInstruction::Vote(recent_votes), account_metas)
@ -123,11 +126,11 @@ pub fn process_instruction(
// TODO: data-driven unpack and dispatch of KeyedAccounts // TODO: data-driven unpack and dispatch of KeyedAccounts
match deserialize(data).map_err(|_| InstructionError::InvalidInstructionData)? { match deserialize(data).map_err(|_| InstructionError::InvalidInstructionData)? {
VoteInstruction::InitializeAccount(node_id, commission) => { VoteInstruction::InitializeAccount(node_pubkey, commission) => {
vote_state::initialize_account(me, &node_id, commission) vote_state::initialize_account(me, &node_pubkey, commission)
} }
VoteInstruction::AuthorizeVoter(voter_id) => { VoteInstruction::AuthorizeVoter(voter_pubkey) => {
vote_state::authorize_voter(me, rest, &voter_id) vote_state::authorize_voter(me, rest, &voter_pubkey)
} }
VoteInstruction::Vote(votes) => { VoteInstruction::Vote(votes) => {
datapoint_warn!("vote-native", ("count", 1, i64)); datapoint_warn!("vote-native", ("count", 1, i64));

View File

@ -62,8 +62,8 @@ impl Lockout {
#[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq, Clone)] #[derive(Debug, Default, Serialize, Deserialize, PartialEq, Eq, Clone)]
pub struct VoteState { pub struct VoteState {
pub votes: VecDeque<Lockout>, pub votes: VecDeque<Lockout>,
pub node_id: Pubkey, pub node_pubkey: Pubkey,
pub authorized_voter_id: Pubkey, pub authorized_voter_pubkey: Pubkey,
/// fraction of std::u32::MAX that represents what part of a rewards /// fraction of std::u32::MAX that represents what part of a rewards
/// payout should be given to this VoteAccount /// payout should be given to this VoteAccount
pub commission: u32, pub commission: u32,
@ -72,14 +72,14 @@ pub struct VoteState {
} }
impl VoteState { impl VoteState {
pub fn new(vote_id: &Pubkey, node_id: &Pubkey, commission: u32) -> Self { pub fn new(vote_pubkey: &Pubkey, node_pubkey: &Pubkey, commission: u32) -> Self {
let votes = VecDeque::new(); let votes = VecDeque::new();
let credits = 0; let credits = 0;
let root_slot = None; let root_slot = None;
Self { Self {
votes, votes,
node_id: *node_id, node_pubkey: *node_pubkey,
authorized_voter_id: *vote_id, authorized_voter_pubkey: *vote_pubkey,
credits, credits,
commission, commission,
root_slot, root_slot,
@ -218,12 +218,12 @@ impl VoteState {
pub fn authorize_voter( pub fn authorize_voter(
vote_account: &mut KeyedAccount, vote_account: &mut KeyedAccount,
other_signers: &[KeyedAccount], other_signers: &[KeyedAccount],
authorized_voter_id: &Pubkey, authorized_voter_pubkey: &Pubkey,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let mut vote_state: VoteState = vote_account.state()?; let mut vote_state: VoteState = vote_account.state()?;
// current authorized signer must say "yay" // current authorized signer must say "yay"
let authorized = Some(&vote_state.authorized_voter_id); let authorized = Some(&vote_state.authorized_voter_pubkey);
if vote_account.signer_key() != authorized if vote_account.signer_key() != authorized
&& other_signers && other_signers
.iter() .iter()
@ -232,7 +232,7 @@ pub fn authorize_voter(
return Err(InstructionError::MissingRequiredSignature); return Err(InstructionError::MissingRequiredSignature);
} }
vote_state.authorized_voter_id = *authorized_voter_id; vote_state.authorized_voter_pubkey = *authorized_voter_pubkey;
vote_account.set_state(&vote_state) vote_account.set_state(&vote_state)
} }
@ -241,17 +241,17 @@ pub fn authorize_voter(
/// that the transaction must be signed by the staker's keys /// that the transaction must be signed by the staker's keys
pub fn initialize_account( pub fn initialize_account(
vote_account: &mut KeyedAccount, vote_account: &mut KeyedAccount,
node_id: &Pubkey, node_pubkey: &Pubkey,
commission: u32, commission: u32,
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let vote_state: VoteState = vote_account.state()?; let vote_state: VoteState = vote_account.state()?;
if vote_state.authorized_voter_id != Pubkey::default() { if vote_state.authorized_voter_pubkey != Pubkey::default() {
return Err(InstructionError::AccountAlreadyInitialized); return Err(InstructionError::AccountAlreadyInitialized);
} }
vote_account.set_state(&VoteState::new( vote_account.set_state(&VoteState::new(
vote_account.unsigned_key(), vote_account.unsigned_key(),
node_id, node_pubkey,
commission, commission,
)) ))
} }
@ -264,7 +264,7 @@ pub fn process_votes(
) -> Result<(), InstructionError> { ) -> Result<(), InstructionError> {
let mut vote_state: VoteState = vote_account.state()?; let mut vote_state: VoteState = vote_account.state()?;
if vote_state.authorized_voter_id == Pubkey::default() { if vote_state.authorized_voter_pubkey == Pubkey::default() {
return Err(InstructionError::UninitializedAccount); return Err(InstructionError::UninitializedAccount);
} }
@ -274,8 +274,8 @@ pub fn process_votes(
let slot_hashes: Vec<(u64, Hash)> = slot_hashes_account.state()?; let slot_hashes: Vec<(u64, Hash)> = slot_hashes_account.state()?;
let authorized = Some(&vote_state.authorized_voter_id); let authorized = Some(&vote_state.authorized_voter_pubkey);
// find a signer that matches the authorized_voter_id // find a signer that matches the authorized_voter_pubkey
if vote_account.signer_key() != authorized if vote_account.signer_key() != authorized
&& other_signers && other_signers
.iter() .iter()
@ -290,16 +290,16 @@ pub fn process_votes(
// utility function, used by Bank, tests // utility function, used by Bank, tests
pub fn create_account( pub fn create_account(
vote_id: &Pubkey, vote_pubkey: &Pubkey,
node_id: &Pubkey, node_pubkey: &Pubkey,
commission: u32, commission: u32,
lamports: u64, lamports: u64,
) -> Account { ) -> Account {
let mut vote_account = Account::new(lamports, VoteState::size_of(), &id()); let mut vote_account = Account::new(lamports, VoteState::size_of(), &id());
initialize_account( initialize_account(
&mut KeyedAccount::new(vote_id, false, &mut vote_account), &mut KeyedAccount::new(vote_pubkey, false, &mut vote_account),
node_id, node_pubkey,
commission, commission,
) )
.unwrap(); .unwrap();
@ -308,14 +308,14 @@ pub fn create_account(
// utility function, used by solana-genesis, tests // utility function, used by solana-genesis, tests
pub fn create_bootstrap_leader_account( pub fn create_bootstrap_leader_account(
vote_id: &Pubkey, vote_pubkey: &Pubkey,
node_id: &Pubkey, node_pubkey: &Pubkey,
commission: u32, commission: u32,
lamports: u64, lamports: u64,
) -> (Account, VoteState) { ) -> (Account, VoteState) {
// Construct a vote account for the bootstrap_leader such that the leader_scheduler // Construct a vote account for the bootstrap_leader such that the leader_scheduler
// will be forced to select it as the leader for height 0 // will be forced to select it as the leader for height 0
let mut vote_account = create_account(&vote_id, &node_id, commission, lamports); let mut vote_account = create_account(&vote_pubkey, &node_pubkey, commission, lamports);
let mut vote_state: VoteState = vote_account.state().unwrap(); let mut vote_state: VoteState = vote_account.state().unwrap();
// TODO: get a hash for slot 0? // TODO: get a hash for slot 0?
@ -340,26 +340,26 @@ mod tests {
#[test] #[test]
fn test_initialize_vote_account() { fn test_initialize_vote_account() {
let vote_account_id = Pubkey::new_rand(); let vote_account_pubkey = Pubkey::new_rand();
let mut vote_account = Account::new(100, VoteState::size_of(), &id()); let mut vote_account = Account::new(100, VoteState::size_of(), &id());
let node_id = Pubkey::new_rand(); let node_pubkey = Pubkey::new_rand();
//init should pass //init should pass
let mut vote_account = KeyedAccount::new(&vote_account_id, false, &mut vote_account); let mut vote_account = KeyedAccount::new(&vote_account_pubkey, false, &mut vote_account);
let res = initialize_account(&mut vote_account, &node_id, 0); let res = initialize_account(&mut vote_account, &node_pubkey, 0);
assert_eq!(res, Ok(())); assert_eq!(res, Ok(()));
// reinit should fail // reinit should fail
let res = initialize_account(&mut vote_account, &node_id, 0); let res = initialize_account(&mut vote_account, &node_pubkey, 0);
assert_eq!(res, Err(InstructionError::AccountAlreadyInitialized)); assert_eq!(res, Err(InstructionError::AccountAlreadyInitialized));
} }
fn create_test_account() -> (Pubkey, Account) { fn create_test_account() -> (Pubkey, Account) {
let vote_id = Pubkey::new_rand(); let vote_pubkey = Pubkey::new_rand();
( (
vote_id, vote_pubkey,
vote_state::create_account(&vote_id, &Pubkey::new_rand(), 0, 100), vote_state::create_account(&vote_pubkey, &Pubkey::new_rand(), 0, 100),
) )
} }
@ -376,7 +376,7 @@ mod tests {
} }
fn simulate_process_vote( fn simulate_process_vote(
vote_id: &Pubkey, vote_pubkey: &Pubkey,
vote_account: &mut Account, vote_account: &mut Account,
vote: &Vote, vote: &Vote,
slot_hashes: &[(u64, Hash)], slot_hashes: &[(u64, Hash)],
@ -385,7 +385,7 @@ mod tests {
create_test_slot_hashes_account(slot_hashes); create_test_slot_hashes_account(slot_hashes);
process_votes( process_votes(
&mut KeyedAccount::new(vote_id, true, vote_account), &mut KeyedAccount::new(vote_pubkey, true, vote_account),
&mut KeyedAccount::new(&slot_hashes_id, false, &mut slot_hashes_account), &mut KeyedAccount::new(&slot_hashes_id, false, &mut slot_hashes_account),
&[], &[],
&[vote.clone()], &[vote.clone()],
@ -395,18 +395,18 @@ mod tests {
/// exercises all the keyed accounts stuff /// exercises all the keyed accounts stuff
fn simulate_process_vote_unchecked( fn simulate_process_vote_unchecked(
vote_id: &Pubkey, vote_pubkey: &Pubkey,
vote_account: &mut Account, vote_account: &mut Account,
vote: &Vote, vote: &Vote,
) -> Result<VoteState, InstructionError> { ) -> Result<VoteState, InstructionError> {
simulate_process_vote(vote_id, vote_account, vote, &[(vote.slot, vote.hash)]) simulate_process_vote(vote_pubkey, vote_account, vote, &[(vote.slot, vote.hash)])
} }
#[test] #[test]
fn test_vote_create_bootstrap_leader_account() { fn test_vote_create_bootstrap_leader_account() {
let vote_id = Pubkey::new_rand(); let vote_pubkey = Pubkey::new_rand();
let (_vote_account, vote_state) = let (_vote_account, vote_state) =
vote_state::create_bootstrap_leader_account(&vote_id, &Pubkey::new_rand(), 0, 100); vote_state::create_bootstrap_leader_account(&vote_pubkey, &Pubkey::new_rand(), 0, 100);
assert_eq!(vote_state.votes.len(), 1); assert_eq!(vote_state.votes.len(), 1);
assert_eq!(vote_state.votes[0], Lockout::new(&Vote::default())); assert_eq!(vote_state.votes[0], Lockout::new(&Vote::default()));
@ -426,44 +426,49 @@ mod tests {
#[test] #[test]
fn test_voter_registration() { fn test_voter_registration() {
let (vote_id, vote_account) = create_test_account(); let (vote_pubkey, vote_account) = create_test_account();
let vote_state: VoteState = vote_account.state().unwrap(); let vote_state: VoteState = vote_account.state().unwrap();
assert_eq!(vote_state.authorized_voter_id, vote_id); assert_eq!(vote_state.authorized_voter_pubkey, vote_pubkey);
assert!(vote_state.votes.is_empty()); assert!(vote_state.votes.is_empty());
} }
#[test] #[test]
fn test_vote() { fn test_vote() {
let (vote_id, mut vote_account) = create_test_account(); let (vote_pubkey, mut vote_account) = create_test_account();
let vote = Vote::new(1, Hash::default()); let vote = Vote::new(1, Hash::default());
let vote_state = let vote_state =
simulate_process_vote_unchecked(&vote_id, &mut vote_account, &vote).unwrap(); simulate_process_vote_unchecked(&vote_pubkey, &mut vote_account, &vote).unwrap();
assert_eq!(vote_state.votes, vec![Lockout::new(&vote)]); assert_eq!(vote_state.votes, vec![Lockout::new(&vote)]);
assert_eq!(vote_state.credits(), 0); assert_eq!(vote_state.credits(), 0);
} }
#[test] #[test]
fn test_vote_slot_hashes() { fn test_vote_slot_hashes() {
let (vote_id, mut vote_account) = create_test_account(); let (vote_pubkey, mut vote_account) = create_test_account();
let hash = hash(&[0u8]); let hash = hash(&[0u8]);
let vote = Vote::new(0, hash); let vote = Vote::new(0, hash);
// wrong hash // wrong hash
let vote_state = let vote_state = simulate_process_vote(
simulate_process_vote(&vote_id, &mut vote_account, &vote, &[(0, Hash::default())]) &vote_pubkey,
.unwrap(); &mut vote_account,
&vote,
&[(0, Hash::default())],
)
.unwrap();
assert_eq!(vote_state.votes.len(), 0); assert_eq!(vote_state.votes.len(), 0);
// wrong slot // wrong slot
let vote_state = let vote_state =
simulate_process_vote(&vote_id, &mut vote_account, &vote, &[(1, hash)]).unwrap(); simulate_process_vote(&vote_pubkey, &mut vote_account, &vote, &[(1, hash)]).unwrap();
assert_eq!(vote_state.votes.len(), 0); assert_eq!(vote_state.votes.len(), 0);
// empty slot_hashes // empty slot_hashes
let vote_state = simulate_process_vote(&vote_id, &mut vote_account, &vote, &[]).unwrap(); let vote_state =
simulate_process_vote(&vote_pubkey, &mut vote_account, &vote, &[]).unwrap();
assert_eq!(vote_state.votes.len(), 0); assert_eq!(vote_state.votes.len(), 0);
// this one would work, but the wrong account is passed for slot_hashes_id // this one would work, but the wrong account is passed for slot_hashes_id
@ -471,7 +476,7 @@ mod tests {
create_test_slot_hashes_account(&[(vote.slot, vote.hash)]); create_test_slot_hashes_account(&[(vote.slot, vote.hash)]);
assert_eq!( assert_eq!(
process_votes( process_votes(
&mut KeyedAccount::new(&vote_id, true, &mut vote_account), &mut KeyedAccount::new(&vote_pubkey, true, &mut vote_account),
&mut KeyedAccount::new(&Pubkey::default(), false, &mut slot_hashes_account), &mut KeyedAccount::new(&Pubkey::default(), false, &mut slot_hashes_account),
&[], &[],
&[vote.clone()], &[vote.clone()],
@ -482,7 +487,7 @@ mod tests {
#[test] #[test]
fn test_vote_signature() { fn test_vote_signature() {
let (vote_id, mut vote_account) = create_test_account(); let (vote_pubkey, mut vote_account) = create_test_account();
let vote = vec![Vote::new(1, Hash::default())]; let vote = vec![Vote::new(1, Hash::default())];
@ -491,7 +496,7 @@ mod tests {
// unsigned // unsigned
let res = process_votes( let res = process_votes(
&mut KeyedAccount::new(&vote_id, false, &mut vote_account), &mut KeyedAccount::new(&vote_pubkey, false, &mut vote_account),
&mut KeyedAccount::new(&slot_hashes_id, false, &mut slot_hashes_account), &mut KeyedAccount::new(&slot_hashes_id, false, &mut slot_hashes_account),
&[], &[],
&vote, &vote,
@ -500,7 +505,7 @@ mod tests {
// unsigned // unsigned
let res = process_votes( let res = process_votes(
&mut KeyedAccount::new(&vote_id, true, &mut vote_account), &mut KeyedAccount::new(&vote_pubkey, true, &mut vote_account),
&mut KeyedAccount::new(&slot_hashes_id, false, &mut slot_hashes_account), &mut KeyedAccount::new(&slot_hashes_id, false, &mut slot_hashes_account),
&[], &[],
&vote, &vote,
@ -508,29 +513,29 @@ mod tests {
assert_eq!(res, Ok(())); assert_eq!(res, Ok(()));
// another voter // another voter
let authorized_voter_id = Pubkey::new_rand(); let authorized_voter_pubkey = Pubkey::new_rand();
let res = authorize_voter( let res = authorize_voter(
&mut KeyedAccount::new(&vote_id, false, &mut vote_account), &mut KeyedAccount::new(&vote_pubkey, false, &mut vote_account),
&[], &[],
&authorized_voter_id, &authorized_voter_pubkey,
); );
assert_eq!(res, Err(InstructionError::MissingRequiredSignature)); assert_eq!(res, Err(InstructionError::MissingRequiredSignature));
let res = authorize_voter( let res = authorize_voter(
&mut KeyedAccount::new(&vote_id, true, &mut vote_account), &mut KeyedAccount::new(&vote_pubkey, true, &mut vote_account),
&[], &[],
&authorized_voter_id, &authorized_voter_pubkey,
); );
assert_eq!(res, Ok(())); assert_eq!(res, Ok(()));
// verify authorized_voter_id can authorize authorized_voter_id ;) // verify authorized_voter_pubkey can authorize authorized_voter_pubkey ;)
let res = authorize_voter( let res = authorize_voter(
&mut KeyedAccount::new(&vote_id, false, &mut vote_account), &mut KeyedAccount::new(&vote_pubkey, false, &mut vote_account),
&[KeyedAccount::new( &[KeyedAccount::new(
&authorized_voter_id, &authorized_voter_pubkey,
true, true,
&mut Account::default(), &mut Account::default(),
)], )],
&authorized_voter_id, &authorized_voter_pubkey,
); );
assert_eq!(res, Ok(())); assert_eq!(res, Ok(()));
@ -539,7 +544,7 @@ mod tests {
let (slot_hashes_id, mut slot_hashes_account) = let (slot_hashes_id, mut slot_hashes_account) =
create_test_slot_hashes_account(&[(2, Hash::default())]); create_test_slot_hashes_account(&[(2, Hash::default())]);
let res = process_votes( let res = process_votes(
&mut KeyedAccount::new(&vote_id, true, &mut vote_account), &mut KeyedAccount::new(&vote_pubkey, true, &mut vote_account),
&mut KeyedAccount::new(&slot_hashes_id, false, &mut slot_hashes_account), &mut KeyedAccount::new(&slot_hashes_id, false, &mut slot_hashes_account),
&[], &[],
&vote, &vote,
@ -549,10 +554,10 @@ mod tests {
// signed by authorized voter // signed by authorized voter
let vote = vec![Vote::new(2, Hash::default())]; let vote = vec![Vote::new(2, Hash::default())];
let res = process_votes( let res = process_votes(
&mut KeyedAccount::new(&vote_id, false, &mut vote_account), &mut KeyedAccount::new(&vote_pubkey, false, &mut vote_account),
&mut KeyedAccount::new(&slot_hashes_id, false, &mut slot_hashes_account), &mut KeyedAccount::new(&slot_hashes_id, false, &mut slot_hashes_account),
&[KeyedAccount::new( &[KeyedAccount::new(
&authorized_voter_id, &authorized_voter_pubkey,
true, true,
&mut Account::default(), &mut Account::default(),
)], )],
@ -563,11 +568,11 @@ mod tests {
#[test] #[test]
fn test_vote_without_initialization() { fn test_vote_without_initialization() {
let vote_id = Pubkey::new_rand(); let vote_pubkey = Pubkey::new_rand();
let mut vote_account = Account::new(100, VoteState::size_of(), &id()); let mut vote_account = Account::new(100, VoteState::size_of(), &id());
let res = simulate_process_vote_unchecked( let res = simulate_process_vote_unchecked(
&vote_id, &vote_pubkey,
&mut vote_account, &mut vote_account,
&Vote::new(1, Hash::default()), &Vote::new(1, Hash::default()),
); );
@ -576,7 +581,7 @@ mod tests {
#[test] #[test]
fn test_vote_lockout() { fn test_vote_lockout() {
let (_vote_id, vote_account) = create_test_account(); let (_vote_pubkey, vote_account) = create_test_account();
let mut vote_state: VoteState = vote_account.state().unwrap(); let mut vote_state: VoteState = vote_account.state().unwrap();
@ -604,8 +609,8 @@ mod tests {
#[test] #[test]
fn test_vote_double_lockout_after_expiration() { fn test_vote_double_lockout_after_expiration() {
let voter_id = Pubkey::new_rand(); let voter_pubkey = Pubkey::new_rand();
let mut vote_state = VoteState::new(&voter_id, &Pubkey::new_rand(), 0); let mut vote_state = VoteState::new(&voter_pubkey, &Pubkey::new_rand(), 0);
for i in 0..3 { for i in 0..3 {
vote_state.process_slot_vote_unchecked(i as u64); vote_state.process_slot_vote_unchecked(i as u64);
@ -632,8 +637,8 @@ mod tests {
#[test] #[test]
fn test_expire_multiple_votes() { fn test_expire_multiple_votes() {
let voter_id = Pubkey::new_rand(); let voter_pubkey = Pubkey::new_rand();
let mut vote_state = VoteState::new(&voter_id, &Pubkey::new_rand(), 0); let mut vote_state = VoteState::new(&voter_pubkey, &Pubkey::new_rand(), 0);
for i in 0..3 { for i in 0..3 {
vote_state.process_slot_vote_unchecked(i as u64); vote_state.process_slot_vote_unchecked(i as u64);
@ -663,8 +668,8 @@ mod tests {
#[test] #[test]
fn test_vote_credits() { fn test_vote_credits() {
let voter_id = Pubkey::new_rand(); let voter_pubkey = Pubkey::new_rand();
let mut vote_state = VoteState::new(&voter_id, &Pubkey::new_rand(), 0); let mut vote_state = VoteState::new(&voter_pubkey, &Pubkey::new_rand(), 0);
for i in 0..MAX_LOCKOUT_HISTORY { for i in 0..MAX_LOCKOUT_HISTORY {
vote_state.process_slot_vote_unchecked(i as u64); vote_state.process_slot_vote_unchecked(i as u64);
@ -682,8 +687,8 @@ mod tests {
#[test] #[test]
fn test_duplicate_vote() { fn test_duplicate_vote() {
let voter_id = Pubkey::new_rand(); let voter_pubkey = Pubkey::new_rand();
let mut vote_state = VoteState::new(&voter_id, &Pubkey::new_rand(), 0); let mut vote_state = VoteState::new(&voter_pubkey, &Pubkey::new_rand(), 0);
vote_state.process_slot_vote_unchecked(0); vote_state.process_slot_vote_unchecked(0);
vote_state.process_slot_vote_unchecked(1); vote_state.process_slot_vote_unchecked(1);
vote_state.process_slot_vote_unchecked(0); vote_state.process_slot_vote_unchecked(0);
@ -694,8 +699,8 @@ mod tests {
#[test] #[test]
fn test_nth_recent_vote() { fn test_nth_recent_vote() {
let voter_id = Pubkey::new_rand(); let voter_pubkey = Pubkey::new_rand();
let mut vote_state = VoteState::new(&voter_id, &Pubkey::new_rand(), 0); let mut vote_state = VoteState::new(&voter_pubkey, &Pubkey::new_rand(), 0);
for i in 0..MAX_LOCKOUT_HISTORY { for i in 0..MAX_LOCKOUT_HISTORY {
vote_state.process_slot_vote_unchecked(i as u64); vote_state.process_slot_vote_unchecked(i as u64);
} }

View File

@ -295,8 +295,8 @@ impl AccountsDB {
}; };
if candidates.is_empty() { if candidates.is_empty() {
let mut stores = self.storage.write().unwrap(); let mut stores = self.storage.write().unwrap();
let path_idx = thread_rng().gen_range(0, self.paths.len()); let path_index = thread_rng().gen_range(0, self.paths.len());
let storage = Arc::new(self.new_storage_entry(fork_id, &self.paths[path_idx])); let storage = Arc::new(self.new_storage_entry(fork_id, &self.paths[path_index]));
stores.insert(storage.id, storage.clone()); stores.insert(storage.id, storage.clone());
candidates.push(storage); candidates.push(storage);
} }

View File

@ -268,7 +268,7 @@ impl Bank {
fn process_genesis_block(&mut self, genesis_block: &GenesisBlock) { fn process_genesis_block(&mut self, genesis_block: &GenesisBlock) {
// Bootstrap leader collects fees until `new_from_parent` is called. // Bootstrap leader collects fees until `new_from_parent` is called.
self.collector_id = genesis_block.bootstrap_leader_id; self.collector_id = genesis_block.bootstrap_leader_pubkey;
self.fee_calculator = genesis_block.fee_calculator.clone(); self.fee_calculator = genesis_block.fee_calculator.clone();
for (pubkey, account) in genesis_block.accounts.iter() { for (pubkey, account) in genesis_block.accounts.iter() {
@ -1017,7 +1017,7 @@ mod tests {
#[test] #[test]
fn test_bank_new() { fn test_bank_new() {
let dummy_leader_id = Pubkey::new_rand(); let dummy_leader_pubkey = Pubkey::new_rand();
let dummy_leader_lamports = BOOTSTRAP_LEADER_LAMPORTS; let dummy_leader_lamports = BOOTSTRAP_LEADER_LAMPORTS;
let mint_lamports = 10_000; let mint_lamports = 10_000;
let GenesisBlockInfo { let GenesisBlockInfo {
@ -1027,7 +1027,7 @@ mod tests {
.. ..
} = create_genesis_block_with_leader( } = create_genesis_block_with_leader(
mint_lamports, mint_lamports,
&dummy_leader_id, &dummy_leader_pubkey,
dummy_leader_lamports, dummy_leader_lamports,
); );
let bank = Bank::new(&genesis_block); let bank = Bank::new(&genesis_block);
@ -1599,10 +1599,10 @@ mod tests {
#[test] #[test]
fn test_bank_epoch_vote_accounts() { fn test_bank_epoch_vote_accounts() {
let leader_id = Pubkey::new_rand(); let leader_pubkey = Pubkey::new_rand();
let leader_lamports = 3; let leader_lamports = 3;
let mut genesis_block = let mut genesis_block =
create_genesis_block_with_leader(5, &leader_id, leader_lamports).genesis_block; create_genesis_block_with_leader(5, &leader_pubkey, leader_lamports).genesis_block;
// set this up weird, forces future generation, odd mod(), etc. // set this up weird, forces future generation, odd mod(), etc.
// this says: "vote_accounts for epoch X should be generated at slot index 3 in epoch X-2... // this says: "vote_accounts for epoch X should be generated at slot index 3 in epoch X-2...
@ -1619,7 +1619,7 @@ mod tests {
.iter() .iter()
.filter_map(|(pubkey, (_, account))| { .filter_map(|(pubkey, (_, account))| {
if let Ok(vote_state) = VoteState::deserialize(&account.data) { if let Ok(vote_state) = VoteState::deserialize(&account.data) {
if vote_state.node_id == leader_id { if vote_state.node_pubkey == leader_pubkey {
Some((*pubkey, true)) Some((*pubkey, true))
} else { } else {
None None
@ -1645,7 +1645,7 @@ mod tests {
// child crosses epoch boundary and is the first slot in the epoch // child crosses epoch boundary and is the first slot in the epoch
let child = Bank::new_from_parent( let child = Bank::new_from_parent(
&parent, &parent,
&leader_id, &leader_pubkey,
SLOTS_PER_EPOCH - (STAKERS_SLOT_OFFSET % SLOTS_PER_EPOCH), SLOTS_PER_EPOCH - (STAKERS_SLOT_OFFSET % SLOTS_PER_EPOCH),
); );
@ -1654,7 +1654,7 @@ mod tests {
// child crosses epoch boundary but isn't the first slot in the epoch // child crosses epoch boundary but isn't the first slot in the epoch
let child = Bank::new_from_parent( let child = Bank::new_from_parent(
&parent, &parent,
&leader_id, &leader_pubkey,
SLOTS_PER_EPOCH - (STAKERS_SLOT_OFFSET % SLOTS_PER_EPOCH) + 1, SLOTS_PER_EPOCH - (STAKERS_SLOT_OFFSET % SLOTS_PER_EPOCH) + 1,
); );
assert!(child.epoch_vote_accounts(i).is_some()); assert!(child.epoch_vote_accounts(i).is_some());

View File

@ -19,7 +19,7 @@ pub struct GenesisBlockInfo {
pub fn create_genesis_block_with_leader( pub fn create_genesis_block_with_leader(
mint_lamports: u64, mint_lamports: u64,
bootstrap_leader_id: &Pubkey, bootstrap_leader_pubkey: &Pubkey,
bootstrap_leader_stake_lamports: u64, bootstrap_leader_stake_lamports: u64,
) -> GenesisBlockInfo { ) -> GenesisBlockInfo {
let mint_keypair = Keypair::new(); let mint_keypair = Keypair::new();
@ -31,13 +31,13 @@ pub fn create_genesis_block_with_leader(
// is fully implemented // is fully implemented
let (vote_account, vote_state) = vote_state::create_bootstrap_leader_account( let (vote_account, vote_state) = vote_state::create_bootstrap_leader_account(
&voting_keypair.pubkey(), &voting_keypair.pubkey(),
&bootstrap_leader_id, &bootstrap_leader_pubkey,
0, 0,
bootstrap_leader_stake_lamports, bootstrap_leader_stake_lamports,
); );
let genesis_block = GenesisBlock::new( let genesis_block = GenesisBlock::new(
&bootstrap_leader_id, &bootstrap_leader_pubkey,
&[ &[
// the mint // the mint
( (
@ -47,7 +47,7 @@ pub fn create_genesis_block_with_leader(
// node needs an account to issue votes and storage proofs from, this will require // node needs an account to issue votes and storage proofs from, this will require
// airdrops at some point to cover fees... // airdrops at some point to cover fees...
( (
*bootstrap_leader_id, *bootstrap_leader_pubkey,
Account::new(42, 0, &system_program::id()), Account::new(42, 0, &system_program::id()),
), ),
// where votes go to // where votes go to

View File

@ -11,7 +11,7 @@ use solana_sdk::system_instruction;
pub fn load_program( pub fn load_program(
bank_client: &BankClient, bank_client: &BankClient,
from_keypair: &Keypair, from_keypair: &Keypair,
loader_id: &Pubkey, loader_pubkey: &Pubkey,
program: Vec<u8>, program: Vec<u8>,
) -> Pubkey { ) -> Pubkey {
let program_keypair = Keypair::new(); let program_keypair = Keypair::new();
@ -22,7 +22,7 @@ pub fn load_program(
&program_pubkey, &program_pubkey,
1, 1,
program.len() as u64, program.len() as u64,
loader_id, loader_pubkey,
); );
bank_client bank_client
.send_instruction(&from_keypair, instruction) .send_instruction(&from_keypair, instruction)
@ -32,7 +32,7 @@ pub fn load_program(
let mut offset = 0; let mut offset = 0;
for chunk in program.chunks(chunk_size) { for chunk in program.chunks(chunk_size) {
let instruction = let instruction =
loader_instruction::write(&program_pubkey, loader_id, offset, chunk.to_vec()); loader_instruction::write(&program_pubkey, loader_pubkey, offset, chunk.to_vec());
let message = Message::new_with_payer(vec![instruction], Some(&from_keypair.pubkey())); let message = Message::new_with_payer(vec![instruction], Some(&from_keypair.pubkey()));
bank_client bank_client
.send_message(&[from_keypair, &program_keypair], message) .send_message(&[from_keypair, &program_keypair], message)
@ -40,7 +40,7 @@ pub fn load_program(
offset += chunk_size as u32; offset += chunk_size as u32;
} }
let instruction = loader_instruction::finalize(&program_pubkey, loader_id); let instruction = loader_instruction::finalize(&program_pubkey, loader_pubkey);
let message = Message::new_with_payer(vec![instruction], Some(&from_keypair.pubkey())); let message = Message::new_with_payer(vec![instruction], Some(&from_keypair.pubkey()));
bank_client bank_client
.send_message(&[from_keypair, &program_keypair], message) .send_message(&[from_keypair, &program_keypair], message)

View File

@ -107,12 +107,12 @@ mod tests {
} }
fn setup() -> (Bank, Vec<Transaction>) { fn setup() -> (Bank, Vec<Transaction>) {
let dummy_leader_id = Pubkey::new_rand(); let dummy_leader_pubkey = Pubkey::new_rand();
let GenesisBlockInfo { let GenesisBlockInfo {
genesis_block, genesis_block,
mint_keypair, mint_keypair,
.. ..
} = create_genesis_block_with_leader(500, &dummy_leader_id, 100); } = create_genesis_block_with_leader(500, &dummy_leader_pubkey, 100);
let bank = Bank::new(&genesis_block); let bank = Bank::new(&genesis_block);
let pubkey = Pubkey::new_rand(); let pubkey = Pubkey::new_rand();

View File

@ -15,12 +15,12 @@ pub struct Stakes {
} }
impl Stakes { impl Stakes {
// sum the stakes that point to the given voter_id // sum the stakes that point to the given voter_pubkey
fn calculate_stake(&self, voter_id: &Pubkey) -> u64 { fn calculate_stake(&self, voter_pubkey: &Pubkey) -> u64 {
self.stake_accounts self.stake_accounts
.iter() .iter()
.filter(|(_, stake_account)| { .filter(|(_, stake_account)| {
Some(*voter_id) == StakeState::voter_id_from(stake_account) Some(*voter_pubkey) == StakeState::voter_pubkey_from(stake_account)
}) })
.map(|(_, stake_account)| stake_account.lamports) .map(|(_, stake_account)| stake_account.lamports)
.sum() .sum()
@ -44,25 +44,25 @@ impl Stakes {
self.vote_accounts.insert(*pubkey, (stake, account.clone())); self.vote_accounts.insert(*pubkey, (stake, account.clone()));
} }
} else if solana_stake_api::check_id(&account.owner) { } else if solana_stake_api::check_id(&account.owner) {
// old_stake is stake lamports and voter_id from the pre-store() version // old_stake is stake lamports and voter_pubkey from the pre-store() version
let old_stake = self.stake_accounts.get(pubkey).and_then(|old_account| { let old_stake = self.stake_accounts.get(pubkey).and_then(|old_account| {
StakeState::voter_id_from(old_account) StakeState::voter_pubkey_from(old_account)
.map(|old_voter_id| (old_account.lamports, old_voter_id)) .map(|old_voter_pubkey| (old_account.lamports, old_voter_pubkey))
}); });
let stake = let stake = StakeState::voter_pubkey_from(account)
StakeState::voter_id_from(account).map(|voter_id| (account.lamports, voter_id)); .map(|voter_pubkey| (account.lamports, voter_pubkey));
// if adjustments need to be made... // if adjustments need to be made...
if stake != old_stake { if stake != old_stake {
if let Some((old_stake, old_voter_id)) = old_stake { if let Some((old_stake, old_voter_pubkey)) = old_stake {
self.vote_accounts self.vote_accounts
.entry(old_voter_id) .entry(old_voter_pubkey)
.and_modify(|e| e.0 -= old_stake); .and_modify(|e| e.0 -= old_stake);
} }
if let Some((stake, voter_id)) = stake { if let Some((stake, voter_pubkey)) = stake {
self.vote_accounts self.vote_accounts
.entry(voter_id) .entry(voter_pubkey)
.and_modify(|e| e.0 += stake); .and_modify(|e| e.0 += stake);
} }
} }
@ -88,19 +88,19 @@ mod tests {
// set up some dummies for a staked node (( vote ) ( stake )) // set up some dummies for a staked node (( vote ) ( stake ))
fn create_staked_node_accounts(stake: u64) -> ((Pubkey, Account), (Pubkey, Account)) { fn create_staked_node_accounts(stake: u64) -> ((Pubkey, Account), (Pubkey, Account)) {
let vote_id = Pubkey::new_rand(); let vote_pubkey = Pubkey::new_rand();
let vote_account = vote_state::create_account(&vote_id, &Pubkey::new_rand(), 0, 1); let vote_account = vote_state::create_account(&vote_pubkey, &Pubkey::new_rand(), 0, 1);
( (
(vote_id, vote_account), (vote_pubkey, vote_account),
create_stake_account(stake, &vote_id), create_stake_account(stake, &vote_pubkey),
) )
} }
// add stake to a vote_id ( stake ) // add stake to a vote_pubkey ( stake )
fn create_stake_account(stake: u64, vote_id: &Pubkey) -> (Pubkey, Account) { fn create_stake_account(stake: u64, vote_pubkey: &Pubkey) -> (Pubkey, Account) {
( (
Pubkey::new_rand(), Pubkey::new_rand(),
stake_state::create_delegate_stake_account(&vote_id, &VoteState::default(), stake), stake_state::create_delegate_stake_account(&vote_pubkey, &VoteState::default(), stake),
) )
} }
@ -108,32 +108,32 @@ mod tests {
fn test_stakes_basic() { fn test_stakes_basic() {
let mut stakes = Stakes::default(); let mut stakes = Stakes::default();
let ((vote_id, vote_account), (stake_id, mut stake_account)) = let ((vote_pubkey, vote_account), (stake_pubkey, mut stake_account)) =
create_staked_node_accounts(10); create_staked_node_accounts(10);
stakes.store(&vote_id, &vote_account); stakes.store(&vote_pubkey, &vote_account);
stakes.store(&stake_id, &stake_account); stakes.store(&stake_pubkey, &stake_account);
{ {
let vote_accounts = stakes.vote_accounts(); let vote_accounts = stakes.vote_accounts();
assert!(vote_accounts.get(&vote_id).is_some()); assert!(vote_accounts.get(&vote_pubkey).is_some());
assert_eq!(vote_accounts.get(&vote_id).unwrap().0, 10); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 10);
} }
stake_account.lamports = 42; stake_account.lamports = 42;
stakes.store(&stake_id, &stake_account); stakes.store(&stake_pubkey, &stake_account);
{ {
let vote_accounts = stakes.vote_accounts(); let vote_accounts = stakes.vote_accounts();
assert!(vote_accounts.get(&vote_id).is_some()); assert!(vote_accounts.get(&vote_pubkey).is_some());
assert_eq!(vote_accounts.get(&vote_id).unwrap().0, 42); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 42);
} }
stake_account.lamports = 0; stake_account.lamports = 0;
stakes.store(&stake_id, &stake_account); stakes.store(&stake_pubkey, &stake_account);
{ {
let vote_accounts = stakes.vote_accounts(); let vote_accounts = stakes.vote_accounts();
assert!(vote_accounts.get(&vote_id).is_some()); assert!(vote_accounts.get(&vote_pubkey).is_some());
assert_eq!(vote_accounts.get(&vote_id).unwrap().0, 0); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 0);
} }
} }
@ -141,32 +141,32 @@ mod tests {
fn test_stakes_vote_account_disappear_reappear() { fn test_stakes_vote_account_disappear_reappear() {
let mut stakes = Stakes::default(); let mut stakes = Stakes::default();
let ((vote_id, mut vote_account), (stake_id, stake_account)) = let ((vote_pubkey, mut vote_account), (stake_pubkey, stake_account)) =
create_staked_node_accounts(10); create_staked_node_accounts(10);
stakes.store(&vote_id, &vote_account); stakes.store(&vote_pubkey, &vote_account);
stakes.store(&stake_id, &stake_account); stakes.store(&stake_pubkey, &stake_account);
{ {
let vote_accounts = stakes.vote_accounts(); let vote_accounts = stakes.vote_accounts();
assert!(vote_accounts.get(&vote_id).is_some()); assert!(vote_accounts.get(&vote_pubkey).is_some());
assert_eq!(vote_accounts.get(&vote_id).unwrap().0, 10); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 10);
} }
vote_account.lamports = 0; vote_account.lamports = 0;
stakes.store(&vote_id, &vote_account); stakes.store(&vote_pubkey, &vote_account);
{ {
let vote_accounts = stakes.vote_accounts(); let vote_accounts = stakes.vote_accounts();
assert!(vote_accounts.get(&vote_id).is_none()); assert!(vote_accounts.get(&vote_pubkey).is_none());
} }
vote_account.lamports = 1; vote_account.lamports = 1;
stakes.store(&vote_id, &vote_account); stakes.store(&vote_pubkey, &vote_account);
{ {
let vote_accounts = stakes.vote_accounts(); let vote_accounts = stakes.vote_accounts();
assert!(vote_accounts.get(&vote_id).is_some()); assert!(vote_accounts.get(&vote_pubkey).is_some());
assert_eq!(vote_accounts.get(&vote_id).unwrap().0, 10); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 10);
} }
} }
@ -174,54 +174,56 @@ mod tests {
fn test_stakes_change_delegate() { fn test_stakes_change_delegate() {
let mut stakes = Stakes::default(); let mut stakes = Stakes::default();
let ((vote_id, vote_account), (stake_id, stake_account)) = create_staked_node_accounts(10); let ((vote_pubkey, vote_account), (stake_pubkey, stake_account)) =
let ((vote_id2, vote_account2), (_stake_id2, stake_account2)) =
create_staked_node_accounts(10); create_staked_node_accounts(10);
stakes.store(&vote_id, &vote_account); let ((vote_pubkey2, vote_account2), (_stake_pubkey2, stake_account2)) =
stakes.store(&vote_id2, &vote_account2); create_staked_node_accounts(10);
// delegates to vote_id stakes.store(&vote_pubkey, &vote_account);
stakes.store(&stake_id, &stake_account); stakes.store(&vote_pubkey2, &vote_account2);
// delegates to vote_pubkey
stakes.store(&stake_pubkey, &stake_account);
{ {
let vote_accounts = stakes.vote_accounts(); let vote_accounts = stakes.vote_accounts();
assert!(vote_accounts.get(&vote_id).is_some()); assert!(vote_accounts.get(&vote_pubkey).is_some());
assert_eq!(vote_accounts.get(&vote_id).unwrap().0, 10); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 10);
assert!(vote_accounts.get(&vote_id2).is_some()); assert!(vote_accounts.get(&vote_pubkey2).is_some());
assert_eq!(vote_accounts.get(&vote_id2).unwrap().0, 0); assert_eq!(vote_accounts.get(&vote_pubkey2).unwrap().0, 0);
} }
// delegates to vote_id2 // delegates to vote_pubkey2
stakes.store(&stake_id, &stake_account2); stakes.store(&stake_pubkey, &stake_account2);
{ {
let vote_accounts = stakes.vote_accounts(); let vote_accounts = stakes.vote_accounts();
assert!(vote_accounts.get(&vote_id).is_some()); assert!(vote_accounts.get(&vote_pubkey).is_some());
assert_eq!(vote_accounts.get(&vote_id).unwrap().0, 0); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 0);
assert!(vote_accounts.get(&vote_id2).is_some()); assert!(vote_accounts.get(&vote_pubkey2).is_some());
assert_eq!(vote_accounts.get(&vote_id2).unwrap().0, 10); assert_eq!(vote_accounts.get(&vote_pubkey2).unwrap().0, 10);
} }
} }
#[test] #[test]
fn test_stakes_multiple_stakers() { fn test_stakes_multiple_stakers() {
let mut stakes = Stakes::default(); let mut stakes = Stakes::default();
let ((vote_id, vote_account), (stake_id, stake_account)) = create_staked_node_accounts(10); let ((vote_pubkey, vote_account), (stake_pubkey, stake_account)) =
create_staked_node_accounts(10);
let (stake_id2, stake_account2) = create_stake_account(10, &vote_id); let (stake_pubkey2, stake_account2) = create_stake_account(10, &vote_pubkey);
stakes.store(&vote_id, &vote_account); stakes.store(&vote_pubkey, &vote_account);
// delegates to vote_id // delegates to vote_pubkey
stakes.store(&stake_id, &stake_account); stakes.store(&stake_pubkey, &stake_account);
stakes.store(&stake_id2, &stake_account2); stakes.store(&stake_pubkey2, &stake_account2);
{ {
let vote_accounts = stakes.vote_accounts(); let vote_accounts = stakes.vote_accounts();
assert!(vote_accounts.get(&vote_id).is_some()); assert!(vote_accounts.get(&vote_pubkey).is_some());
assert_eq!(vote_accounts.get(&vote_id).unwrap().0, 20); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 20);
} }
} }
@ -229,23 +231,24 @@ mod tests {
fn test_stakes_not_delegate() { fn test_stakes_not_delegate() {
let mut stakes = Stakes::default(); let mut stakes = Stakes::default();
let ((vote_id, vote_account), (stake_id, stake_account)) = create_staked_node_accounts(10); let ((vote_pubkey, vote_account), (stake_pubkey, stake_account)) =
create_staked_node_accounts(10);
stakes.store(&vote_id, &vote_account); stakes.store(&vote_pubkey, &vote_account);
stakes.store(&stake_id, &stake_account); stakes.store(&stake_pubkey, &stake_account);
{ {
let vote_accounts = stakes.vote_accounts(); let vote_accounts = stakes.vote_accounts();
assert!(vote_accounts.get(&vote_id).is_some()); assert!(vote_accounts.get(&vote_pubkey).is_some());
assert_eq!(vote_accounts.get(&vote_id).unwrap().0, 10); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 10);
} }
// not a stake account, and whacks above entry // not a stake account, and whacks above entry
stakes.store(&stake_id, &Account::new(1, 0, &solana_stake_api::id())); stakes.store(&stake_pubkey, &Account::new(1, 0, &solana_stake_api::id()));
{ {
let vote_accounts = stakes.vote_accounts(); let vote_accounts = stakes.vote_accounts();
assert!(vote_accounts.get(&vote_id).is_some()); assert!(vote_accounts.get(&vote_pubkey).is_some());
assert_eq!(vote_accounts.get(&vote_id).unwrap().0, 0); assert_eq!(vote_accounts.get(&vote_pubkey).unwrap().0, 0);
} }
} }

View File

@ -15,7 +15,7 @@ use std::path::Path;
#[derive(Serialize, Deserialize, Debug)] #[derive(Serialize, Deserialize, Debug)]
pub struct GenesisBlock { pub struct GenesisBlock {
pub accounts: Vec<(Pubkey, Account)>, pub accounts: Vec<(Pubkey, Account)>,
pub bootstrap_leader_id: Pubkey, pub bootstrap_leader_pubkey: Pubkey,
pub epoch_warmup: bool, pub epoch_warmup: bool,
pub fee_calculator: FeeCalculator, pub fee_calculator: FeeCalculator,
pub native_instruction_processors: Vec<(String, Pubkey)>, pub native_instruction_processors: Vec<(String, Pubkey)>,
@ -43,13 +43,13 @@ pub fn create_genesis_block(lamports: u64) -> (GenesisBlock, Keypair) {
impl GenesisBlock { impl GenesisBlock {
pub fn new( pub fn new(
bootstrap_leader_id: &Pubkey, bootstrap_leader_pubkey: &Pubkey,
accounts: &[(Pubkey, Account)], accounts: &[(Pubkey, Account)],
native_instruction_processors: &[(String, Pubkey)], native_instruction_processors: &[(String, Pubkey)],
) -> Self { ) -> Self {
Self { Self {
accounts: accounts.to_vec(), accounts: accounts.to_vec(),
bootstrap_leader_id: *bootstrap_leader_id, // TODO: leader_schedule to derive from actual stakes, instead ;) bootstrap_leader_pubkey: *bootstrap_leader_pubkey, // TODO: leader_schedule to derive from actual stakes, instead ;)
epoch_warmup: true, epoch_warmup: true,
fee_calculator: FeeCalculator::default(), fee_calculator: FeeCalculator::default(),
native_instruction_processors: native_instruction_processors.to_vec(), native_instruction_processors: native_instruction_processors.to_vec(),

View File

@ -20,8 +20,13 @@ pub enum LoaderInstruction {
Finalize, Finalize,
} }
pub fn write(account_id: &Pubkey, program_id: &Pubkey, offset: u32, bytes: Vec<u8>) -> Instruction { pub fn write(
let account_metas = vec![AccountMeta::new(*account_id, true)]; account_pubkey: &Pubkey,
program_id: &Pubkey,
offset: u32,
bytes: Vec<u8>,
) -> Instruction {
let account_metas = vec![AccountMeta::new(*account_pubkey, true)];
Instruction::new( Instruction::new(
*program_id, *program_id,
&LoaderInstruction::Write { offset, bytes }, &LoaderInstruction::Write { offset, bytes },
@ -29,7 +34,7 @@ pub fn write(account_id: &Pubkey, program_id: &Pubkey, offset: u32, bytes: Vec<u
) )
} }
pub fn finalize(account_id: &Pubkey, program_id: &Pubkey) -> Instruction { pub fn finalize(account_pubkey: &Pubkey, program_id: &Pubkey) -> Instruction {
let account_metas = vec![AccountMeta::new(*account_id, true)]; let account_metas = vec![AccountMeta::new(*account_pubkey, true)];
Instruction::new(*program_id, &LoaderInstruction::Finalize, account_metas) Instruction::new(*program_id, &LoaderInstruction::Finalize, account_metas)
} }

View File

@ -47,15 +47,15 @@ pub enum SystemInstruction {
} }
pub fn create_account( pub fn create_account(
from_id: &Pubkey, from_pubkey: &Pubkey,
to_id: &Pubkey, to_pubkey: &Pubkey,
lamports: u64, lamports: u64,
space: u64, space: u64,
program_id: &Pubkey, program_id: &Pubkey,
) -> Instruction { ) -> Instruction {
let account_metas = vec![ let account_metas = vec![
AccountMeta::new(*from_id, true), AccountMeta::new(*from_pubkey, true),
AccountMeta::new(*to_id, false), AccountMeta::new(*to_pubkey, false),
]; ];
Instruction::new( Instruction::new(
system_program::id(), system_program::id(),
@ -69,13 +69,13 @@ pub fn create_account(
} }
/// Create and sign a transaction to create a system account /// Create and sign a transaction to create a system account
pub fn create_user_account(from_id: &Pubkey, to_id: &Pubkey, lamports: u64) -> Instruction { pub fn create_user_account(from_pubkey: &Pubkey, to_pubkey: &Pubkey, lamports: u64) -> Instruction {
let program_id = system_program::id(); let program_id = system_program::id();
create_account(from_id, to_id, lamports, 0, &program_id) create_account(from_pubkey, to_pubkey, lamports, 0, &program_id)
} }
pub fn assign(from_id: &Pubkey, program_id: &Pubkey) -> Instruction { pub fn assign(from_pubkey: &Pubkey, program_id: &Pubkey) -> Instruction {
let account_metas = vec![AccountMeta::new(*from_id, true)]; let account_metas = vec![AccountMeta::new(*from_pubkey, true)];
Instruction::new( Instruction::new(
system_program::id(), system_program::id(),
&SystemInstruction::Assign { &SystemInstruction::Assign {
@ -85,10 +85,10 @@ pub fn assign(from_id: &Pubkey, program_id: &Pubkey) -> Instruction {
) )
} }
pub fn transfer(from_id: &Pubkey, to_id: &Pubkey, lamports: u64) -> Instruction { pub fn transfer(from_pubkey: &Pubkey, to_pubkey: &Pubkey, lamports: u64) -> Instruction {
let account_metas = vec![ let account_metas = vec![
AccountMeta::new(*from_id, true), AccountMeta::new(*from_pubkey, true),
AccountMeta::new(*to_id, false), AccountMeta::new(*to_pubkey, false),
]; ];
Instruction::new( Instruction::new(
system_program::id(), system_program::id(),
@ -98,10 +98,10 @@ pub fn transfer(from_id: &Pubkey, to_id: &Pubkey, lamports: u64) -> Instruction
} }
/// Create and sign new SystemInstruction::Transfer transaction to many destinations /// Create and sign new SystemInstruction::Transfer transaction to many destinations
pub fn transfer_many(from_id: &Pubkey, to_lamports: &[(Pubkey, u64)]) -> Vec<Instruction> { pub fn transfer_many(from_pubkey: &Pubkey, to_lamports: &[(Pubkey, u64)]) -> Vec<Instruction> {
to_lamports to_lamports
.iter() .iter()
.map(|(to_id, lamports)| transfer(from_id, to_id, *lamports)) .map(|(to_pubkey, lamports)| transfer(from_pubkey, to_pubkey, *lamports))
.collect() .collect()
} }

View File

@ -186,8 +186,8 @@ pub fn parse_command(
} }
} }
("create-vote-account", Some(matches)) => { ("create-vote-account", Some(matches)) => {
let voting_account_id = pubkey_of(matches, "voting_account_id").unwrap(); let voting_account_pubkey = pubkey_of(matches, "voting_account_pubkey").unwrap();
let node_id = pubkey_of(matches, "node_id").unwrap(); let node_pubkey = pubkey_of(matches, "node_pubkey").unwrap();
let commission = if let Some(commission) = matches.value_of("commission") { let commission = if let Some(commission) = matches.value_of("commission") {
commission.parse()? commission.parse()?
} else { } else {
@ -195,102 +195,105 @@ pub fn parse_command(
}; };
let lamports = matches.value_of("lamports").unwrap().parse()?; let lamports = matches.value_of("lamports").unwrap().parse()?;
Ok(WalletCommand::CreateVoteAccount( Ok(WalletCommand::CreateVoteAccount(
voting_account_id, voting_account_pubkey,
node_id, node_pubkey,
commission, commission,
lamports, lamports,
)) ))
} }
("authorize-voter", Some(matches)) => { ("authorize-voter", Some(matches)) => {
let voting_account_id = pubkey_of(matches, "voting_account_id").unwrap(); let voting_account_pubkey = pubkey_of(matches, "voting_account_pubkey").unwrap();
let authorized_voter_keypair = let authorized_voter_keypair =
keypair_of(matches, "authorized_voter_keypair_file").unwrap(); keypair_of(matches, "authorized_voter_keypair_file").unwrap();
let new_authorized_voter_id = pubkey_of(matches, "new_authorized_voter_id").unwrap(); let new_authorized_voter_pubkey =
pubkey_of(matches, "new_authorized_voter_pubkey").unwrap();
Ok(WalletCommand::AuthorizeVoter( Ok(WalletCommand::AuthorizeVoter(
voting_account_id, voting_account_pubkey,
authorized_voter_keypair, authorized_voter_keypair,
new_authorized_voter_id, new_authorized_voter_pubkey,
)) ))
} }
("show-vote-account", Some(matches)) => { ("show-vote-account", Some(matches)) => {
let voting_account_id = pubkey_of(matches, "voting_account_id").unwrap(); let voting_account_pubkey = pubkey_of(matches, "voting_account_pubkey").unwrap();
Ok(WalletCommand::ShowVoteAccount(voting_account_id)) Ok(WalletCommand::ShowVoteAccount(voting_account_pubkey))
} }
("create-stake-account", Some(matches)) => { ("create-stake-account", Some(matches)) => {
let staking_account_id = pubkey_of(matches, "staking_account_id").unwrap(); let staking_account_pubkey = pubkey_of(matches, "staking_account_pubkey").unwrap();
let lamports = matches.value_of("lamports").unwrap().parse()?; let lamports = matches.value_of("lamports").unwrap().parse()?;
Ok(WalletCommand::CreateStakeAccount( Ok(WalletCommand::CreateStakeAccount(
staking_account_id, staking_account_pubkey,
lamports, lamports,
)) ))
} }
("create-mining-pool-account", Some(matches)) => { ("create-mining-pool-account", Some(matches)) => {
let mining_pool_account_id = pubkey_of(matches, "mining_pool_account_id").unwrap(); let mining_pool_account_pubkey =
pubkey_of(matches, "mining_pool_account_pubkey").unwrap();
let lamports = matches.value_of("lamports").unwrap().parse()?; let lamports = matches.value_of("lamports").unwrap().parse()?;
Ok(WalletCommand::CreateMiningPoolAccount( Ok(WalletCommand::CreateMiningPoolAccount(
mining_pool_account_id, mining_pool_account_pubkey,
lamports, lamports,
)) ))
} }
("delegate-stake", Some(matches)) => { ("delegate-stake", Some(matches)) => {
let staking_account_keypair = let staking_account_keypair =
keypair_of(matches, "staking_account_keypair_file").unwrap(); keypair_of(matches, "staking_account_keypair_file").unwrap();
let voting_account_id = pubkey_of(matches, "voting_account_id").unwrap(); let voting_account_pubkey = pubkey_of(matches, "voting_account_pubkey").unwrap();
Ok(WalletCommand::DelegateStake( Ok(WalletCommand::DelegateStake(
staking_account_keypair, staking_account_keypair,
voting_account_id, voting_account_pubkey,
)) ))
} }
("redeem-vote-credits", Some(matches)) => { ("redeem-vote-credits", Some(matches)) => {
let mining_pool_account_id = pubkey_of(matches, "mining_pool_account_id").unwrap(); let mining_pool_account_pubkey =
let staking_account_id = pubkey_of(matches, "staking_account_id").unwrap(); pubkey_of(matches, "mining_pool_account_pubkey").unwrap();
let voting_account_id = pubkey_of(matches, "voting_account_id").unwrap(); let staking_account_pubkey = pubkey_of(matches, "staking_account_pubkey").unwrap();
let voting_account_pubkey = pubkey_of(matches, "voting_account_pubkey").unwrap();
Ok(WalletCommand::RedeemVoteCredits( Ok(WalletCommand::RedeemVoteCredits(
mining_pool_account_id, mining_pool_account_pubkey,
staking_account_id, staking_account_pubkey,
voting_account_id, voting_account_pubkey,
)) ))
} }
("show-stake-account", Some(matches)) => { ("show-stake-account", Some(matches)) => {
let staking_account_id = pubkey_of(matches, "staking_account_id").unwrap(); let staking_account_pubkey = pubkey_of(matches, "staking_account_pubkey").unwrap();
Ok(WalletCommand::ShowStakeAccount(staking_account_id)) Ok(WalletCommand::ShowStakeAccount(staking_account_pubkey))
} }
("create-storage-mining-pool-account", Some(matches)) => { ("create-storage-mining-pool-account", Some(matches)) => {
let storage_mining_pool_account_id = let storage_mining_pool_account_pubkey =
pubkey_of(matches, "storage_mining_pool_account_id").unwrap(); pubkey_of(matches, "storage_mining_pool_account_pubkey").unwrap();
let lamports = matches.value_of("lamports").unwrap().parse()?; let lamports = matches.value_of("lamports").unwrap().parse()?;
Ok(WalletCommand::CreateStorageMiningPoolAccount( Ok(WalletCommand::CreateStorageMiningPoolAccount(
storage_mining_pool_account_id, storage_mining_pool_account_pubkey,
lamports, lamports,
)) ))
} }
("create-replicator-storage-account", Some(matches)) => { ("create-replicator-storage-account", Some(matches)) => {
let storage_account_id = pubkey_of(matches, "storage_account_id").unwrap(); let storage_account_pubkey = pubkey_of(matches, "storage_account_pubkey").unwrap();
Ok(WalletCommand::CreateReplicatorStorageAccount( Ok(WalletCommand::CreateReplicatorStorageAccount(
storage_account_id, storage_account_pubkey,
)) ))
} }
("create-validator-storage-account", Some(matches)) => { ("create-validator-storage-account", Some(matches)) => {
let storage_account_id = pubkey_of(matches, "storage_account_id").unwrap(); let storage_account_pubkey = pubkey_of(matches, "storage_account_pubkey").unwrap();
Ok(WalletCommand::CreateValidatorStorageAccount( Ok(WalletCommand::CreateValidatorStorageAccount(
storage_account_id, storage_account_pubkey,
)) ))
} }
("claim-storage-reward", Some(matches)) => { ("claim-storage-reward", Some(matches)) => {
let storage_mining_pool_account_id = let storage_mining_pool_account_pubkey =
pubkey_of(matches, "storage_mining_pool_account_id").unwrap(); pubkey_of(matches, "storage_mining_pool_account_pubkey").unwrap();
let storage_account_id = pubkey_of(matches, "storage_account_id").unwrap(); let storage_account_pubkey = pubkey_of(matches, "storage_account_pubkey").unwrap();
let slot = matches.value_of("slot").unwrap().parse()?; let slot = matches.value_of("slot").unwrap().parse()?;
Ok(WalletCommand::ClaimStorageReward( Ok(WalletCommand::ClaimStorageReward(
storage_mining_pool_account_id, storage_mining_pool_account_pubkey,
storage_account_id, storage_account_pubkey,
slot, slot,
)) ))
} }
("show-storage-account", Some(matches)) => { ("show-storage-account", Some(matches)) => {
let storage_account_id = pubkey_of(matches, "storage_account_id").unwrap(); let storage_account_pubkey = pubkey_of(matches, "storage_account_pubkey").unwrap();
Ok(WalletCommand::ShowStorageAccount(storage_account_id)) Ok(WalletCommand::ShowStorageAccount(storage_account_pubkey))
} }
("deploy", Some(deploy_matches)) => Ok(WalletCommand::Deploy( ("deploy", Some(deploy_matches)) => Ok(WalletCommand::Deploy(
deploy_matches deploy_matches
@ -442,15 +445,15 @@ fn process_confirm(rpc_client: &RpcClient, signature: &Signature) -> ProcessResu
fn process_create_vote_account( fn process_create_vote_account(
rpc_client: &RpcClient, rpc_client: &RpcClient,
config: &WalletConfig, config: &WalletConfig,
voting_account_id: &Pubkey, voting_account_pubkey: &Pubkey,
node_id: &Pubkey, node_pubkey: &Pubkey,
commission: u32, commission: u32,
lamports: u64, lamports: u64,
) -> ProcessResult { ) -> ProcessResult {
let ixs = vote_instruction::create_account( let ixs = vote_instruction::create_account(
&config.keypair.pubkey(), &config.keypair.pubkey(),
voting_account_id, voting_account_pubkey,
node_id, node_pubkey,
commission, commission,
lamports, lamports,
); );
@ -463,16 +466,16 @@ fn process_create_vote_account(
fn process_authorize_voter( fn process_authorize_voter(
rpc_client: &RpcClient, rpc_client: &RpcClient,
config: &WalletConfig, config: &WalletConfig,
voting_account_id: &Pubkey, voting_account_pubkey: &Pubkey,
authorized_voter_keypair: &Keypair, authorized_voter_keypair: &Keypair,
new_authorized_voter_id: &Pubkey, new_authorized_voter_pubkey: &Pubkey,
) -> ProcessResult { ) -> ProcessResult {
let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?; let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?;
let ixs = vec![vote_instruction::authorize_voter( let ixs = vec![vote_instruction::authorize_voter(
&config.keypair.pubkey(), // from &config.keypair.pubkey(), // from
voting_account_id, // vote account to update voting_account_pubkey, // vote account to update
&authorized_voter_keypair.pubkey(), // current authorized voter (often the vote account itself) &authorized_voter_keypair.pubkey(), // current authorized voter (often the vote account itself)
new_authorized_voter_id, // new vote signer new_authorized_voter_pubkey, // new vote signer
)]; )];
let mut tx = Transaction::new_signed_instructions( let mut tx = Transaction::new_signed_instructions(
@ -487,11 +490,11 @@ fn process_authorize_voter(
fn process_show_vote_account( fn process_show_vote_account(
rpc_client: &RpcClient, rpc_client: &RpcClient,
_config: &WalletConfig, _config: &WalletConfig,
voting_account_id: &Pubkey, voting_account_pubkey: &Pubkey,
) -> ProcessResult { ) -> ProcessResult {
use solana_vote_api::vote_state::VoteState; use solana_vote_api::vote_state::VoteState;
let vote_account_lamports = rpc_client.retry_get_balance(voting_account_id, 5)?; let vote_account_lamports = rpc_client.retry_get_balance(voting_account_pubkey, 5)?;
let vote_account_data = rpc_client.get_account_data(voting_account_id)?; let vote_account_data = rpc_client.get_account_data(voting_account_pubkey)?;
let vote_state = VoteState::deserialize(&vote_account_data).map_err(|_| { let vote_state = VoteState::deserialize(&vote_account_data).map_err(|_| {
WalletError::RpcRequestError( WalletError::RpcRequestError(
"Account data could not be deserialized to vote state".to_string(), "Account data could not be deserialized to vote state".to_string(),
@ -499,8 +502,11 @@ fn process_show_vote_account(
})?; })?;
println!("account lamports: {}", vote_account_lamports.unwrap()); println!("account lamports: {}", vote_account_lamports.unwrap());
println!("node id: {}", vote_state.node_id); println!("node id: {}", vote_state.node_pubkey);
println!("authorized voter id: {}", vote_state.authorized_voter_id); println!(
"authorized voter pubkey: {}",
vote_state.authorized_voter_pubkey
);
println!("credits: {}", vote_state.credits()); println!("credits: {}", vote_state.credits());
println!( println!(
"commission: {}%", "commission: {}%",
@ -528,13 +534,13 @@ fn process_show_vote_account(
fn process_create_stake_account( fn process_create_stake_account(
rpc_client: &RpcClient, rpc_client: &RpcClient,
config: &WalletConfig, config: &WalletConfig,
staking_account_id: &Pubkey, staking_account_pubkey: &Pubkey,
lamports: u64, lamports: u64,
) -> ProcessResult { ) -> ProcessResult {
let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?; let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?;
let ixs = stake_instruction::create_delegate_account( let ixs = stake_instruction::create_delegate_account(
&config.keypair.pubkey(), &config.keypair.pubkey(),
staking_account_id, staking_account_pubkey,
lamports, lamports,
); );
let mut tx = Transaction::new_signed_instructions(&[&config.keypair], ixs, recent_blockhash); let mut tx = Transaction::new_signed_instructions(&[&config.keypair], ixs, recent_blockhash);
@ -545,13 +551,13 @@ fn process_create_stake_account(
fn process_create_mining_pool_account( fn process_create_mining_pool_account(
rpc_client: &RpcClient, rpc_client: &RpcClient,
config: &WalletConfig, config: &WalletConfig,
mining_pool_account_id: &Pubkey, mining_pool_account_pubkey: &Pubkey,
lamports: u64, lamports: u64,
) -> ProcessResult { ) -> ProcessResult {
let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?; let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?;
let ixs = stake_instruction::create_mining_pool_account( let ixs = stake_instruction::create_mining_pool_account(
&config.keypair.pubkey(), &config.keypair.pubkey(),
mining_pool_account_id, mining_pool_account_pubkey,
lamports, lamports,
); );
let mut tx = Transaction::new_signed_instructions(&[&config.keypair], ixs, recent_blockhash); let mut tx = Transaction::new_signed_instructions(&[&config.keypair], ixs, recent_blockhash);
@ -563,13 +569,13 @@ fn process_delegate_stake(
rpc_client: &RpcClient, rpc_client: &RpcClient,
config: &WalletConfig, config: &WalletConfig,
staking_account_keypair: &Keypair, staking_account_keypair: &Keypair,
voting_account_id: &Pubkey, voting_account_pubkey: &Pubkey,
) -> ProcessResult { ) -> ProcessResult {
let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?; let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?;
let ixs = vec![stake_instruction::delegate_stake( let ixs = vec![stake_instruction::delegate_stake(
&config.keypair.pubkey(), &config.keypair.pubkey(),
&staking_account_keypair.pubkey(), &staking_account_keypair.pubkey(),
voting_account_id, voting_account_pubkey,
)]; )];
let mut tx = Transaction::new_signed_instructions( let mut tx = Transaction::new_signed_instructions(
&[&config.keypair, &staking_account_keypair], &[&config.keypair, &staking_account_keypair],
@ -584,16 +590,16 @@ fn process_delegate_stake(
fn process_redeem_vote_credits( fn process_redeem_vote_credits(
rpc_client: &RpcClient, rpc_client: &RpcClient,
config: &WalletConfig, config: &WalletConfig,
mining_pool_account_id: &Pubkey, mining_pool_account_pubkey: &Pubkey,
staking_account_id: &Pubkey, staking_account_pubkey: &Pubkey,
voting_account_id: &Pubkey, voting_account_pubkey: &Pubkey,
) -> ProcessResult { ) -> ProcessResult {
let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?; let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?;
let ixs = vec![stake_instruction::redeem_vote_credits( let ixs = vec![stake_instruction::redeem_vote_credits(
&config.keypair.pubkey(), &config.keypair.pubkey(),
mining_pool_account_id, mining_pool_account_pubkey,
staking_account_id, staking_account_pubkey,
voting_account_id, voting_account_pubkey,
)]; )];
let mut tx = Transaction::new_signed_instructions(&[&config.keypair], ixs, recent_blockhash); let mut tx = Transaction::new_signed_instructions(&[&config.keypair], ixs, recent_blockhash);
let signature_str = rpc_client.send_and_confirm_transaction(&mut tx, &[&config.keypair])?; let signature_str = rpc_client.send_and_confirm_transaction(&mut tx, &[&config.keypair])?;
@ -603,17 +609,17 @@ fn process_redeem_vote_credits(
fn process_show_stake_account( fn process_show_stake_account(
rpc_client: &RpcClient, rpc_client: &RpcClient,
_config: &WalletConfig, _config: &WalletConfig,
staking_account_id: &Pubkey, staking_account_pubkey: &Pubkey,
) -> ProcessResult { ) -> ProcessResult {
use solana_stake_api::stake_state::StakeState; use solana_stake_api::stake_state::StakeState;
let stake_account = rpc_client.get_account(staking_account_id)?; let stake_account = rpc_client.get_account(staking_account_pubkey)?;
match stake_account.state() { match stake_account.state() {
Ok(StakeState::Delegate { Ok(StakeState::Delegate {
voter_id, voter_pubkey,
credits_observed, credits_observed,
}) => { }) => {
println!("account lamports: {}", stake_account.lamports); println!("account lamports: {}", stake_account.lamports);
println!("voter id: {}", voter_id); println!("voter pubkey: {}", voter_pubkey);
println!("credits observed: {}", credits_observed); println!("credits observed: {}", credits_observed);
Ok("".to_string()) Ok("".to_string())
} }
@ -630,13 +636,13 @@ fn process_show_stake_account(
fn process_create_storage_mining_pool_account( fn process_create_storage_mining_pool_account(
rpc_client: &RpcClient, rpc_client: &RpcClient,
config: &WalletConfig, config: &WalletConfig,
storage_account_id: &Pubkey, storage_account_pubkey: &Pubkey,
lamports: u64, lamports: u64,
) -> ProcessResult { ) -> ProcessResult {
let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?; let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?;
let ixs = storage_instruction::create_mining_pool_account( let ixs = storage_instruction::create_mining_pool_account(
&config.keypair.pubkey(), &config.keypair.pubkey(),
storage_account_id, storage_account_pubkey,
lamports, lamports,
); );
let mut tx = Transaction::new_signed_instructions(&[&config.keypair], ixs, recent_blockhash); let mut tx = Transaction::new_signed_instructions(&[&config.keypair], ixs, recent_blockhash);
@ -647,12 +653,12 @@ fn process_create_storage_mining_pool_account(
fn process_create_replicator_storage_account( fn process_create_replicator_storage_account(
rpc_client: &RpcClient, rpc_client: &RpcClient,
config: &WalletConfig, config: &WalletConfig,
storage_account_id: &Pubkey, storage_account_pubkey: &Pubkey,
) -> ProcessResult { ) -> ProcessResult {
let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?; let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?;
let ixs = storage_instruction::create_replicator_storage_account( let ixs = storage_instruction::create_replicator_storage_account(
&config.keypair.pubkey(), &config.keypair.pubkey(),
storage_account_id, storage_account_pubkey,
1, 1,
); );
let mut tx = Transaction::new_signed_instructions(&[&config.keypair], ixs, recent_blockhash); let mut tx = Transaction::new_signed_instructions(&[&config.keypair], ixs, recent_blockhash);
@ -663,12 +669,12 @@ fn process_create_replicator_storage_account(
fn process_create_validator_storage_account( fn process_create_validator_storage_account(
rpc_client: &RpcClient, rpc_client: &RpcClient,
config: &WalletConfig, config: &WalletConfig,
storage_account_id: &Pubkey, storage_account_pubkey: &Pubkey,
) -> ProcessResult { ) -> ProcessResult {
let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?; let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?;
let ixs = storage_instruction::create_validator_storage_account( let ixs = storage_instruction::create_validator_storage_account(
&config.keypair.pubkey(), &config.keypair.pubkey(),
storage_account_id, storage_account_pubkey,
1, 1,
); );
let mut tx = Transaction::new_signed_instructions(&[&config.keypair], ixs, recent_blockhash); let mut tx = Transaction::new_signed_instructions(&[&config.keypair], ixs, recent_blockhash);
@ -679,14 +685,17 @@ fn process_create_validator_storage_account(
fn process_claim_storage_reward( fn process_claim_storage_reward(
rpc_client: &RpcClient, rpc_client: &RpcClient,
config: &WalletConfig, config: &WalletConfig,
storage_mining_pool_account_id: &Pubkey, storage_mining_pool_account_pubkey: &Pubkey,
storage_account_id: &Pubkey, storage_account_pubkey: &Pubkey,
slot: u64, slot: u64,
) -> ProcessResult { ) -> ProcessResult {
let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?; let (recent_blockhash, _fee_calculator) = rpc_client.get_recent_blockhash()?;
let instruction = let instruction = storage_instruction::claim_reward(
storage_instruction::claim_reward(storage_account_id, storage_mining_pool_account_id, slot); storage_account_pubkey,
storage_mining_pool_account_pubkey,
slot,
);
let signers = [&config.keypair]; let signers = [&config.keypair];
let message = Message::new_with_payer(vec![instruction], Some(&signers[0].pubkey())); let message = Message::new_with_payer(vec![instruction], Some(&signers[0].pubkey()));
@ -698,10 +707,10 @@ fn process_claim_storage_reward(
fn process_show_storage_account( fn process_show_storage_account(
rpc_client: &RpcClient, rpc_client: &RpcClient,
_config: &WalletConfig, _config: &WalletConfig,
storage_account_id: &Pubkey, storage_account_pubkey: &Pubkey,
) -> ProcessResult { ) -> ProcessResult {
use solana_storage_api::storage_contract::StorageContract; use solana_storage_api::storage_contract::StorageContract;
let account = rpc_client.get_account(storage_account_id)?; let account = rpc_client.get_account(storage_account_pubkey)?;
let storage_contract: StorageContract = account.state().map_err(|err| { let storage_contract: StorageContract = account.state().map_err(|err| {
WalletError::RpcRequestError( WalletError::RpcRequestError(
format!("Unable to deserialize storage account: {:?}", err).to_string(), format!("Unable to deserialize storage account: {:?}", err).to_string(),
@ -969,103 +978,106 @@ pub fn process_command(config: &WalletConfig) -> ProcessResult {
WalletCommand::Confirm(signature) => process_confirm(&rpc_client, signature), WalletCommand::Confirm(signature) => process_confirm(&rpc_client, signature),
// Create vote account // Create vote account
WalletCommand::CreateVoteAccount(voting_account_id, node_id, commission, lamports) => { WalletCommand::CreateVoteAccount(
process_create_vote_account( voting_account_pubkey,
&rpc_client, node_pubkey,
config, commission,
&voting_account_id, lamports,
&node_id, ) => process_create_vote_account(
*commission, &rpc_client,
*lamports, config,
) &voting_account_pubkey,
} &node_pubkey,
*commission,
*lamports,
),
// Configure staking account already created // Configure staking account already created
WalletCommand::AuthorizeVoter( WalletCommand::AuthorizeVoter(
voting_account_id, voting_account_pubkey,
authorized_voter_keypair, authorized_voter_keypair,
new_authorized_voter_id, new_authorized_voter_pubkey,
) => process_authorize_voter( ) => process_authorize_voter(
&rpc_client, &rpc_client,
config, config,
&voting_account_id, &voting_account_pubkey,
&authorized_voter_keypair, &authorized_voter_keypair,
&new_authorized_voter_id, &new_authorized_voter_pubkey,
), ),
// Show a vote account // Show a vote account
WalletCommand::ShowVoteAccount(voting_account_id) => { WalletCommand::ShowVoteAccount(voting_account_pubkey) => {
process_show_vote_account(&rpc_client, config, &voting_account_id) process_show_vote_account(&rpc_client, config, &voting_account_pubkey)
} }
// Create stake account // Create stake account
WalletCommand::CreateStakeAccount(staking_account_id, lamports) => { WalletCommand::CreateStakeAccount(staking_account_pubkey, lamports) => {
process_create_stake_account(&rpc_client, config, &staking_account_id, *lamports) process_create_stake_account(&rpc_client, config, &staking_account_pubkey, *lamports)
} }
WalletCommand::CreateMiningPoolAccount(mining_pool_account_id, lamports) => { WalletCommand::CreateMiningPoolAccount(mining_pool_account_pubkey, lamports) => {
process_create_mining_pool_account( process_create_mining_pool_account(
&rpc_client, &rpc_client,
config, config,
&mining_pool_account_id, &mining_pool_account_pubkey,
*lamports, *lamports,
) )
} }
WalletCommand::DelegateStake(staking_account_keypair, voting_account_id) => { WalletCommand::DelegateStake(staking_account_keypair, voting_account_pubkey) => {
process_delegate_stake( process_delegate_stake(
&rpc_client, &rpc_client,
config, config,
&staking_account_keypair, &staking_account_keypair,
&voting_account_id, &voting_account_pubkey,
) )
} }
WalletCommand::RedeemVoteCredits( WalletCommand::RedeemVoteCredits(
mining_pool_account_id, mining_pool_account_pubkey,
staking_account_id, staking_account_pubkey,
voting_account_id, voting_account_pubkey,
) => process_redeem_vote_credits( ) => process_redeem_vote_credits(
&rpc_client, &rpc_client,
config, config,
&mining_pool_account_id, &mining_pool_account_pubkey,
&staking_account_id, &staking_account_pubkey,
&voting_account_id, &voting_account_pubkey,
), ),
WalletCommand::ShowStakeAccount(staking_account_id) => { WalletCommand::ShowStakeAccount(staking_account_pubkey) => {
process_show_stake_account(&rpc_client, config, &staking_account_id) process_show_stake_account(&rpc_client, config, &staking_account_pubkey)
} }
WalletCommand::CreateStorageMiningPoolAccount(storage_account_id, lamports) => { WalletCommand::CreateStorageMiningPoolAccount(storage_account_pubkey, lamports) => {
process_create_storage_mining_pool_account( process_create_storage_mining_pool_account(
&rpc_client, &rpc_client,
config, config,
&storage_account_id, &storage_account_pubkey,
*lamports, *lamports,
) )
} }
WalletCommand::CreateReplicatorStorageAccount(storage_account_id) => { WalletCommand::CreateReplicatorStorageAccount(storage_account_pubkey) => {
process_create_replicator_storage_account(&rpc_client, config, &storage_account_id) process_create_replicator_storage_account(&rpc_client, config, &storage_account_pubkey)
} }
WalletCommand::CreateValidatorStorageAccount(storage_account_id) => { WalletCommand::CreateValidatorStorageAccount(storage_account_pubkey) => {
process_create_validator_storage_account(&rpc_client, config, &storage_account_id) process_create_validator_storage_account(&rpc_client, config, &storage_account_pubkey)
} }
WalletCommand::ClaimStorageReward( WalletCommand::ClaimStorageReward(
storage_mining_pool_account_id, storage_mining_pool_account_pubkey,
storage_account_id, storage_account_pubkey,
slot, slot,
) => process_claim_storage_reward( ) => process_claim_storage_reward(
&rpc_client, &rpc_client,
config, config,
&storage_mining_pool_account_id, &storage_mining_pool_account_pubkey,
&storage_account_id, &storage_account_pubkey,
*slot, *slot,
), ),
WalletCommand::ShowStorageAccount(storage_account_id) => { WalletCommand::ShowStorageAccount(storage_account_pubkey) => {
process_show_storage_account(&rpc_client, config, &storage_account_id) process_show_storage_account(&rpc_client, config, &storage_account_pubkey)
} }
// Deploy a custom program to the chain // Deploy a custom program to the chain
@ -1263,7 +1275,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
SubCommand::with_name("authorize-voter") SubCommand::with_name("authorize-voter")
.about("Authorize a new vote signing keypair for the given vote account") .about("Authorize a new vote signing keypair for the given vote account")
.arg( .arg(
Arg::with_name("voting_account_id") Arg::with_name("voting_account_pubkey")
.index(1) .index(1)
.value_name("PUBKEY") .value_name("PUBKEY")
.takes_value(true) .takes_value(true)
@ -1280,7 +1292,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
.help("Keypair file for the currently authorized vote signer"), .help("Keypair file for the currently authorized vote signer"),
) )
.arg( .arg(
Arg::with_name("new_authorized_voter_id") Arg::with_name("new_authorized_voter_pubkey")
.index(3) .index(3)
.value_name("PUBKEY") .value_name("PUBKEY")
.takes_value(true) .takes_value(true)
@ -1293,7 +1305,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
SubCommand::with_name("create-vote-account") SubCommand::with_name("create-vote-account")
.about("Create vote account for a node") .about("Create vote account for a node")
.arg( .arg(
Arg::with_name("voting_account_id") Arg::with_name("voting_account_pubkey")
.index(1) .index(1)
.value_name("PUBKEY") .value_name("PUBKEY")
.takes_value(true) .takes_value(true)
@ -1302,7 +1314,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
.help("Vote account address to fund"), .help("Vote account address to fund"),
) )
.arg( .arg(
Arg::with_name("node_id") Arg::with_name("node_pubkey")
.index(2) .index(2)
.value_name("PUBKEY") .value_name("PUBKEY")
.takes_value(true) .takes_value(true)
@ -1330,7 +1342,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
SubCommand::with_name("show-vote-account") SubCommand::with_name("show-vote-account")
.about("Show the contents of a vote account") .about("Show the contents of a vote account")
.arg( .arg(
Arg::with_name("voting_account_id") Arg::with_name("voting_account_pubkey")
.index(1) .index(1)
.value_name("PUBKEY") .value_name("PUBKEY")
.takes_value(true) .takes_value(true)
@ -1343,7 +1355,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
SubCommand::with_name("create-mining-pool-account") SubCommand::with_name("create-mining-pool-account")
.about("Create staking mining pool account") .about("Create staking mining pool account")
.arg( .arg(
Arg::with_name("mining_pool_account_id") Arg::with_name("mining_pool_account_pubkey")
.index(1) .index(1)
.value_name("PUBKEY") .value_name("PUBKEY")
.takes_value(true) .takes_value(true)
@ -1364,7 +1376,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
SubCommand::with_name("create-stake-account") SubCommand::with_name("create-stake-account")
.about("Create staking account") .about("Create staking account")
.arg( .arg(
Arg::with_name("staking_account_id") Arg::with_name("staking_account_pubkey")
.index(1) .index(1)
.value_name("PUBKEY") .value_name("PUBKEY")
.takes_value(true) .takes_value(true)
@ -1393,7 +1405,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
.help("Keypair file for the staking account, for signing the delegate transaction."), .help("Keypair file for the staking account, for signing the delegate transaction."),
) )
.arg( .arg(
Arg::with_name("voting_account_id") Arg::with_name("voting_account_pubkey")
.index(2) .index(2)
.value_name("PUBKEY") .value_name("PUBKEY")
.takes_value(true) .takes_value(true)
@ -1406,7 +1418,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
SubCommand::with_name("redeem-vote-credits") SubCommand::with_name("redeem-vote-credits")
.about("Redeem credits in the staking account") .about("Redeem credits in the staking account")
.arg( .arg(
Arg::with_name("mining_pool_account_id") Arg::with_name("mining_pool_account_pubkey")
.index(1) .index(1)
.value_name("MINING POOL PUBKEY") .value_name("MINING POOL PUBKEY")
.takes_value(true) .takes_value(true)
@ -1415,7 +1427,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
.help("Mining pool account to redeem credits from"), .help("Mining pool account to redeem credits from"),
) )
.arg( .arg(
Arg::with_name("staking_account_id") Arg::with_name("staking_account_pubkey")
.index(2) .index(2)
.value_name("STAKING ACCOUNT PUBKEY") .value_name("STAKING ACCOUNT PUBKEY")
.takes_value(true) .takes_value(true)
@ -1424,7 +1436,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
.help("Staking account address to redeem credits for"), .help("Staking account address to redeem credits for"),
) )
.arg( .arg(
Arg::with_name("voting_account_id") Arg::with_name("voting_account_pubkey")
.index(3) .index(3)
.value_name("PUBKEY") .value_name("PUBKEY")
.takes_value(true) .takes_value(true)
@ -1437,7 +1449,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
SubCommand::with_name("show-stake-account") SubCommand::with_name("show-stake-account")
.about("Show the contents of a stake account") .about("Show the contents of a stake account")
.arg( .arg(
Arg::with_name("staking_account_id") Arg::with_name("staking_account_pubkey")
.index(1) .index(1)
.value_name("PUBKEY") .value_name("PUBKEY")
.takes_value(true) .takes_value(true)
@ -1450,7 +1462,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
SubCommand::with_name("create-storage-mining-pool-account") SubCommand::with_name("create-storage-mining-pool-account")
.about("Create mining pool account") .about("Create mining pool account")
.arg( .arg(
Arg::with_name("storage_account_id") Arg::with_name("storage_account_pubkey")
.index(1) .index(1)
.value_name("PUBKEY") .value_name("PUBKEY")
.takes_value(true) .takes_value(true)
@ -1471,7 +1483,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
SubCommand::with_name("create-replicator-storage-account") SubCommand::with_name("create-replicator-storage-account")
.about("Create a replicator storage account") .about("Create a replicator storage account")
.arg( .arg(
Arg::with_name("storage_account_id") Arg::with_name("storage_account_pubkey")
.index(1) .index(1)
.value_name("PUBKEY") .value_name("PUBKEY")
.takes_value(true) .takes_value(true)
@ -1483,7 +1495,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
SubCommand::with_name("create-validator-storage-account") SubCommand::with_name("create-validator-storage-account")
.about("Create a validator storage account") .about("Create a validator storage account")
.arg( .arg(
Arg::with_name("storage_account_id") Arg::with_name("storage_account_pubkey")
.index(1) .index(1)
.value_name("PUBKEY") .value_name("PUBKEY")
.takes_value(true) .takes_value(true)
@ -1495,7 +1507,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
SubCommand::with_name("claim-storage-reward") SubCommand::with_name("claim-storage-reward")
.about("Redeem storage reward credits") .about("Redeem storage reward credits")
.arg( .arg(
Arg::with_name("storage_mining_pool_account_id") Arg::with_name("storage_mining_pool_account_pubkey")
.index(1) .index(1)
.value_name("MINING POOL PUBKEY") .value_name("MINING POOL PUBKEY")
.takes_value(true) .takes_value(true)
@ -1504,7 +1516,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
.help("Mining pool account to redeem credits from"), .help("Mining pool account to redeem credits from"),
) )
.arg( .arg(
Arg::with_name("storage_account_id") Arg::with_name("storage_account_pubkey")
.index(2) .index(2)
.value_name("STORAGE ACCOUNT PUBKEY") .value_name("STORAGE ACCOUNT PUBKEY")
.takes_value(true) .takes_value(true)
@ -1525,7 +1537,7 @@ pub fn app<'ab, 'v>(name: &str, about: &'ab str, version: &'v str) -> App<'ab, '
SubCommand::with_name("show-storage-account") SubCommand::with_name("show-storage-account")
.about("Show the contents of a storage account") .about("Show the contents of a storage account")
.arg( .arg(
Arg::with_name("storage_account_id") Arg::with_name("storage_account_pubkey")
.index(1) .index(1)
.value_name("PUBKEY") .value_name("PUBKEY")
.takes_value(true) .takes_value(true)
@ -1752,31 +1764,31 @@ mod tests {
); );
// Test CreateVoteAccount SubCommand // Test CreateVoteAccount SubCommand
let node_id = Pubkey::new_rand(); let node_pubkey = Pubkey::new_rand();
let node_id_string = format!("{}", node_id); let node_pubkey_string = format!("{}", node_pubkey);
let test_create_vote_account = test_commands.clone().get_matches_from(vec![ let test_create_vote_account = test_commands.clone().get_matches_from(vec![
"test", "test",
"create-vote-account", "create-vote-account",
&pubkey_string, &pubkey_string,
&node_id_string, &node_pubkey_string,
"50", "50",
"--commission", "--commission",
"10", "10",
]); ]);
assert_eq!( assert_eq!(
parse_command(&pubkey, &test_create_vote_account).unwrap(), parse_command(&pubkey, &test_create_vote_account).unwrap(),
WalletCommand::CreateVoteAccount(pubkey, node_id, 10, 50) WalletCommand::CreateVoteAccount(pubkey, node_pubkey, 10, 50)
); );
let test_create_vote_account2 = test_commands.clone().get_matches_from(vec![ let test_create_vote_account2 = test_commands.clone().get_matches_from(vec![
"test", "test",
"create-vote-account", "create-vote-account",
&pubkey_string, &pubkey_string,
&node_id_string, &node_pubkey_string,
"50", "50",
]); ]);
assert_eq!( assert_eq!(
parse_command(&pubkey, &test_create_vote_account2).unwrap(), parse_command(&pubkey, &test_create_vote_account2).unwrap(),
WalletCommand::CreateVoteAccount(pubkey, node_id, 0, 50) WalletCommand::CreateVoteAccount(pubkey, node_pubkey, 0, 50)
); );
// Test Create Stake Account // Test Create Stake Account
@ -1969,8 +1981,8 @@ mod tests {
assert_eq!(process_command(&config).unwrap(), "Confirmed"); assert_eq!(process_command(&config).unwrap(), "Confirmed");
let bob_pubkey = Pubkey::new_rand(); let bob_pubkey = Pubkey::new_rand();
let node_id = Pubkey::new_rand(); let node_pubkey = Pubkey::new_rand();
config.command = WalletCommand::CreateVoteAccount(bob_pubkey, node_id, 0, 10); config.command = WalletCommand::CreateVoteAccount(bob_pubkey, node_pubkey, 0, 10);
let signature = process_command(&config); let signature = process_command(&config);
assert_eq!(signature.unwrap(), SIGNATURE.to_string()); assert_eq!(signature.unwrap(), SIGNATURE.to_string());
@ -1984,8 +1996,8 @@ mod tests {
assert_eq!(signature.unwrap(), SIGNATURE.to_string()); assert_eq!(signature.unwrap(), SIGNATURE.to_string());
let bob_keypair = Keypair::new(); let bob_keypair = Keypair::new();
let node_id = Pubkey::new_rand(); let node_pubkey = Pubkey::new_rand();
config.command = WalletCommand::DelegateStake(bob_keypair.into(), node_id); config.command = WalletCommand::DelegateStake(bob_keypair.into(), node_pubkey);
let signature = process_command(&config); let signature = process_command(&config);
assert_eq!(signature.unwrap(), SIGNATURE.to_string()); assert_eq!(signature.unwrap(), SIGNATURE.to_string());
@ -2090,7 +2102,7 @@ mod tests {
config.command = WalletCommand::Balance(config.keypair.pubkey()); config.command = WalletCommand::Balance(config.keypair.pubkey());
assert!(process_command(&config).is_err()); assert!(process_command(&config).is_err());
config.command = WalletCommand::CreateVoteAccount(bob_pubkey, node_id, 0, 10); config.command = WalletCommand::CreateVoteAccount(bob_pubkey, node_pubkey, 0, 10);
assert!(process_command(&config).is_err()); assert!(process_command(&config).is_err());
config.command = WalletCommand::AuthorizeVoter(bob_pubkey, Keypair::new(), bob_pubkey); config.command = WalletCommand::AuthorizeVoter(bob_pubkey, Keypair::new(), bob_pubkey);