Skip to content

Commit

Permalink
update to rust 1.59 and delete all the dead code
Browse files Browse the repository at this point in the history
  • Loading branch information
davidiw authored and aptos-bot committed Apr 6, 2022
1 parent 48e4de3 commit 33c2d74
Show file tree
Hide file tree
Showing 71 changed files with 137 additions and 284 deletions.
5 changes: 1 addition & 4 deletions api/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0

use aptos_api_types::{Error, LedgerInfo, TransactionOnChainData};
use aptos_config::config::{ApiConfig, RoleType};
use aptos_config::config::ApiConfig;
use aptos_crypto::HashValue;
use aptos_mempool::{MempoolClientRequest, MempoolClientSender, SubmissionStatus};
use aptos_types::{
Expand Down Expand Up @@ -34,7 +34,6 @@ pub struct Context {
chain_id: ChainId,
db: Arc<dyn DbReader>,
mp_sender: MempoolClientSender,
role: RoleType,
api_config: ApiConfig,
}

Expand All @@ -43,14 +42,12 @@ impl Context {
chain_id: ChainId,
db: Arc<dyn DbReader>,
mp_sender: MempoolClientSender,
role: RoleType,
api_config: ApiConfig,
) -> Self {
Self {
chain_id,
db,
mp_sender,
role,
api_config,
}
}
Expand Down
3 changes: 1 addition & 2 deletions api/src/runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,11 @@ pub fn bootstrap(
.build()
.expect("[api] failed to create runtime");

let role = config.base.role;
let api_config = config.api.clone();
let api = WebServer::from(api_config.clone());

runtime.spawn(async move {
let context = Context::new(chain_id, db, mp_sender, role, api_config);
let context = Context::new(chain_id, db, mp_sender, api_config);
let routes = index::routes(context);
api.serve(routes).await;
});
Expand Down
2 changes: 1 addition & 1 deletion api/src/tests/events_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ async fn test_get_events_by_struct_type_has_generic_type_parameter() {
// Instead of creating the example, we just look up an event handle that does not exist.
let path = format!(
"/accounts/0x1/events/{}/coin",
utf8_percent_encode("0x1::TestCoin::Balance<0x1::ABC::ABC>", NON_ALPHANUMERIC).to_string()
utf8_percent_encode("0x1::TestCoin::Balance<0x1::ABC::ABC>", NON_ALPHANUMERIC)
);
let resp = context.expect_status_code(404).get(path.as_str()).await;
context.check_golden_output(resp);
Expand Down
2 changes: 1 addition & 1 deletion api/src/tests/golden_output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ pub(crate) struct GoldenOutputs {

fn golden_path() -> PathBuf {
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push(GOLDEN_DIR_PATH.to_string());
path.push(GOLDEN_DIR_PATH);
path
}

Expand Down
5 changes: 2 additions & 3 deletions api/src/tests/test_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use aptos_api_types::{
mime_types, HexEncodedBytes, TransactionOnChainData, X_APTOS_CHAIN_ID,
X_APTOS_LEDGER_TIMESTAMP, X_APTOS_LEDGER_VERSION,
};
use aptos_config::config::{ApiConfig, RoleType};
use aptos_config::config::ApiConfig;
use aptos_crypto::{hash::HashValue, SigningKey};
use aptos_genesis_tool::validator_builder::{RootKeys, ValidatorBuilder};
use aptos_global_constants::OWNER_ACCOUNT;
Expand Down Expand Up @@ -72,7 +72,6 @@ pub fn new_test_context(test_name: &'static str) -> TestContext {
ChainId::test(),
db.clone(),
mempool.ac_client.clone(),
RoleType::Validator,
ApiConfig::default(),
),
rng,
Expand Down Expand Up @@ -128,7 +127,7 @@ impl TestContext {

pub fn check_golden_output(&mut self, msg: Value) {
if self.golden_output.is_none() {
self.golden_output = Some(GoldenOutputs::new(self.test_name.replace(":", "_")));
self.golden_output = Some(GoldenOutputs::new(self.test_name.replace(':', "_")));
}
self.golden_output.as_ref().unwrap().log(&pretty(&msg));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
// Copyright (c) Aptos
// SPDX-License-Identifier: Apache-2.0

// We're currently evaluating the future of this crate
#![allow(dead_code)]

use anyhow::{bail, format_err, Result};
use aptos_crypto::{
ed25519::{Ed25519PrivateKey, Ed25519PublicKey},
Expand Down
4 changes: 2 additions & 2 deletions aptos-move/aptos-vm/src/adapter_common.rs
Original file line number Diff line number Diff line change
Expand Up @@ -131,14 +131,14 @@ pub fn validate_signed_transaction<A: VMAdapter>(

pub(crate) fn validate_signature_checked_transaction<S: MoveResolver, A: VMAdapter>(
adapter: &A,
mut session: &mut SessionExt<S>,
session: &mut SessionExt<S>,
transaction: &SignatureCheckedTransaction,
allow_too_new: bool,
log_context: &AdapterLogSchema,
) -> Result<(), VMStatus> {
adapter.check_transaction_format(transaction)?;

let prologue_status = adapter.run_prologue(&mut session, transaction, log_context);
let prologue_status = adapter.run_prologue(session, transaction, log_context);
match prologue_status {
Err(err) if !allow_too_new || err.status_code() != StatusCode::SEQUENCE_NUMBER_TOO_NEW => {
Err(err)
Expand Down
4 changes: 1 addition & 3 deletions aptos-move/aptos-vm/src/aptos_vm_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -265,9 +265,7 @@ impl AptosVMImpl {
let secondary_public_key_hashes: Vec<MoveValue> = txn_data
.secondary_authentication_key_preimages
.iter()
.map(|preimage| {
MoveValue::vector_u8(HashValue::sha3_256_of(&preimage.to_vec()).to_vec())
})
.map(|preimage| MoveValue::vector_u8(HashValue::sha3_256_of(preimage).to_vec()))
.collect();
let args = if self.get_version()? >= APTOS_VERSION_3 && txn_data.is_multi_agent() {
vec![
Expand Down
8 changes: 1 addition & 7 deletions aptos-move/e2e-tests/src/executor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -273,13 +273,7 @@ impl FakeExecutor {
let ap = AccessPath::resource_access_path(ResourceKey::new(*addr, T::struct_tag()));
let data_blob = StateView::get_state_value(&self.data_store, &StateKey::AccessPath(ap))
.expect("account must exist in data store")
.unwrap_or_else(|| {
panic!(
"Can't fetch {} resource for {}",
T::STRUCT_NAME.to_string(),
addr
)
});
.unwrap_or_else(|| panic!("Can't fetch {} resource for {}", T::STRUCT_NAME, addr));
bcs::from_bytes(data_blob.as_slice()).ok()
}

Expand Down
2 changes: 1 addition & 1 deletion aptos-move/e2e-tests/src/golden_outputs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ pub(crate) struct GoldenOutputs {

fn golden_path() -> PathBuf {
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push(GOLDEN_DIR_PATH.to_string());
path.push(GOLDEN_DIR_PATH);
path
}

Expand Down
4 changes: 2 additions & 2 deletions aptos-move/transaction-builder-generator/src/typescript.rs
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,7 @@ return new AptosTypes.Script(code, tyArgs, args);"#,
}},
"#,
abi.name().to_camel_case(),
abi.doc().replace("\"", "\\\"").replace("\n", "\" + \n \""),
abi.doc().replace('\"', "\\\"").replace('\n', "\" + \n \""),
abi.ty_args()
.iter()
.map(|ty_arg| format!("\"{}\"", ty_arg.name()))
Expand Down Expand Up @@ -504,7 +504,7 @@ return new AptosTypes.Script(code, tyArgs, args);"#,
writeln!(
self.out,
" description: \"{}\",",
abi.doc().replace("\"", "\\\"").replace("\n", "\" + \n \"")
abi.doc().replace('\"', "\\\"").replace('\n', "\" + \n \"")
)?;
writeln!(
self.out,
Expand Down
3 changes: 0 additions & 3 deletions aptos-move/transaction-replay/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@ struct Opt {
/// Path to the local AptosDB file
#[structopt(long, parse(from_os_str))]
db: Option<PathBuf>,
/// Full URL address to connect to - should include port number, if applicable
#[structopt(short = "u", long)]
url: Option<String>,
/// If true, persist the effects of replaying transactions via `cmd` to disk in a format understood by the Move CLI
#[structopt(short = "s", global = true)]
save_write_sets: bool,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ fn compile_admin_script(input: &str) -> Result<Script> {

pub fn template_path() -> PathBuf {
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
path.push(SCRIPTS_DIR_PATH.to_string());
path.push(SCRIPTS_DIR_PATH);
path
}

Expand Down
2 changes: 2 additions & 0 deletions clippy.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@ cognitive-complexity-threshold = 100
type-complexity-threshold = 10000
# manipulating complex states machines in consensus
too-many-arguments-threshold = 13
# Reasonably large enum variants are okay
enum-variant-size-threshold = 1000
6 changes: 3 additions & 3 deletions config/management/genesis/src/genesis.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,13 +53,13 @@ impl Genesis {

if let Some(path) = self.path {
let mut file = File::create(path).map_err(|e| {
Error::UnexpectedError(format!("Unable to create genesis file: {}", e.to_string()))
Error::UnexpectedError(format!("Unable to create genesis file: {}", e))
})?;
let bytes = bcs::to_bytes(&genesis).map_err(|e| {
Error::UnexpectedError(format!("Unable to serialize genesis: {}", e.to_string()))
Error::UnexpectedError(format!("Unable to serialize genesis: {}", e))
})?;
file.write_all(&bytes).map_err(|e| {
Error::UnexpectedError(format!("Unable to write genesis file: {}", e.to_string()))
Error::UnexpectedError(format!("Unable to write genesis file: {}", e))
})?;
}

Expand Down
6 changes: 2 additions & 4 deletions config/management/genesis/src/verify.rs
Original file line number Diff line number Diff line change
Expand Up @@ -243,15 +243,13 @@ fn validator_config(
.get_latest_state_value(StateKey::AccountAddressKey(
account_config::validator_set_address(),
))
.map_err(|e| {
Error::UnexpectedError(format!("ValidatorSet Account issue {}", e.to_string()))
})?
.map_err(|e| Error::UnexpectedError(format!("ValidatorSet Account issue {}", e)))?
.ok_or_else(|| Error::UnexpectedError("ValidatorSet Account not found".into()))?;
let account_state = AccountState::try_from(&blob)
.map_err(|e| Error::UnexpectedError(format!("Failed to parse blob: {}", e)))?;
let validator_set: ValidatorSet = account_state
.get_validator_set()
.map_err(|e| Error::UnexpectedError(format!("ValidatorSet issue {}", e.to_string())))?
.map_err(|e| Error::UnexpectedError(format!("ValidatorSet issue {}", e)))?
.ok_or_else(|| Error::UnexpectedError("ValidatorSet does not exist".into()))?;
let info = validator_set
.payload()
Expand Down
2 changes: 1 addition & 1 deletion config/management/operational/src/account_resource.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ impl RotateOperatorKey {
Err(e) => {
return Err(Error::UnexpectedError(format!(
"Invalid authentication key found in account resource. Error: {}",
e.to_string()
e,
)));
}
};
Expand Down
7 changes: 1 addition & 6 deletions config/management/operational/src/validator_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use aptos_crypto::{ed25519::Ed25519PublicKey, x25519};
use aptos_global_constants::{
CONSENSUS_KEY, FULLNODE_NETWORK_KEY, OPERATOR_ACCOUNT, OWNER_ACCOUNT, VALIDATOR_NETWORK_KEY,
};
use aptos_management::{error::Error, secure_backend::ValidatorBackend, storage::to_x25519};
use aptos_management::{error::Error, storage::to_x25519};
use aptos_types::{
account_address::AccountAddress,
network_address::{NetworkAddress, Protocol},
Expand Down Expand Up @@ -267,11 +267,6 @@ pub struct ValidatorConfig {
/// JSON-RPC Endpoint (e.g. http://localhost:8080)
#[structopt(long, required_unless = "config")]
json_server: Option<String>,
#[structopt(
long,
help = "The secure backend that contains the network address encryption keys"
)]
validator_backend: Option<ValidatorBackend>,
}

impl ValidatorConfig {
Expand Down
7 changes: 1 addition & 6 deletions config/management/operational/src/validator_set.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::{
validator_config::{fullnode_addresses, validator_addresses, DecodedValidatorConfig},
};
use aptos_crypto::ed25519::Ed25519PublicKey;
use aptos_management::{config::ConfigPath, error::Error, secure_backend::ValidatorBackend};
use aptos_management::{config::ConfigPath, error::Error};
use aptos_types::{
account_address::AccountAddress, network_address::NetworkAddress, validator_info::ValidatorInfo,
};
Expand All @@ -22,11 +22,6 @@ pub struct ValidatorSet {
json_server: Option<String>,
#[structopt(long, help = "AccountAddress to retrieve the validator set info")]
account_address: Option<AccountAddress>,
#[structopt(
long,
help = "The secure backend that contains the network address encryption keys"
)]
validator_backend: Option<ValidatorBackend>,
}

impl ValidatorSet {
Expand Down
4 changes: 2 additions & 2 deletions consensus/src/block_storage/block_store.rs
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ impl BlockStore {

let blocks_to_commit = self
.path_from_ordered_root(block_id_to_commit)
.unwrap_or_else(Vec::new);
.unwrap_or_default();

assert!(!blocks_to_commit.is_empty());

Expand Down Expand Up @@ -359,7 +359,7 @@ impl BlockStore {
// recover the block tree in executor
let blocks_to_reexecute = self
.path_from_ordered_root(parent_block_id)
.unwrap_or_else(Vec::new);
.unwrap_or_default();

for block in blocks_to_reexecute {
self.execute_block(block.block().clone()).await?;
Expand Down
3 changes: 1 addition & 2 deletions consensus/src/epoch_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -586,8 +586,7 @@ impl EpochManager {
event: VerifiedEvent,
) -> anyhow::Result<()> {
match event {
buffer_manager_event
@ (VerifiedEvent::CommitVote(_)
buffer_manager_event @ (VerifiedEvent::CommitVote(_)
| VerifiedEvent::CommitDecision(_)) => {
if let Some(sender) = &mut self.buffer_manager_msg_tx {
sender.push(peer_id, buffer_manager_event)?;
Expand Down
2 changes: 1 addition & 1 deletion consensus/src/twins/twins_node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ impl SMRNode {
.collect(),
);
// sort by the peer id
node_configs.sort_by_key(|n1| author_from_config(n1));
node_configs.sort_by_key(author_from_config);

let proposer_type = match proposer_type {
RoundProposer(_) => {
Expand Down
2 changes: 1 addition & 1 deletion crates/aptos-crypto-derive/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -415,7 +415,7 @@ pub fn bcs_crypto_hash_dispatch(input: TokenStream) -> TokenStream {
let name = &ast.ident;
let hasher_name = Ident::new(&format!("{}Hasher", &name.to_string()), Span::call_site());
let error_msg = syn::LitStr::new(
&format!("BCS serialization of {} should not fail", name.to_string()),
&format!("BCS serialization of {} should not fail", name),
Span::call_site(),
);
let generics = add_trait_bounds(ast.generics);
Expand Down
2 changes: 1 addition & 1 deletion crates/aptos-crypto/src/hkdf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ where
let hkdf =
hkdf::Hkdf::<D>::from_prk(prk).map_err(|_| HkdfError::WrongPseudorandomKeyError)?;
let mut okm = vec![0u8; length];
hkdf.expand(info.unwrap_or_else(|| &[]), &mut okm)
hkdf.expand(info.unwrap_or(&[]), &mut okm)
// length > D::OutputSize::to_usize() * 255
.map_err(|_| HkdfError::InvalidOutputLengthError)?;
Ok(okm)
Expand Down
6 changes: 3 additions & 3 deletions crates/aptos-crypto/src/noise.rs
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ fn hash(data: &[u8]) -> Vec<u8> {
}

fn hkdf(ck: &[u8], dh_output: Option<&[u8]>) -> Result<(Vec<u8>, Vec<u8>), NoiseError> {
let dh_output = dh_output.unwrap_or_else(|| &[]);
let dh_output = dh_output.unwrap_or(&[]);
let hkdf_output = if dh_output.is_empty() {
Hkdf::<sha2::Sha256>::extract_then_expand_no_ikm(Some(ck), None, 64)
} else {
Expand Down Expand Up @@ -326,7 +326,7 @@ impl NoiseConfig {
let aead = Aes256Gcm::new(GenericArray::from_slice(&k));

let msg_and_ad = Payload {
msg: payload.unwrap_or_else(|| &[]),
msg: payload.unwrap_or(&[]),
aad: &h,
};
let nonce = GenericArray::from_slice(&[0u8; AES_NONCE_SIZE]);
Expand Down Expand Up @@ -547,7 +547,7 @@ impl NoiseConfig {
let aead = Aes256Gcm::new(GenericArray::from_slice(&k));

let msg_and_ad = Payload {
msg: payload.unwrap_or_else(|| &[]),
msg: payload.unwrap_or(&[]),
aad: &h,
};
let nonce = GenericArray::from_slice(&[0u8; AES_NONCE_SIZE]);
Expand Down
4 changes: 2 additions & 2 deletions crates/aptos-faucet/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -454,12 +454,12 @@ mod tests {

let resp = warp::test::request()
.method("GET")
.path(&"/health".to_string())
.path("/health")
.reply(&routes(service))
.await;

assert_eq!(resp.status(), 200);
assert_eq!(resp.body(), 0.to_string().as_str());
assert_eq!(resp.body(), std::string::ToString::to_string(&0).as_str());
}

#[tokio::test]
Expand Down
4 changes: 2 additions & 2 deletions crates/aptos-logger/src/aptos_logger.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ impl LogEntry {
}

pub fn hostname(&self) -> Option<&str> {
self.hostname.as_deref()
self.hostname
}

pub fn timestamp(&self) -> &str {
Expand Down Expand Up @@ -517,7 +517,7 @@ impl Writer for FileWriter {
/// Write to file
fn write(&self, log: String) {
if let Err(err) = writeln!(self.log_file.write(), "{}", log) {
eprintln!("Unable to write to log file: {}", err.to_string());
eprintln!("Unable to write to log file: {}", err);
}
}
}
Expand Down
Loading

0 comments on commit 33c2d74

Please sign in to comment.