Skip to content
Merged
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,9 @@ The format is loosely based on [Keep a Changelog](https://keepachangelog.com/en/

### Changed
- Build:
- internal `is-empty` utility crate (plus its derive macro) consolidates the
`is_empty` checks over aggregate types; `PoSAccountingData::is_empty` is now
derived instead of hand-written, with no behavior change.
- the workspace no longer depends on `chrono` (unmaintained per RUSTSEC-2026-0543):
first-party code now uses `jiff`, and the remaining transitive uses are served by
temporary overlay forks (file-rotate, reedline, serde_with) that make `chrono`
Expand Down
17 changes: 17 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,8 @@ members = [
"tokens-accounting", # Tokens accounting
"utils", # Various utilities.
"utils/build_utils", # Build-related utilities.
"utils/is-empty", # Trait and derive for the is-empty check on aggregate types.
"utils/is-empty-derive", # Proc-macro implementation of the IsEmpty derive.
"utils/networking", # Various async/tokio utilities.
"utxo", # Utxo and related utilities (cache, undo, etc.).
"wallet", # Wallet primitives.
Expand Down
1 change: 1 addition & 0 deletions chainstate/test-suite/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ common = { path = "../../common" }
consensus = { path = "../../consensus" }
constraints-value-accumulator = { path = "../constraints-value-accumulator" }
crypto = { path = "../../crypto" }
is-empty = { path = "../../utils/is-empty" }
logging = { path = "../../logging" }
orders-accounting = { path = "../../orders-accounting" }
pos-accounting = { path = "../../pos-accounting" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ use common::{
primitives::{Amount, Idable, per_thousand::PerThousand},
};
use crypto::vrf::{VRFKeyKind, VRFPrivateKey};
use is_empty::IsEmpty;
use pos_accounting::PoolData;
use randomness::{CryptoRng, RngExt as _};
use rstest::rstest;
Expand Down
1 change: 1 addition & 0 deletions pos-accounting/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ rust-version.workspace = true
accounting = { path = "../accounting" }
common = { path = "../common" }
crypto = { path = "../crypto" }
is-empty = { path = "../utils/is-empty" }
randomness = { path = "../randomness" }
serialization = { path = "../serialization" }
typename = { path = "../utils/typename" }
Expand Down
12 changes: 2 additions & 10 deletions pos-accounting/src/data.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,12 @@ use common::{
chain::{DelegationId, PoolId},
primitives::Amount,
};
use is_empty::IsEmpty;
use serialization::{Decode, Encode};

use crate::{DelegationData, PoolData};

#[derive(Clone, Encode, Decode, Debug, PartialEq, Eq)]
#[derive(Clone, Encode, Decode, Debug, PartialEq, Eq, IsEmpty)]
pub struct PoSAccountingData {
/// A collection of all the pools and their data.
pub pool_data: BTreeMap<PoolId, PoolData>,
Expand Down Expand Up @@ -56,13 +57,4 @@ impl PoSAccountingData {
delegation_data: BTreeMap::new(),
}
}

// TODO: avoid manual implementation (mintlayer/mintlayer-core#669)
pub fn is_empty(&self) -> bool {
self.pool_data.is_empty()
&& self.pool_balances.is_empty()
&& self.pool_delegation_shares.is_empty()
&& self.delegation_balances.is_empty()
&& self.delegation_data.is_empty()
}
}
14 changes: 14 additions & 0 deletions utils/is-empty-derive/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
[package]
name = "is-empty-derive"
publish = false
license.workspace = true
version.workspace = true
edition.workspace = true
rust-version.workspace = true

[lib]
proc-macro = true

[dependencies]
syn.workspace = true
quote.workspace = true
99 changes: 99 additions & 0 deletions utils/is-empty-derive/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// Copyright (c) 2026 RBB S.r.l
// opensource@mintlayer.org
// SPDX-License-Identifier: MIT
// Licensed under the MIT License;
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://github.com/mintlayer/mintlayer-core/blob/master/LICENSE
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use proc_macro::TokenStream;
use quote::quote;
use syn::{Data, DeriveInput, Fields, Index, Type, parse_macro_input};

/// Derive the `IsEmpty` trait for a struct.
///
/// The generated implementation considers the struct empty when all of its fields are empty. A
/// struct with no fields is always empty.
///
/// Each field's own `is_empty` method is used, and it is resolved by ordinary method lookup rather
/// than through this trait, so that the standard collections and `String` work through their
/// inherent methods. Two things follow from that:
///
/// * A field whose `is_empty` means something unrelated is accepted silently. Fixed size arrays
/// are rejected outright: `[T; N]` would resolve to the slice method and return `false` for
/// any `N > 0`, silently making the whole struct permanently non-empty.
/// * A field whose type gets its `is_empty` from this trait needs the trait in scope at the point
/// of the derive, since the per field call is not qualified.
#[proc_macro_derive(IsEmpty)]
pub fn derive(input: TokenStream) -> TokenStream {
let DeriveInput {
ident,
generics,
data,
..
} = parse_macro_input!(input);

let fields = match data {
Data::Struct(data) => data.fields,
Data::Enum(_) | Data::Union(_) => {
return syn::Error::new_spanned(ident, "IsEmpty can only be derived for structs")
.to_compile_error()
.into();
}
};

// Arrays always report non-empty through their slice method, so deriving over them
// would silently produce a permanently non-empty aggregate; reject them instead.
for field in fields.iter() {
if let Type::Array(_) = field.ty {
return syn::Error::new_spanned(
&field.ty,
"IsEmpty cannot be derived for structs with array fields",
)
.to_compile_error()
.into();
}
}

let checks: Vec<_> = match fields {
Fields::Named(fields) => fields
.named
.into_iter()
.map(|field| {
let name = field.ident.expect("a named field always has an identifier");
quote!(self.#name.is_empty())
})
.collect(),
Fields::Unnamed(fields) => (0..fields.unnamed.len())
.map(|i| {
let index = Index::from(i);
quote!(self.#index.is_empty())
})
.collect(),
Fields::Unit => Vec::new(),
};

let body = match checks.split_first() {
Some((first, rest)) => quote!(#first #(&& #rest)*),
None => quote!(true),
};

let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

quote! {
#[automatically_derived]
impl #impl_generics ::is_empty::IsEmpty for #ident #ty_generics #where_clause {
fn is_empty(&self) -> bool {
#body
}
}
}
.into()
}
10 changes: 10 additions & 0 deletions utils/is-empty/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
[package]
name = "is-empty"
publish = false
license.workspace = true
version.workspace = true
edition.workspace = true
rust-version.workspace = true

[dependencies]
is-empty-derive = { path = "../is-empty-derive" }
163 changes: 163 additions & 0 deletions utils/is-empty/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
// Copyright (c) 2026 RBB S.r.l
// opensource@mintlayer.org
// SPDX-License-Identifier: MIT
// Licensed under the MIT License;
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://github.com/mintlayer/mintlayer-core/blob/master/LICENSE
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// The derive macro expands to `::is_empty::IsEmpty`, which would not resolve inside this crate
// itself. This alias makes that path work here too, so the trait can be derived in our own tests.
extern crate self as is_empty;

pub use is_empty_derive::IsEmpty;

/// The interface for checking whether a value is "empty".
///
/// This is mainly meant to be derived for aggregate types (see the `IsEmpty` derive macro), where
/// a value is empty when all of its fields are empty. Note that the derive emits no bounds: a
/// generic parameter is only usable when its own type implements `IsEmpty` independently. Arrays
/// are rejected: their slice `is_empty` is always `false`, which would silently make the whole
/// struct permanently non-empty. Deriving it instead of writing `is_empty` by
/// hand means a newly added field can't be silently left out of the check.
pub trait IsEmpty {
/// Returns `true` if the value is empty.
fn is_empty(&self) -> bool;
}

#[cfg(test)]
mod tests {
use std::collections::BTreeMap;

use super::*;

#[derive(IsEmpty)]
struct Aggregate {
a: BTreeMap<u32, u32>,
b: Vec<u32>,
c: String,
}

#[test]
fn empty_when_all_fields_are_empty() {
let value = Aggregate {
a: BTreeMap::new(),
b: Vec::new(),
c: String::new(),
};
assert!(value.is_empty());
}

#[test]
fn not_empty_when_any_field_is_not_empty() {
let with_map = Aggregate {
a: BTreeMap::from([(1, 1)]),
b: Vec::new(),
c: String::new(),
};
assert!(!with_map.is_empty());

let with_vec = Aggregate {
a: BTreeMap::new(),
b: vec![1],
c: String::new(),
};
assert!(!with_vec.is_empty());

let with_string = Aggregate {
a: BTreeMap::new(),
b: Vec::new(),
c: "x".to_owned(),
};
assert!(!with_string.is_empty());
}

#[test]
fn nested_derived_field_resolves_through_the_trait() {
#[derive(IsEmpty)]
struct Inner {
items: Vec<u32>,
}

#[derive(IsEmpty)]
struct Outer {
inner: Inner,
label: String,
}

assert!(
Outer {
inner: Inner { items: Vec::new() },
label: String::new()
}
.is_empty()
);
assert!(
!Outer {
inner: Inner { items: vec![1] },
label: String::new()
}
.is_empty()
);
assert!(
!Outer {
inner: Inner { items: Vec::new() },
label: "x".to_owned()
}
.is_empty()
);
}

#[test]
fn tuple_struct_is_empty_uses_all_fields() {
#[derive(IsEmpty)]
struct Pair(Vec<u32>, String);

assert!(Pair(Vec::new(), String::new()).is_empty());
assert!(!Pair(vec![1], String::new()).is_empty());
}

#[test]
fn unit_struct_is_always_empty() {
#[derive(IsEmpty)]
struct Unit;

assert!(Unit.is_empty());
}

// The generated impl names the trait by its full path, so deriving through a path qualified
// macro works without the trait being imported, and picks the right trait even if another one
// of the same name happens to be in scope.
mod trait_not_in_scope {
// Deliberately not importing the trait here.

#[derive(super::super::IsEmpty)]
struct Aggregate {
a: Vec<u32>,
}

// A decoy that would be picked up if the generated impl named the trait unqualified.
// It is never implemented or called on purpose; see the test below.
#[allow(dead_code)]
trait IsEmpty {
fn is_empty(&self) -> bool;
}

fn assert_impls<T: crate::IsEmpty>(value: &T) -> bool {
value.is_empty()
}

#[test]
fn derives_the_trait_from_its_own_crate() {
assert!(assert_impls(&Aggregate { a: Vec::new() }));
assert!(!assert_impls(&Aggregate { a: vec![1] }));
}
}
}
Loading