Skip to content

Commit c657791

Browse files
committed
clippy: enable a bunch of casting and safety lints
Also enable a grab bag of other lints; I basically copied the giant list from rust-elements and removed the ones that seemed too annoying to fix and not very important.
1 parent 3017886 commit c657791

File tree

15 files changed

+87
-48
lines changed

15 files changed

+87
-48
lines changed

Cargo.toml

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,3 +68,47 @@ members = ["bitcoind-tests", "fuzz"]
6868

6969
[lints.rust]
7070
unexpected_cfgs = { level = "deny", check-cfg = ['cfg(miniscript_bench)'] }
71+
72+
[lints.clippy]
73+
# Exclude lints we don't think are valuable.
74+
needless_question_mark = "allow" # https://github.com/rust-bitcoin/rust-bitcoin/pull/2134
75+
manual_range_contains = "allow" # More readable than clippy's format.
76+
uninlined_format_args = "allow" # This is a subjective style choice.
77+
float_cmp = "allow" # Bitcoin floats are typically limited to 8 decimal places and we want them exact.
78+
match_bool = "allow" # Adds extra indentation and LOC.
79+
match_same_arms = "allow" # Collapses things that are conceptually unrelated to each other.
80+
must_use_candidate = "allow" # Useful for audit but many false positives.
81+
similar_names = "allow" # Too many (subjectively) false positives.
82+
# Exhaustive list of pedantic clippy lints
83+
assigning_clones = "warn"
84+
borrow_as_ptr = "warn"
85+
cast_lossless = "warn"
86+
cast_possible_truncation = "allow" # All casts should include a code comment (except test code).
87+
cast_possible_wrap = "allow" # Same as above re code comment.
88+
cast_precision_loss = "warn"
89+
cast_ptr_alignment = "warn"
90+
cast_sign_loss = "allow" # All casts should include a code comment (except in test code).
91+
invalid_upcast_comparisons = "warn"
92+
option_as_ref_cloned = "warn"
93+
ptr_as_ptr = "warn"
94+
ptr_cast_constness = "warn"
95+
ref_as_ptr = "warn"
96+
ref_binding_to_reference = "warn"
97+
ref_option_ref = "warn"
98+
same_functions_in_if_condition = "warn"
99+
should_panic_without_expect = "warn"
100+
single_char_pattern = "warn"
101+
stable_sort_primitive = "warn"
102+
str_split_at_newline = "warn"
103+
string_add_assign = "warn"
104+
transmute_ptr_to_ptr = "warn"
105+
trivially_copy_pass_by_ref = "warn"
106+
unchecked_duration_subtraction = "warn"
107+
unicode_not_nfc = "warn"
108+
unnecessary_box_returns = "warn"
109+
unnecessary_join = "warn"
110+
unnecessary_literal_bound = "warn"
111+
unnecessary_wraps = "warn"
112+
unsafe_derive_deserialize = "warn"
113+
unused_async = "warn"
114+
unused_self = "warn"

src/descriptor/mod.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -969,7 +969,7 @@ impl<Ext: Extension + ParseableExt> Descriptor<DescriptorPublicKey, Ext> {
969969

970970
impl<'a> Translator<DescriptorPublicKey, String, ()> for KeyMapLookUp<'a> {
971971
fn pk(&mut self, pk: &DescriptorPublicKey) -> Result<String, ()> {
972-
key_to_string(pk, self.0)
972+
Ok(key_to_string(pk, self.0))
973973
}
974974

975975
fn sha256(&mut self, sha256: &sha256::Hash) -> Result<String, ()> {
@@ -989,11 +989,11 @@ impl<Ext: Extension + ParseableExt> Descriptor<DescriptorPublicKey, Ext> {
989989
}
990990
}
991991

992-
fn key_to_string(pk: &DescriptorPublicKey, key_map: &KeyMap) -> Result<String, ()> {
993-
Ok(match key_map.get(pk) {
992+
fn key_to_string(pk: &DescriptorPublicKey, key_map: &KeyMap) -> String {
993+
match key_map.get(pk) {
994994
Some(secret) => secret.to_string(),
995995
None => pk.to_string(),
996-
})
996+
}
997997
}
998998

999999
let descriptor = self

src/extensions/introspect_ops.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -623,7 +623,7 @@ fn spk(pref: i8, prog: &[u8]) -> Option<elements::Script> {
623623
} else if pref <= 16 && pref >= 0 {
624624
Some(
625625
script::Builder::new()
626-
.push_int(pref as i64)
626+
.push_int(i64::from(pref))
627627
.push_slice(prog)
628628
.into_script(),
629629
)
@@ -664,7 +664,7 @@ impl AssetExpr<CovExtArgs> {
664664
Asset::Explicit(a) => builder.push_slice(a.into_inner().as_ref()).push_int(1), // explicit prefix
665665
Asset::Confidential(c) => {
666666
let ser = c.serialize();
667-
builder.push_slice(&ser[1..]).push_int(ser[0] as i64)
667+
builder.push_slice(&ser[1..]).push_int(i64::from(ser[0]))
668668
}
669669
}
670670
}
@@ -752,7 +752,7 @@ impl ValueExpr<CovExtArgs> {
752752
} // explicit prefix
753753
confidential::Value::Confidential(c) => {
754754
let ser = c.serialize();
755-
builder.push_slice(&ser[1..]).push_int(ser[0] as i64)
755+
builder.push_slice(&ser[1..]).push_int(i64::from(ser[0]))
756756
}
757757
}
758758
}
@@ -838,7 +838,7 @@ impl SpkExpr<CovExtArgs> {
838838
SpkInner::Script(s) => spk_to_components(s),
839839
SpkInner::Hashed(h) => (-1, h.to_byte_array().to_vec()),
840840
};
841-
builder.push_slice(&prog).push_int(ver as i64)
841+
builder.push_slice(&prog).push_int(i64::from(ver))
842842
}
843843
SpkExpr::Const(_) => unreachable!(
844844
"Both constructors from_str and from_token_iter

src/interpreter/mod.rs

Lines changed: 2 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -701,20 +701,12 @@ where
701701
Terminal::After(ref n) => {
702702
debug_assert_eq!(node_state.n_evaluated, 0);
703703
debug_assert_eq!(node_state.n_satisfied, 0);
704-
let res = self
705-
.stack
706-
.evaluate_after(&LockTime::from(*n), self.lock_time);
707-
if res.is_some() {
708-
return res;
709-
}
704+
return Some(self.stack.evaluate_after(LockTime::from(*n), self.lock_time));
710705
}
711706
Terminal::Older(ref n) => {
712707
debug_assert_eq!(node_state.n_evaluated, 0);
713708
debug_assert_eq!(node_state.n_satisfied, 0);
714-
let res = self.stack.evaluate_older(n, self.age);
715-
if res.is_some() {
716-
return res;
717-
}
709+
return Some(self.stack.evaluate_older(*n, self.age));
718710
}
719711
Terminal::Sha256(ref hash) => {
720712
debug_assert_eq!(node_state.n_evaluated, 0);

src/interpreter/stack.rs

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -245,27 +245,27 @@ impl<'txin> Stack<'txin> {
245245
/// booleans
246246
pub(super) fn evaluate_after<Ext: Extension>(
247247
&mut self,
248-
n: &LockTime,
248+
n: LockTime,
249249
lock_time: LockTime,
250-
) -> Option<Result<SatisfiedConstraint<Ext>, Error>> {
250+
) -> Result<SatisfiedConstraint<Ext>, Error> {
251251
use LockTime::*;
252252

253-
let is_satisfied = match (*n, lock_time) {
253+
let is_satisfied = match (n, lock_time) {
254254
(Blocks(n), Blocks(lock_time)) => n <= lock_time,
255255
(Seconds(n), Seconds(lock_time)) => n <= lock_time,
256256
_ => {
257-
return Some(Err(Error::AbsoluteLocktimeComparisonInvalid(
257+
return Err(Error::AbsoluteLocktimeComparisonInvalid(
258258
n.to_consensus_u32(),
259259
lock_time.to_consensus_u32(),
260-
)))
260+
))
261261
}
262262
};
263263

264264
if is_satisfied {
265265
self.push(Element::Satisfied);
266-
Some(Ok(SatisfiedConstraint::AbsoluteTimelock { n: *n }))
266+
Ok(SatisfiedConstraint::AbsoluteTimelock { n })
267267
} else {
268-
Some(Err(Error::AbsoluteLocktimeNotMet(n.to_consensus_u32())))
268+
Err(Error::AbsoluteLocktimeNotMet(n.to_consensus_u32()))
269269
}
270270
}
271271

@@ -277,14 +277,14 @@ impl<'txin> Stack<'txin> {
277277
/// booleans
278278
pub(super) fn evaluate_older<Ext: Extension>(
279279
&mut self,
280-
n: &Sequence,
280+
n: Sequence,
281281
age: Sequence,
282-
) -> Option<Result<SatisfiedConstraint<Ext>, Error>> {
283-
if age >= *n {
282+
) -> Result<SatisfiedConstraint<Ext>, Error> {
283+
if age >= n {
284284
self.push(Element::Satisfied);
285-
Some(Ok(SatisfiedConstraint::RelativeTimelock { n: *n }))
285+
Ok(SatisfiedConstraint::RelativeTimelock { n })
286286
} else {
287-
Some(Err(Error::RelativeLocktimeNotMet(n.to_consensus_u32())))
287+
Err(Error::RelativeLocktimeNotMet(n.to_consensus_u32()))
288288
}
289289
}
290290

src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -534,7 +534,7 @@ impl fmt::Display for Error {
534534
Error::BareDescriptorAddr => write!(f, "Bare descriptors don't have address"),
535535
Error::BtcError(ref e) => write!(f, " Bitcoin Miniscript Error {}", e),
536536
Error::CovError(ref e) => write!(f, "Covenant Error: {}", e),
537-
Error::PubKeyCtxError(ref pk, ref ctx) => {
537+
Error::PubKeyCtxError(ref pk, ctx) => {
538538
write!(f, "Pubkey error: {} under {} scriptcontext", pk, ctx)
539539
}
540540
Error::MultiATooManyKeys(k) => write!(f, "MultiA too many keys {}", k),

src/miniscript/astelem.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -740,7 +740,7 @@ pub trait StackCtxOperations: Sized {
740740
impl StackCtxOperations for script::Builder {
741741
fn check_item_eq(self, idx: u32, target: &[u8]) -> Self {
742742
self.push_opcode(opcodes::all::OP_DEPTH)
743-
.push_int(idx as i64)
743+
.push_int(i64::from(idx))
744744
.push_opcode(opcodes::all::OP_SUB)
745745
.push_opcode(opcodes::all::OP_PICK)
746746
.push_slice(target)
@@ -764,7 +764,7 @@ impl StackCtxOperations for script::Builder {
764764

765765
builder
766766
.push_opcode(opcodes::all::OP_DEPTH)
767-
.push_int(idx as i64)
767+
.push_int(i64::from(idx))
768768
.push_opcode(opcodes::all::OP_SUB)
769769
.push_opcode(opcodes::all::OP_PICK)
770770
.push_opcode(opcodes::all::OP_EQUAL)

src/miniscript/context.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ impl fmt::Display for ScriptContextError {
111111
pk
112112
)
113113
}
114-
ScriptContextError::XOnlyKeysNotAllowed(ref pk, ref ctx) => {
114+
ScriptContextError::XOnlyKeysNotAllowed(ref pk, ctx) => {
115115
write!(f, "x-only key {} not allowed in {}", pk, ctx)
116116
}
117117
ScriptContextError::UncompressedKeysNotAllowed => {

src/miniscript/lex.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -180,20 +180,19 @@ impl<'s> Iterator for TokenIter<'s> {
180180
pub fn lex(script: &script::Script) -> Result<Vec<Token<'_>>, Error> {
181181
let mut ret = Vec::with_capacity(script.len());
182182

183-
fn process_candidate_push(ret: &mut [Token<'_>]) -> Result<(), Error> {
183+
fn process_candidate_push(ret: &mut [Token<'_>]) {
184184
let ret_len = ret.len();
185185

186186
if ret_len < 2 || ret[ret_len - 1] != Token::Swap {
187-
return Ok(());
187+
return;
188188
}
189189
let token = match &ret[ret_len - 2] {
190190
Token::Hash20(x) => Token::Push(x.to_vec()),
191191
Token::Bytes32(x) | Token::Bytes33(x) | Token::Bytes65(x) => Token::Push(x.to_vec()),
192-
Token::Num(k) => Token::Push(build_scriptint(*k as i64)),
193-
_x => return Ok(()), // no change required
192+
Token::Num(k) => Token::Push(build_scriptint(i64::from(*k))),
193+
_x => return, // no change required
194194
};
195195
ret[ret_len - 2] = token;
196-
Ok(())
197196
}
198197

199198
for ins in script.instructions_minimal() {
@@ -329,7 +328,7 @@ pub fn lex(script: &script::Script) -> Result<Vec<Token<'_>>, Error> {
329328
ret.push(Token::Dup2);
330329
}
331330
script::Instruction::Op(opcodes::all::OP_CAT) => {
332-
process_candidate_push(&mut ret)?;
331+
process_candidate_push(&mut ret);
333332
ret.push(Token::Cat);
334333
}
335334
script::Instruction::Op(opcodes::all::OP_CODESEPARATOR) => {

src/miniscript/satisfy.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ pub fn elementssig_to_rawsig(sig: &ElementsSig) -> Vec<u8> {
4141
/// Returns underlying secp if the Signature is not of correct format
4242
pub fn elementssig_from_rawsig(rawsig: &[u8]) -> Result<ElementsSig, crate::interpreter::Error> {
4343
let (flag, sig) = rawsig.split_last().unwrap();
44-
let flag = elements::EcdsaSighashType::from_u32(*flag as u32);
44+
let flag = elements::EcdsaSighashType::from_u32(u32::from(*flag));
4545
let sig = secp256k1_zkp::ecdsa::Signature::from_der(sig)?;
4646
Ok((sig, flag))
4747
}

0 commit comments

Comments
 (0)