Merge rust-bitcoin/rust-bitcoin#2435: Enforce `$source: std::error::Error` in `write_err`
What changed, and why it matters
This commit tightens a Rust helper macro used to format error messages so it only accepts real error types. It also fixes a bug where, in builds without the standard library, displaying certain errors would call itself forever (infinite recursion) and crash the program. Most of the changes are defensive compile-time checks; the actual recursion bug is mentioned in the pull request description but the diff only shows the macro change, not the original buggy code path.
Review the remaining `write_err_unchecked_source!` call sites to confirm they are truly generic and cannot be constrained to `std::error::Error`. Verify that the no_std infinite recursion path described in the PR is fully resolved by this macro change and that no other call sites still trigger recursion.
Security signals we found
Fixes infinite recursion in error Display on no_std builds (per PR description)
Adds compile-time enforcement that error-formatting macro receives an actual std::error::Error source
Prevents accidental misuse of write_err for non-error sources
Preserves unchecked variant for legitimate generic cases
Evidence from the diff
The write_err! macro in internals/src/error/mod.rs now requires the $source argument to implement std::error::Error + 'static when the std feature is enabled, using a helper trait ErrorExt. The old unchecked behavior is preserved as write_err_unchecked_source! for generic contexts where the source type is not known to be an error. Several call sites in bitcoin/src/crypto/sighash.rs, consensus_encoding/src/error.rs, and io/src/error.rs are switched to the unchecked variant because their source types are generic display types rather than std::error::Error. The PR description states this also fixes an infinite recursion introduced in #1400 when displaying errors on no_std, because the macro previously called Display::fmt in a way that could loop.
Changed components
internals/src/error/mod.rsbitcoin/src/crypto/sighash.rsconsensus_encoding/src/error.rsio/src/error.rsInspect captured patch +65 / −10
### bitcoin/src/crypto/sighash.rs
@@ -1096,7 +1096,7 @@ pub mod error {
use core::convert::Infallible;
use core::fmt;
- use internals::write_err;
+ use internals::{write_err, write_err_unchecked_source};
use crate::transaction;
@@ -1391,7 +1391,7 @@ pub mod error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Io(error) => write_err!(f, "failed to write sighash data"; error),
- Self::Sighash(error) => write_err!(f, "failed to compute sighash data"; error),
+ Self::Sighash(error) => write_err_unchecked_source!(f, "failed to compute sighash data"; error),
}
}
}
### consensus_encoding/src/error.rs
@@ -8,7 +8,7 @@
use core::convert::Infallible;
use core::fmt;
-use internals::write_err;
+use internals::{write_err, write_err_unchecked_source};
#[cfg(doc)]
use crate::{ArrayDecoder, Decoder2, Decoder3, Decoder4, Decoder6};
@@ -73,8 +73,8 @@ where
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
- Self::Parse(ref e) => write_err!(f, "error parsing encoded object"; e),
- Self::Unconsumed(ref e) => write_err!(f, "unconsumed"; e),
+ Self::Parse(ref e) => write_err_unchecked_source!(f, "error parsing encoded object"; e),
+ Self::Unconsumed(ref e) => write_err_unchecked_source!(f, "unconsumed"; e),
}
}
}
@@ -278,7 +278,7 @@ where
match self.0 {
E::LengthPrefixDecode(ref e) => write_err!(f, "vec decoder error"; e),
- E::Item(ref e) => write_err!(f, "vec decoder error"; e),
+ E::Item(ref e) => write_err_unchecked_source!(f, "vec decoder error"; e),
E::UnexpectedEof(ref e) => write_err!(f, "vec decoder error"; e),
}
}
@@ -352,7 +352,7 @@ impl<ParseErr: fmt::Display> fmt::Display for FromHexError<ParseErr> {
match self.0 {
FromHexErrorInner::OddLength(ref e) => write_err!(f, "odd length string"; e),
FromHexErrorInner::InvalidChar(ref e) => write_err!(f, "invalid character"; e),
- FromHexErrorInner::Decode(ref e) => write_err!(f, "decode error"; e),
+ FromHexErrorInner::Decode(ref e) => write_err_unchecked_source!(f, "decode error"; e),
}
}
}
@@ -397,7 +397,7 @@ macro_rules! define_decoder_n_error {
{
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
- $(Self::$err_wrap(ref e) => write_err!(f, $err_msg; e),)*
+ $(Self::$err_wrap(ref e) => write_err_unchecked_source!(f, $err_msg; e),)*
}
}
}
### internals/src/error/mod.rs
@@ -11,18 +11,73 @@ mod parse_error;
#[cfg(not(creusot))]
pub use input_string::InputString;
+#[doc(hidden)]
+/// Helper trait for checking whether something implements [`std::error::Error`].
+///
+/// We use helper trait instead of function to make the compiler handle auto dereferencing.
+#[cfg(feature = "std")]
+pub trait ErrorExt: std::error::Error + 'static {
+ /// Does nothing, just call it
+ #[inline(always)]
+ fn check_is_actually_error_source(&self) {}
+}
+
+#[doc(hidden)]
+#[cfg(feature = "std")]
+impl<T: std::error::Error + 'static> ErrorExt for T { }
+
/// Formats error.
///
/// If `std` feature is OFF appends error source (delimited by `: `). We do this because
/// `e.source()` is only available in std builds, without this macro the error source is lost for
/// no-std builds.
+///
+/// Note: will not compile on std if $source doesn't implement [`std::error::Error`]. This is
+/// intentional because if it doesn't the macro MUST NOT be used. However this check is very rarely
+/// imprecise so if you know what you're doing you can use the unchecked version.
#[macro_export]
macro_rules! write_err {
+ ($writer:expr, $string:literal $(, $args:expr)*; $source:expr) => {
+ {
+ #[cfg(feature = "std")]
+ {
+ use $crate::error::ErrorExt;
+
+ // Enforces that $source is actually an error.
+ //
+ // Occasionally people accidentally use write_err! with non-error and it's quite
+ // hard to detect otherwise so this gives them compilation error.
+ // Also avoids lints saying $source is unused.
+ ($source).check_is_actually_error_source();
+
+ write!($writer, $string $(, $args)*)
+ }
+ #[cfg(not(feature = "std"))]
+ {
+ write!($writer, concat!($string, ": {}") $(, $args)*, $source)
+ }
+ }
+ }
+}
+
+/// Formats error.
+///
+/// Unlike [`write_err`] doesn't statically check that `$source` implements `std::error::Error`.
+/// This should be used only in rare generic situations. Specifically, in case of a generic
+/// `MyError<Error>`, this macro should be used when formatting an error message for the generic
+/// type `Error`.
+///
+/// If `std` feature is OFF appends error source (delimited by `: `). We do this because
+/// `e.source()` is only available in std builds, without this macro the error source is lost for
+/// no-std builds.
+#[macro_export]
+macro_rules! write_err_unchecked_source {
($writer:expr, $string:literal $(, $args:expr)*; $source:expr) => {
{
#[cfg(feature = "std")]
{
let _ = &$source; // Prevents clippy warnings.
+
write!($writer, $string $(, $args)*)
}
#[cfg(not(feature = "std"))]
### io/src/error.rs
@@ -9,7 +9,7 @@ use core::fmt;
#[cfg(feature = "std")]
use std::boxed::Box;
-use internals::write_err;
+use internals::{write_err, write_err_unchecked_source};
/// The `io` crate error type.
#[derive(Debug)]
@@ -218,7 +218,7 @@ impl<D: fmt::Display> fmt::Display for ReadError<D> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Io(e) => write_err!(f, "I/O error"; e),
- Self::Decode(e) => write_err!(f, "decode error"; e),
+ Self::Decode(e) => write_err_unchecked_source!(f, "decode error"; e),
}
}
}Why this scored 31/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.