use chia_protocol::Bytes32;
use dig_chainsource_interface::ChainSource;
use crate::registry::anchor::ProfileAnchor;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AnchorVerdict {
Verified,
Contradicted(String),
Unknown(String),
}
impl AnchorVerdict {
pub fn may_present(&self) -> bool {
!matches!(self, Self::Contradicted(_))
}
}
pub fn verify_anchor<C>(anchor: &ProfileAnchor, chain: &C) -> AnchorVerdict
where
C: ChainSource + ?Sized,
{
let did = confirm_coin(
chain,
anchor.did_coin_id(),
anchor.did_confirmed_height(),
"DID",
);
let store = match anchor.store_coin_id() {
Some(store_coin_id) => confirm_coin(
chain,
store_coin_id,
anchor.store_confirmed_height(),
"store",
),
None => Some(AnchorVerdict::Unknown(
"this anchor predates dig-account 0.22 and records no store coin, so its store half cannot be re-read"
.to_string(),
)),
};
match (did, store) {
(None, None) => AnchorVerdict::Verified,
(Some(disagreement @ AnchorVerdict::Contradicted(_)), _)
| (_, Some(disagreement @ AnchorVerdict::Contradicted(_))) => disagreement,
(Some(other), _) | (_, Some(other)) => other,
}
}
fn confirm_coin<C>(
chain: &C,
coin_id: Bytes32,
claimed_height: u32,
half: &str,
) -> Option<AnchorVerdict>
where
C: ChainSource + ?Sized,
{
let record = match chain.coin_record(coin_id) {
Ok(record) => record,
Err(e) => {
return Some(AnchorVerdict::Unknown(format!(
"the chain could not be asked about the {half} coin {coin_id}: {e}"
)))
}
};
let Some(record) = record else {
return Some(AnchorVerdict::Contradicted(format!(
"the {half} coin {coin_id} this profile names does not exist on chain"
)));
};
match record.confirmed_height {
None => Some(AnchorVerdict::Unknown(format!(
"this source knows the {half} coin {coin_id} but not the block it confirmed in"
))),
Some(height) if height != claimed_height => Some(AnchorVerdict::Contradicted(format!(
"the {half} coin {coin_id} confirmed at height {height}, but this profile claims \
{claimed_height}"
))),
Some(_) => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::mint::fixtures::bound_mint;
use chia_protocol::CoinSpend;
use dig_chainsource_interface::{CoinRecord, SingletonLineage};
use std::collections::HashMap;
#[derive(Default)]
struct CoinOracle {
heights: HashMap<Bytes32, Option<u32>>,
unreachable: bool,
}
impl CoinOracle {
fn confirmed(mut self, coin_id: Bytes32, height: u32) -> Self {
self.heights.insert(coin_id, Some(height));
self
}
fn height_unknown(mut self, coin_id: Bytes32) -> Self {
self.heights.insert(coin_id, None);
self
}
fn unreachable() -> Self {
Self {
unreachable: true,
..Self::default()
}
}
}
impl ChainSource for CoinOracle {
type Error = String;
fn coin_record(&self, coin_id: Bytes32) -> Result<Option<CoinRecord>, Self::Error> {
if self.unreachable {
return Err("connection refused".to_string());
}
Ok(self.heights.get(&coin_id).map(|height| CoinRecord {
coin: chia_protocol::Coin::new(Bytes32::new([0; 32]), Bytes32::new([0; 32]), 1),
confirmed_height: *height,
spent_height: None,
timestamp: None,
coinbase: false,
}))
}
fn coin_records_by_puzzle_hash(
&self,
_puzzle_hash: Bytes32,
_include_spent: bool,
) -> Result<Vec<CoinRecord>, Self::Error> {
Ok(Vec::new())
}
fn coin_records_by_parent(&self, _parent: Bytes32) -> Result<Vec<CoinRecord>, Self::Error> {
Ok(Vec::new())
}
fn coin_spend(&self, _coin_id: Bytes32) -> Result<Option<CoinSpend>, Self::Error> {
Ok(None)
}
fn resolve_singleton_lineage(
&self,
_launcher_id: Bytes32,
) -> Result<Option<SingletonLineage>, Self::Error> {
Err("not supported by this test double".to_string())
}
fn peak_height(&self) -> Result<Option<u32>, Self::Error> {
Ok(Some(u32::MAX))
}
fn block_timestamp(&self, _height: u32) -> Result<Option<u64>, Self::Error> {
Ok(None)
}
}
fn anchor() -> ProfileAnchor {
let (did, store) = bound_mint(3);
ProfileAnchor::from_confirmed(&did, &store).expect("the fixture halves are one mint")
}
fn store_coin(anchor: &ProfileAnchor) -> Bytes32 {
anchor
.store_coin_id()
.expect("an anchor built by this crate records its store coin")
}
fn agreeing(anchor: &ProfileAnchor) -> CoinOracle {
CoinOracle::default()
.confirmed(anchor.did_coin_id(), anchor.did_confirmed_height())
.confirmed(store_coin(anchor), anchor.store_confirmed_height())
}
#[test]
fn an_anchor_the_chain_agrees_with_verifies() {
let anchor = anchor();
assert_eq!(
verify_anchor(&anchor, &agreeing(&anchor)),
AnchorVerdict::Verified
);
}
#[test]
fn an_anchor_whose_store_coin_does_not_exist_is_contradicted() {
let anchor = anchor();
let chain =
CoinOracle::default().confirmed(anchor.did_coin_id(), anchor.did_confirmed_height());
let verdict = verify_anchor(&anchor, &chain);
assert!(
matches!(&verdict, AnchorVerdict::Contradicted(why) if why.contains("store")),
"a missing store coin must contradict the anchor, naming the half: {verdict:?}"
);
assert!(
!verdict.may_present(),
"a contradicted profile must not be shown"
);
}
#[test]
fn an_anchor_whose_did_coin_does_not_exist_is_contradicted() {
let anchor = anchor();
let chain =
CoinOracle::default().confirmed(store_coin(&anchor), anchor.store_confirmed_height());
let verdict = verify_anchor(&anchor, &chain);
assert!(
matches!(&verdict, AnchorVerdict::Contradicted(why) if why.contains("DID")),
"a DID coin that does not exist must contradict the anchor: {verdict:?}"
);
}
#[test]
fn an_anchor_whose_store_confirmed_at_another_height_is_contradicted() {
let anchor = anchor();
let chain = CoinOracle::default()
.confirmed(anchor.did_coin_id(), anchor.did_confirmed_height())
.confirmed(store_coin(&anchor), anchor.store_confirmed_height() + 1);
let verdict = verify_anchor(&anchor, &chain);
assert!(
matches!(&verdict, AnchorVerdict::Contradicted(why) if why.contains("store")),
"a height the chain disagrees with must contradict the anchor: {verdict:?}"
);
}
#[test]
fn an_unreachable_chain_yields_unknown_and_the_profile_stays_presentable() {
let verdict = verify_anchor(&anchor(), &CoinOracle::unreachable());
assert!(
matches!(verdict, AnchorVerdict::Unknown(_)),
"an unreachable source must not contradict anything: {verdict:?}"
);
assert!(verdict.may_present());
}
#[test]
fn a_contradiction_beats_a_non_answer_about_the_other_half() {
let anchor = anchor();
let chain = CoinOracle::default().height_unknown(anchor.did_coin_id());
let verdict = verify_anchor(&anchor, &chain);
assert!(
matches!(&verdict, AnchorVerdict::Contradicted(why) if why.contains("store")),
"the store coin does not exist and the source said so; an unreadable DID block must \
not hide that: {verdict:?}"
);
assert!(!verdict.may_present());
}
#[test]
fn a_contradicted_did_beats_a_non_answer_about_the_store() {
let anchor = anchor();
let chain = CoinOracle::default().height_unknown(store_coin(&anchor));
let verdict = verify_anchor(&anchor, &chain);
assert!(
matches!(&verdict, AnchorVerdict::Contradicted(why) if why.contains("DID")),
"the DID coin does not exist and the source said so: {verdict:?}"
);
}
#[test]
fn a_source_that_knows_the_coin_but_not_its_block_yields_unknown() {
let anchor = anchor();
let chain = CoinOracle::default()
.height_unknown(anchor.did_coin_id())
.confirmed(store_coin(&anchor), anchor.store_confirmed_height());
let verdict = verify_anchor(&anchor, &chain);
assert!(
matches!(verdict, AnchorVerdict::Unknown(_)),
"an unknown height is not a disagreement: {verdict:?}"
);
assert!(verdict.may_present());
}
#[test]
fn a_pre_0_22_anchor_is_unknown_rather_than_verified() {
let json = serde_json::to_value(anchor()).expect("an anchor always serializes");
let mut fields = json
.as_object()
.expect("an anchor is a JSON object")
.clone();
fields.remove("store_coin_id");
fields.remove("store_launched_from");
let old: ProfileAnchor =
serde_json::from_value(fields.into()).expect("a pre-0.22 anchor still deserializes");
assert_eq!(old.store_coin_id(), None);
let chain = CoinOracle::default().confirmed(old.did_coin_id(), old.did_confirmed_height());
let verdict = verify_anchor(&old, &chain);
assert!(
matches!(&verdict, AnchorVerdict::Unknown(why) if why.contains("0.22")),
"a half-checkable anchor is not a verified one: {verdict:?}"
);
assert!(verdict.may_present());
}
}