Skip to content

Commit

Permalink
BFT-457: Generic read_map
Browse files Browse the repository at this point in the history
  • Loading branch information
aakoshh committed Jun 12, 2024
1 parent 2856fbe commit b5b3c64
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 14 deletions.
20 changes: 20 additions & 0 deletions node/libs/protobuf/src/proto_fmt.rs
Original file line number Diff line number Diff line change
Expand Up @@ -285,6 +285,26 @@ pub fn read_optional<T: ProtoFmt>(field: &Option<T::Proto>) -> anyhow::Result<Op
field.as_ref().map(ProtoFmt::read).transpose()
}

/// Parses a repeated proto struct into a map.
pub fn read_map<T, K, V, F, G>(items: &[T], k: F, v: G) -> anyhow::Result<BTreeMap<K, V>>
where
K: ProtoFmt + Ord,
V: ProtoFmt,
F: Fn(&T) -> &Option<K::Proto>,
G: Fn(&T) -> &Option<V::Proto>,
{
let items: Vec<(K, V)> = items
.iter()
.map(|item| {
let k = read_required(k(item)).context("key")?;
let v = read_required(v(item)).context("value")?;
Ok((k, v))
})
.collect::<anyhow::Result<Vec<_>>>()?;

Ok(items.into_iter().collect())
}

/// Extracts a required field.
pub fn required<T>(field: &Option<T>) -> anyhow::Result<&T> {
field.as_ref().context("missing")
Expand Down
16 changes: 2 additions & 14 deletions node/libs/roles/src/attester/conv.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use crate::proto::attester::{self as proto, Attestation};
use anyhow::Context as _;
use zksync_consensus_crypto::ByteFmt;
use zksync_consensus_utils::enum_util::Variant;
use zksync_protobuf::{read_required, required, ProtoFmt};
use zksync_protobuf::{read_map, read_required, required, ProtoFmt};

impl ProtoFmt for Batch {
type Proto = proto::Batch;
Expand Down Expand Up @@ -132,21 +132,9 @@ impl ProtoFmt for BatchQC {
type Proto = proto::BatchQc;

fn read(r: &Self::Proto) -> anyhow::Result<Self> {
let signatures: Vec<(PublicKey, Signature)> = r
.signatures
.iter()
.map(|s| {
let key = read_required(&s.key).context("key")?;
let sig = read_required(&s.sig).context("sig")?;
Ok((key, sig))
})
.collect::<anyhow::Result<Vec<_>>>()?;

let signatures = signatures.into_iter().collect();

Ok(Self {
message: read_required(&r.msg).context("message")?,
signatures,
signatures: read_map(&r.signatures, |s| &s.key, |s| &s.sig).context("signatures")?,
})
}

Expand Down

0 comments on commit b5b3c64

Please sign in to comment.