Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

Apply clippy::unnecesary_to_owned and clippy::unwrap_or_default fixes throughout stacks core #5741

Merged
merged 5 commits into from
Jan 28, 2025
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion libsigner/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ fn test_simple_signer() {
reward_cycle: 1,
};
for i in 0..max_events {
let privk = Secp256k1PrivateKey::new();
let privk = Secp256k1PrivateKey::random();
let message = SignerMessage::BlockProposal(block_proposal.clone());
let message_bytes = message.serialize_to_vec();
let mut chunk = StackerDBChunkData::new(i as u32, 1, message_bytes);
Expand Down
20 changes: 11 additions & 9 deletions libsigner/src/v0/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1192,7 +1192,7 @@ mod test {
let rejection = BlockRejection::new(
Sha512Trunc256Sum([0u8; 32]),
RejectCode::ValidationFailed(ValidateRejectCode::InvalidBlock),
&StacksPrivateKey::new(),
&StacksPrivateKey::random(),
thread_rng().gen_bool(0.5),
thread_rng().next_u64(),
);
Expand All @@ -1204,7 +1204,7 @@ mod test {
let rejection = BlockRejection::new(
Sha512Trunc256Sum([1u8; 32]),
RejectCode::ConnectivityIssues,
&StacksPrivateKey::new(),
&StacksPrivateKey::random(),
thread_rng().gen_bool(0.5),
thread_rng().next_u64(),
);
Expand All @@ -1231,7 +1231,7 @@ mod test {
let response = BlockResponse::Rejected(BlockRejection::new(
Sha512Trunc256Sum([1u8; 32]),
RejectCode::ValidationFailed(ValidateRejectCode::InvalidBlock),
&StacksPrivateKey::new(),
&StacksPrivateKey::random(),
thread_rng().gen_bool(0.5),
thread_rng().next_u64(),
));
Expand Down Expand Up @@ -1318,10 +1318,10 @@ mod test {

#[test]
fn verify_sign_mock_proposal() {
let private_key = StacksPrivateKey::new();
let private_key = StacksPrivateKey::random();
let public_key = StacksPublicKey::from_private(&private_key);

let bad_private_key = StacksPrivateKey::new();
let bad_private_key = StacksPrivateKey::random();
let bad_public_key = StacksPublicKey::from_private(&bad_private_key);

let mut mock_proposal = random_mock_proposal();
Expand Down Expand Up @@ -1353,7 +1353,7 @@ mod test {
#[test]
fn serde_mock_proposal() {
let mut mock_signature = random_mock_proposal();
mock_signature.sign(&StacksPrivateKey::new()).unwrap();
mock_signature.sign(&StacksPrivateKey::random()).unwrap();
let serialized_signature = mock_signature.serialize_to_vec();
let deserialized_signature = read_next::<MockProposal, _>(&mut &serialized_signature[..])
.expect("Failed to deserialize MockSignature");
Expand All @@ -1368,7 +1368,7 @@ mod test {
metadata: SignerMessageMetadata::default(),
};
mock_signature
.sign(&StacksPrivateKey::new())
.sign(&StacksPrivateKey::random())
.expect("Failed to sign MockSignature");
let serialized_signature = mock_signature.serialize_to_vec();
let deserialized_signature = read_next::<MockSignature, _>(&mut &serialized_signature[..])
Expand All @@ -1379,8 +1379,10 @@ mod test {
#[test]
fn serde_mock_block() {
let mock_proposal = random_mock_proposal();
let mock_signature_1 = MockSignature::new(mock_proposal.clone(), &StacksPrivateKey::new());
let mock_signature_2 = MockSignature::new(mock_proposal.clone(), &StacksPrivateKey::new());
let mock_signature_1 =
MockSignature::new(mock_proposal.clone(), &StacksPrivateKey::random());
let mock_signature_2 =
MockSignature::new(mock_proposal.clone(), &StacksPrivateKey::random());
let mock_block = MockBlock {
mock_proposal,
mock_signatures: vec![mock_signature_1, mock_signature_2],
Expand Down
2 changes: 1 addition & 1 deletion libstackerdb/src/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ use crate::*;

#[test]
fn test_stackerdb_slot_metadata_sign_verify() {
let pk = StacksPrivateKey::new();
let pk = StacksPrivateKey::random();
let addr = StacksAddress::from_public_keys(
C32_ADDRESS_VERSION_MAINNET_SINGLESIG,
&AddressHashMode::SerializeP2PKH,
Expand Down
14 changes: 4 additions & 10 deletions stacks-common/src/util/secp256k1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ impl Default for Secp256k1PublicKey {
impl Secp256k1PublicKey {
#[cfg(any(test, feature = "testing"))]
pub fn new() -> Secp256k1PublicKey {
Secp256k1PublicKey::from_private(&Secp256k1PrivateKey::new())
Secp256k1PublicKey::from_private(&Secp256k1PrivateKey::random())
}

pub fn from_hex(hex_string: &str) -> Result<Secp256k1PublicKey, &'static str> {
Expand Down Expand Up @@ -249,14 +249,8 @@ impl PublicKey for Secp256k1PublicKey {
}
}

impl Default for Secp256k1PrivateKey {
fn default() -> Self {
Self::new()
}
}

impl Secp256k1PrivateKey {
pub fn new() -> Secp256k1PrivateKey {
pub fn random() -> Secp256k1PrivateKey {
let mut rng = rand::thread_rng();
loop {
// keep trying to generate valid bytes
Expand Down Expand Up @@ -460,7 +454,7 @@ mod tests {

#[test]
fn test_parse_serialize_compressed() {
let mut t1 = Secp256k1PrivateKey::new();
let mut t1 = Secp256k1PrivateKey::random();
t1.set_compress_public(true);
let h_comp = t1.to_hex();
t1.set_compress_public(false);
Expand Down Expand Up @@ -654,7 +648,7 @@ mod tests {
let mut rng = rand::thread_rng();

for i in 0..100 {
let privk = Secp256k1PrivateKey::new();
let privk = Secp256k1PrivateKey::random();
let pubk = Secp256k1PublicKey::from_private(&privk);

let mut msg = [0u8; 32];
Expand Down
4 changes: 2 additions & 2 deletions stacks-signer/src/client/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ pub(crate) mod tests {
pox_consensus_hash: Option<ConsensusHash>,
) -> (String, RPCPeerInfoData) {
// Generate some random info
let private_key = StacksPrivateKey::new();
let private_key = StacksPrivateKey::random();
let public_key = StacksPublicKey::from_private(&private_key);
let public_key_buf = StacksPublicKeyBuffer::from_public_key(&public_key);
let public_key_hash = Hash160::from_node_public_key(&public_key);
Expand Down Expand Up @@ -376,7 +376,7 @@ pub(crate) mod tests {
let private_key = if signer_id == 0 {
config.stacks_private_key
} else {
StacksPrivateKey::new()
StacksPrivateKey::random()
};
let public_key = StacksPublicKey::from_private(&private_key);

Expand Down
2 changes: 1 addition & 1 deletion stacks-signer/src/client/stackerdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ mod tests {
#[test]
fn send_signer_message_should_succeed() {
let signer_config = build_signer_config_tomls(
&[StacksPrivateKey::new()],
&[StacksPrivateKey::random()],
"localhost:20443",
Some(Duration::from_millis(128)), // Timeout defaults to 5 seconds. Let's override it to 128 milliseconds.
&Network::Testnet,
Expand Down
2 changes: 1 addition & 1 deletion stacks-signer/src/client/stacks_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1197,7 +1197,7 @@ mod tests {
#[test]
fn get_reward_set_should_succeed() {
let mock = MockServerClient::new();
let private_key = StacksPrivateKey::new();
let private_key = StacksPrivateKey::random();
let public_key = StacksPublicKey::from_private(&private_key);
let mut bytes = [0u8; 33];
bytes.copy_from_slice(&public_key.to_bytes_compressed());
Expand Down
4 changes: 2 additions & 2 deletions stacks-signer/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,10 +409,10 @@ pub mod tests {
#[test]
fn test_verify_vote() {
let mut rand = rand::thread_rng();
let private_key = Secp256k1PrivateKey::new();
let private_key = Secp256k1PrivateKey::random();
let public_key = StacksPublicKey::from_private(&private_key);

let invalid_private_key = Secp256k1PrivateKey::new();
let invalid_private_key = Secp256k1PrivateKey::random();
let invalid_public_key = StacksPublicKey::from_private(&invalid_private_key);

let sip = rand.next_u32();
Expand Down
2 changes: 1 addition & 1 deletion stacks-signer/src/monitor_signers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ impl SignerMonitor {
pub fn new(args: MonitorSignersArgs) -> Self {
url::Url::parse(&format!("http://{}", args.host)).expect("Failed to parse node host");
let stacks_client = StacksClient::try_from_host(
StacksPrivateKey::new(), // We don't need a private key to read
StacksPrivateKey::random(), // We don't need a private key to read
args.host.clone(),
"FOO".to_string(), // We don't care about authorized paths. Just accessing public info
)
Expand Down
3 changes: 2 additions & 1 deletion stacks-signer/src/runloop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -544,7 +544,8 @@ mod tests {
let weight = 10;
let mut signer_entries = Vec::with_capacity(nmb_signers);
for _ in 0..nmb_signers {
let key = StacksPublicKey::from_private(&StacksPrivateKey::new()).to_bytes_compressed();
let key =
StacksPublicKey::from_private(&StacksPrivateKey::random()).to_bytes_compressed();
let mut signing_key = [0u8; 33];
signing_key.copy_from_slice(&key);
signer_entries.push(NakamotoSignerEntry {
Expand Down
4 changes: 2 additions & 2 deletions stacks-signer/src/signerdb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1674,13 +1674,13 @@ mod tests {
previous_tenure_blocks: 1,
cause: TenureChangeCause::BlockFound,
pubkey_hash: Hash160::from_node_public_key(&StacksPublicKey::from_private(
&StacksPrivateKey::new(),
&StacksPrivateKey::random(),
)),
};
let tenure_change_tx_payload = TransactionPayload::TenureChange(tenure_change_payload);
let tenure_change_tx = StacksTransaction::new(
TransactionVersion::Testnet,
TransactionAuth::from_p2pkh(&StacksPrivateKey::new()).unwrap(),
TransactionAuth::from_p2pkh(&StacksPrivateKey::random()).unwrap(),
tenure_change_tx_payload,
);

Expand Down
2 changes: 1 addition & 1 deletion stacks-signer/src/tests/chainstate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ fn setup_test_environment(
};

let stacks_client = StacksClient::new(
StacksPrivateKey::new(),
StacksPrivateKey::random(),
SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 10000).to_string(),
"FOO".into(),
false,
Expand Down
4 changes: 2 additions & 2 deletions stackslib/src/blockstack_cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -579,7 +579,7 @@ fn generate_secret_key(args: &[String], version: TransactionVersion) -> Result<S
return Err(CliError::Message(format!("USAGE:\n {}", GENERATE_USAGE)));
}

let sk = StacksPrivateKey::new();
let sk = StacksPrivateKey::random();
let pk = StacksPublicKey::from_private(&sk);
let version = match version {
TransactionVersion::Mainnet => C32_ADDRESS_VERSION_MAINNET_SINGLESIG,
Expand Down Expand Up @@ -1157,7 +1157,7 @@ mod test {
.contains("Failed to decode hex")
);

let sk = StacksPrivateKey::new();
let sk = StacksPrivateKey::random();
let s = format!(
"{}",
sign_transaction_single_sig_standard("01zz", &sk).unwrap_err()
Expand Down
2 changes: 1 addition & 1 deletion stackslib/src/burnchains/bitcoin/blocks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ impl BitcoinBlockParser {
match (inputs_opt, outputs_opt) {
(Some(inputs), Some(outputs)) => {
Some(BitcoinTransaction {
txid: Txid::from_vec_be(&tx.txid().as_bytes().to_vec()).unwrap(), // this *should* panic if it fails
txid: Txid::from_vec_be(tx.txid().as_bytes()).unwrap(), // this *should* panic if it fails
vtxindex: vtxindex as u32,
opcode,
data,
Expand Down
4 changes: 2 additions & 2 deletions stackslib/src/burnchains/bitcoin/indexer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ impl BitcoinIndexer {

// instantiate headers DB
let _ = SpvClient::new(
&working_dir_path.to_str().unwrap().to_string(),
working_dir_path.to_str().unwrap(),
0,
None,
BitcoinNetworkType::Regtest,
Expand All @@ -236,7 +236,7 @@ impl BitcoinIndexer {
)
.expect(&format!(
"Failed to open {:?}",
&working_dir_path.to_str().unwrap().to_string()
working_dir_path.to_str().unwrap()
));

BitcoinIndexer {
Expand Down
2 changes: 1 addition & 1 deletion stackslib/src/burnchains/tests/burnchain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,7 @@ fn test_burn_snapshot_sequence() {
let pubkey_hex = vrf_pubkey.to_hex();
leader_public_keys.push(pubkey_hex);

let bitcoin_privkey = Secp256k1PrivateKey::new();
let bitcoin_privkey = Secp256k1PrivateKey::random();
let bitcoin_publickey = BitcoinPublicKey::from_private(&bitcoin_privkey);

leader_bitcoin_public_keys.push(to_hex(&bitcoin_publickey.to_bytes()));
Expand Down
12 changes: 5 additions & 7 deletions stackslib/src/burnchains/tests/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -241,13 +241,11 @@ impl TestMiner {
);
match self.vrf_key_map.get(vrf_pubkey) {
Some(prover_key) => {
let proof = VRF::prove(prover_key, &last_sortition_hash.as_bytes().to_vec());
let valid =
match VRF::verify(vrf_pubkey, &proof, &last_sortition_hash.as_bytes().to_vec())
{
Ok(v) => v,
Err(e) => false,
};
let proof = VRF::prove(prover_key, last_sortition_hash.as_bytes());
let valid = match VRF::verify(vrf_pubkey, &proof, last_sortition_hash.as_bytes()) {
Ok(v) => v,
Err(e) => false,
};
assert!(valid);
Some(proof)
}
Expand Down
Loading
Loading