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

Use hex_debug, skip_if and custom_derive_debug where appropriate. #2884

Merged
merged 1 commit into from
Nov 13, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 3 additions & 0 deletions Cargo.lock

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

3 changes: 3 additions & 0 deletions examples/Cargo.lock

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

52 changes: 22 additions & 30 deletions linera-base/src/data_types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -675,6 +675,11 @@ impl Amount {
pub fn saturating_div(self, other: Amount) -> u128 {
self.0.checked_div(other.0).unwrap_or(u128::MAX)
}

/// Returns whether this amount is 0.
pub fn is_zero(&self) -> bool {
*self == Amount::ZERO
}
}

/// Permissions for applications on a chain.
Expand All @@ -696,13 +701,16 @@ pub struct ApplicationPermissions {
/// If this is `None`, all system operations and application operations are allowed.
/// If it is `Some`, only operations from the specified applications are allowed, and
/// no system operations.
#[debug(skip_if = Option::is_none)]
pub execute_operations: Option<Vec<ApplicationId>>,
/// At least one operation or incoming message from each of these applications must occur in
/// every block.
#[graphql(default)]
#[debug(skip_if = Vec::is_empty)]
pub mandatory_applications: Vec<ApplicationId>,
/// These applications are allowed to close the current chain using the system API.
#[graphql(default)]
#[debug(skip_if = Vec::is_empty)]
pub close_chain: Vec<ApplicationId>,
}

Expand Down Expand Up @@ -736,9 +744,9 @@ impl ApplicationPermissions {
#[derive(Debug, PartialEq, Eq, Hash, Clone, Serialize, Deserialize)]
pub enum OracleResponse {
/// The response from a service query.
Service(Vec<u8>),
Service(#[debug(with = "hex_debug")] Vec<u8>),
/// The response from an HTTP POST request.
Post(Vec<u8>),
Post(#[debug(with = "hex_debug")] Vec<u8>),
/// A successful read or write of a blob.
Blob(BlobId),
/// An assertion oracle that passed.
Expand Down Expand Up @@ -815,10 +823,11 @@ impl From<&UserApplicationDescription> for UserApplicationId {
}

/// A WebAssembly module's bytecode.
#[derive(Clone, Deserialize, Eq, Hash, PartialEq, Serialize)]
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, Serialize)]
pub struct Bytecode {
/// Bytes of the bytecode.
#[serde(with = "serde_bytes")]
#[debug(with = "hex_debug")]
pub bytes: Vec<u8>,
}

Expand Down Expand Up @@ -852,12 +861,6 @@ impl AsRef<[u8]> for Bytecode {
}
}

impl fmt::Debug for Bytecode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
f.debug_struct("Bytecode").finish_non_exhaustive()
}
}

/// A type for errors happening during decompression.
#[derive(Error, Debug)]
pub enum DecompressionError {
Expand All @@ -867,11 +870,12 @@ pub enum DecompressionError {
}

/// A compressed WebAssembly module's bytecode.
#[derive(Clone, Deserialize, Hash, Serialize, WitType, WitStore)]
#[derive(Clone, Debug, Deserialize, Hash, Serialize, WitType, WitStore)]
#[cfg_attr(with_testing, derive(Eq, PartialEq))]
pub struct CompressedBytecode {
/// Compressed bytes of the bytecode.
#[serde(with = "serde_bytes")]
#[debug(with = "hex_debug")]
pub compressed_bytes: Vec<u8>,
}

Expand Down Expand Up @@ -943,12 +947,6 @@ impl CompressedBytecode {
}
}

impl fmt::Debug for CompressedBytecode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("CompressedBytecode").finish_non_exhaustive()
}
}

/// Internal bytes of a blob.
#[derive(Clone, Serialize, Deserialize, WitType, WitStore)]
#[cfg_attr(with_testing, derive(Eq, PartialEq))]
Expand All @@ -964,25 +962,19 @@ impl Hash for BlobBytes {
}

/// A blob of binary data.
#[derive(Hash, Clone, Serialize, Deserialize, WitType, WitStore)]
#[derive(Hash, Clone, Debug, Serialize, Deserialize, WitType, WitStore)]
#[cfg_attr(with_testing, derive(Eq, PartialEq))]
pub enum BlobContent {
/// A generic data blob.
Data(#[serde(with = "serde_bytes")] Vec<u8>),
Data(
#[serde(with = "serde_bytes")]
#[debug(skip)]
Vec<u8>,
),
/// A blob containing contract bytecode.
ContractBytecode(CompressedBytecode),
ContractBytecode(#[debug(skip)] CompressedBytecode),
/// A blob containing service bytecode.
ServiceBytecode(CompressedBytecode),
}

impl fmt::Debug for BlobContent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
BlobContent::Data(_) => write!(f, "BlobContent::Data"),
BlobContent::ContractBytecode(_) => write!(f, "BlobContent::ContractBytecode"),
BlobContent::ServiceBytecode(_) => write!(f, "BlobContent::ServiceBytecode"),
}
}
ServiceBytecode(#[debug(skip)] CompressedBytecode),
}

impl BlobContent {
Expand Down
52 changes: 17 additions & 35 deletions linera-base/src/identifiers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,23 @@
//! Core identifiers used by the Linera protocol.

use std::{
fmt::{self, Debug, Display, Formatter},
fmt::{self, Display, Formatter},
hash::{Hash, Hasher},
marker::PhantomData,
str::FromStr,
};

use anyhow::{anyhow, Context};
use async_graphql::SimpleObject;
use custom_debug_derive::Debug;
use linera_witty::{WitLoad, WitStore, WitType};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::{
bcs_scalar,
crypto::{BcsHashable, CryptoError, CryptoHash, PublicKey},
data_types::{BlobContent, BlockHeight},
doc_scalar,
doc_scalar, hex_debug,
};

/// The owner of a chain. This is currently the hash of the owner's public key used to
Expand All @@ -45,6 +46,7 @@ pub struct Account {
/// The chain of the account.
pub chain_id: ChainId,
/// The owner of the account, or `None` for the chain balance.
#[debug(skip_if = Option::is_none)]
pub owner: Option<Owner>,
}

Expand Down Expand Up @@ -301,7 +303,7 @@ pub struct MessageId {
}

/// A unique identifier for a user application.
#[derive(WitLoad, WitStore, WitType)]
#[derive(Debug, WitLoad, WitStore, WitType)]
#[cfg_attr(with_testing, derive(Default))]
pub struct ApplicationId<A = ()> {
/// The bytecode to use for the application.
Expand Down Expand Up @@ -355,14 +357,15 @@ impl From<ApplicationId> for GenericApplicationId {
}

/// A unique identifier for an application bytecode.
#[derive(WitLoad, WitStore, WitType)]
#[derive(Debug, WitLoad, WitStore, WitType)]
#[cfg_attr(with_testing, derive(Default))]
pub struct BytecodeId<Abi = (), Parameters = (), InstantiationArgument = ()> {
/// The hash of the blob containing the contract bytecode.
pub contract_blob_hash: CryptoHash,
/// The hash of the blob containing the service bytecode.
pub service_blob_hash: CryptoHash,
#[witty(skip)]
#[debug(skip)]
_phantom: PhantomData<(Abi, Parameters, InstantiationArgument)>,
}

Expand All @@ -381,7 +384,11 @@ pub struct BytecodeId<Abi = (), Parameters = (), InstantiationArgument = ()> {
WitStore,
WitType,
)]
pub struct ChannelName(#[serde(with = "serde_bytes")] Vec<u8>);
pub struct ChannelName(
#[serde(with = "serde_bytes")]
#[debug(with = "hex_debug")]
Vec<u8>,
);

/// The name of an event stream.
#[derive(
Expand All @@ -398,7 +405,11 @@ pub struct ChannelName(#[serde(with = "serde_bytes")] Vec<u8>);
WitStore,
WitType,
)]
pub struct StreamName(#[serde(with = "serde_bytes")] pub Vec<u8>);
pub struct StreamName(
#[serde(with = "serde_bytes")]
#[debug(with = "hex_debug")]
pub Vec<u8>,
);

/// An event stream ID.
#[derive(
Expand Down Expand Up @@ -559,22 +570,6 @@ impl<Abi, Parameters, InstantiationArgument> Hash
}
}

impl<Abi, Parameters, InstantiationArgument> Debug
for BytecodeId<Abi, Parameters, InstantiationArgument>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let BytecodeId {
contract_blob_hash: contract_blob_id,
service_blob_hash: service_blob_id,
_phantom,
} = self;
f.debug_struct("BytecodeId")
.field("contract_blob_id", contract_blob_id)
.field("service_blob_id", service_blob_id)
.finish_non_exhaustive()
}
}

#[derive(Serialize, Deserialize)]
#[serde(rename = "BytecodeId")]
struct SerializableBytecodeId {
Expand Down Expand Up @@ -731,19 +726,6 @@ impl<A> Hash for ApplicationId<A> {
}
}

impl<A> Debug for ApplicationId<A> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let ApplicationId {
bytecode_id,
creation,
} = self;
f.debug_struct("ApplicationId")
.field("bytecode_id", bytecode_id)
.field("creation", creation)
.finish()
}
}

#[derive(Serialize, Deserialize)]
#[serde(rename = "ApplicationId")]
struct SerializableApplicationId {
Expand Down
39 changes: 38 additions & 1 deletion linera-base/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
#![deny(missing_docs)]
#![deny(clippy::large_futures)]

use std::fmt;

#[doc(hidden)]
pub use async_trait::async_trait;

Expand Down Expand Up @@ -93,7 +95,7 @@ macro_rules! ensure {
/// "Message { bytes: 20202020202020203130202020202020..20202020343020202020202020203530 }"
/// );
/// ```
pub fn hex_debug<T: AsRef<[u8]>>(bytes: &T, f: &mut std::fmt::Formatter) -> std::fmt::Result {
pub fn hex_debug<T: AsRef<[u8]>>(bytes: &T, f: &mut fmt::Formatter) -> fmt::Result {
const ELIDE_AFTER: usize = 16;
let bytes = bytes.as_ref();
if bytes.len() <= 2 * ELIDE_AFTER {
Expand All @@ -108,3 +110,38 @@ pub fn hex_debug<T: AsRef<[u8]>>(bytes: &T, f: &mut std::fmt::Formatter) -> std:
}
Ok(())
}

/// Applies `hex_debug` to a slice of byte vectors.
///
/// # Examples
///
/// ```
/// # use linera_base::hex_vec_debug;
/// use custom_debug_derive::Debug;
///
/// #[derive(Debug)]
/// struct Messages {
/// #[debug(with = "hex_vec_debug")]
/// byte_vecs: Vec<Vec<u8>>,
/// }
///
/// let msgs = Messages {
/// byte_vecs: vec![vec![0x12, 0x34, 0x56, 0x78], vec![0x9A]],
/// };
///
/// assert_eq!(
/// format!("{:?}", msgs),
/// "Messages { byte_vecs: [12345678, 9a] }"
/// );
/// ```
#[allow(clippy::ptr_arg)] // This only works with custom_debug_derive if it's &Vec.
pub fn hex_vec_debug(list: &Vec<Vec<u8>>, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[")?;
for (i, bytes) in list.iter().enumerate() {
if i != 0 {
write!(f, ", ")?;
}
hex_debug(bytes, f)?;
}
write!(f, "]")
}
4 changes: 4 additions & 0 deletions linera-base/src/ownership.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

use std::{collections::BTreeMap, iter};

use custom_debug_derive::Debug;
use linera_witty::{WitLoad, WitStore, WitType};
use serde::{Deserialize, Serialize};
use thiserror::Error;
Expand All @@ -21,6 +22,7 @@ use crate::{
#[derive(PartialEq, Eq, Clone, Hash, Debug, Serialize, Deserialize, WitLoad, WitStore, WitType)]
pub struct TimeoutConfig {
/// The duration of the fast round.
#[debug(skip_if = Option::is_none)]
pub fast_round_duration: Option<TimeDelta>,
/// The duration of the first single-leader and all multi-leader rounds.
pub base_timeout: TimeDelta,
Expand Down Expand Up @@ -48,8 +50,10 @@ impl Default for TimeoutConfig {
)]
pub struct ChainOwnership {
/// Super owners can propose fast blocks in the first round, and regular blocks in any round.
#[debug(skip_if = BTreeMap::is_empty)]
pub super_owners: BTreeMap<Owner, PublicKey>,
/// The regular owners, with their weights that determine how often they are round leader.
#[debug(skip_if = BTreeMap::is_empty)]
pub owners: BTreeMap<Owner, (PublicKey, u64)>,
/// The number of initial rounds after 0 in which all owners are allowed to propose blocks.
pub multi_leader_rounds: u32,
Expand Down
Loading
Loading