use anyhow::anyhow;
use penumbra_proto::{core::component::sct::v1 as pb, DomainType};
use serde::{Deserialize, Serialize};
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[serde(try_from = "pb::CommitmentSource", into = "pb::CommitmentSource")]
pub enum CommitmentSource {
Genesis,
Transaction {
id: Option<[u8; 32]>,
},
FundingStreamReward { epoch_index: u64 },
CommunityPoolOutput,
Ics20Transfer {
packet_seq: u64,
channel_id: String,
sender: String,
},
}
impl DomainType for CommitmentSource {
type Proto = pb::CommitmentSource;
}
impl CommitmentSource {
pub fn transaction() -> Self {
CommitmentSource::Transaction { id: None }
}
pub fn stripped(&self) -> Self {
match self {
CommitmentSource::Transaction { .. } => CommitmentSource::Transaction { id: None },
x => x.clone(),
}
}
pub fn id(&self) -> Option<[u8; 32]> {
match self {
CommitmentSource::Transaction { id: Some(id) } => Some(*id),
_ => None,
}
}
}
impl From<CommitmentSource> for pb::CommitmentSource {
fn from(value: CommitmentSource) -> Self {
use pb::commitment_source::{self as pbcs, Source};
Self {
source: Some(match value {
CommitmentSource::Genesis => Source::Genesis(pbcs::Genesis {}),
CommitmentSource::Transaction { id } => Source::Transaction(pbcs::Transaction {
id: id.map(|bytes| bytes.to_vec()).unwrap_or_default(),
}),
CommitmentSource::FundingStreamReward { epoch_index } => {
Source::FundingStreamReward(pbcs::FundingStreamReward { epoch_index })
}
CommitmentSource::CommunityPoolOutput => {
Source::CommunityPoolOutput(pbcs::CommunityPoolOutput {})
}
CommitmentSource::Ics20Transfer {
packet_seq,
channel_id,
sender,
} => Source::Ics20Transfer(pbcs::Ics20Transfer {
packet_seq,
channel_id,
sender,
}),
}),
}
}
}
impl TryFrom<pb::CommitmentSource> for CommitmentSource {
type Error = anyhow::Error;
fn try_from(value: pb::CommitmentSource) -> Result<Self, Self::Error> {
use pb::commitment_source::Source;
let source = value.source.ok_or_else(|| anyhow!("missing source"))?;
Ok(match source {
Source::Genesis(_) => Self::Genesis,
Source::CommunityPoolOutput(_) => Self::CommunityPoolOutput,
Source::FundingStreamReward(x) => Self::FundingStreamReward {
epoch_index: x.epoch_index,
},
Source::Transaction(x) => {
if x.id.is_empty() {
Self::Transaction { id: None }
} else {
Self::Transaction {
id: Some(x.id.try_into().map_err(|id: Vec<u8>| {
anyhow!("expected 32-byte id array, got {} bytes", id.len())
})?),
}
}
}
Source::Ics20Transfer(x) => Self::Ics20Transfer {
packet_seq: x.packet_seq,
channel_id: x.channel_id,
sender: x.sender,
},
})
}
}