use std::sync::Arc;
use chia_bls::Signature;
use chia_protocol::{Bytes32, CoinSpend, SpendBundle};
use dig_chainsource_interface::ChainSource;
use dig_merkle::{required_signatures, Datastore, DigDataStoreMetadata, Owner, RequiredSignature};
use dig_social_profile::slot::standard::SCHEMA_VERSION;
use dig_social_profile::{Profile, SlotEdit, VerifiedBody};
use crate::id::ProfileIx;
use crate::keys::wallet_key::WalletKey;
use crate::mint::chain::{PushOutcome, SpendPublisher};
use crate::mint::did::MintNetwork;
use crate::registry::ProfileAnchor;
use crate::session_residency::Residency;
use dig_session::UnlockedMasterSeed;
use super::batch::ProfileEdit;
use super::content::ProfileContentSource;
use super::error::{EditError, EditResult};
use super::read::{read_profile, resolve_store_tip};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EditStatus {
Pushed {
new_root: [u8; 32],
},
Confirmed {
root: [u8; 32],
},
}
impl EditStatus {
pub fn confirmed_root(&self) -> Option<[u8; 32]> {
match self {
Self::Confirmed { root } => Some(*root),
Self::Pushed { .. } => None,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CommittedEdit {
status: EditStatus,
body: Vec<u8>,
}
impl CommittedEdit {
pub fn status(&self) -> &EditStatus {
&self.status
}
pub fn body_bytes(&self) -> &[u8] {
&self.body
}
pub fn root(&self) -> [u8; 32] {
match self.status {
EditStatus::Pushed { new_root } => new_root,
EditStatus::Confirmed { root } => root,
}
}
pub fn into_parts(self) -> (EditStatus, Vec<u8>) {
(self.status, self.body)
}
}
pub struct ProfileEditor {
seed: Arc<UnlockedMasterSeed>,
residency: Arc<Residency>,
}
impl ProfileEditor {
pub(crate) fn new(seed: Arc<UnlockedMasterSeed>, residency: Arc<Residency>) -> Self {
Self { seed, residency }
}
pub fn edit_status<C>(
&self,
anchor: &ProfileAnchor,
new_root: [u8; 32],
chain: &C,
) -> EditResult<EditStatus>
where
C: ChainSource + ?Sized,
{
let anchored: [u8; 32] = resolve_store_tip(anchor, chain)?
.info
.metadata
.root_hash
.into();
if anchored == new_root {
Ok(EditStatus::Confirmed { root: anchored })
} else {
Ok(EditStatus::Pushed { new_root })
}
}
#[allow(
clippy::too_many_arguments,
reason = "each argument is a distinct authority"
)]
pub fn commit_edit<C, S, P>(
&self,
ix: ProfileIx,
anchor: &ProfileAnchor,
edit: &ProfileEdit,
chain: &C,
content: &S,
publisher: &P,
network: &MintNetwork,
) -> EditResult<CommittedEdit>
where
C: ChainSource + ?Sized,
S: ProfileContentSource + ?Sized,
P: SpendPublisher + ?Sized,
{
if edit.is_empty() {
return Err(EditError::Refused(
"an empty edit commits the root the store already has".into(),
));
}
reject_protected_removals(edit)?;
let wallet = self.live_wallet_key(ix)?;
let snapshot = read_profile(anchor, chain, content)?;
let mut next = snapshot.content().clone();
next.apply_all(edit.slot_edits());
let next_body = VerifiedBody::from_profile(&next)
.map_err(|e| EditError::Format(format!("edited profile body: {e}")))?;
let new_root = next_body.root();
let body = next_body.as_bytes().to_vec();
if new_root == snapshot.root() {
return Ok(CommittedEdit {
status: EditStatus::Confirmed { root: new_root },
body,
});
}
let bundle = self.build_and_sign_update(anchor, &wallet, new_root, chain, network)?;
match publisher
.push(&bundle)
.map_err(|e| EditError::ChainUnreachable(e.to_string()))?
{
PushOutcome::Accepted | PushOutcome::AlreadyInMempool => Ok(CommittedEdit {
status: EditStatus::Pushed { new_root },
body,
}),
PushOutcome::Rejected { reason } => Err(EditError::Rejected(reason)),
}
}
#[allow(
clippy::too_many_arguments,
reason = "each argument is a distinct authority"
)]
pub fn publish_profile<C, P>(
&self,
ix: ProfileIx,
anchor: &ProfileAnchor,
profile: &Profile,
chain: &C,
publisher: &P,
network: &MintNetwork,
) -> EditResult<CommittedEdit>
where
C: ChainSource + ?Sized,
P: SpendPublisher + ?Sized,
{
reject_profile_without_schema_version(profile)?;
let wallet = self.live_wallet_key(ix)?;
let next_body = VerifiedBody::from_profile(profile)
.map_err(|e| EditError::Format(format!("published profile body: {e}")))?;
let new_root = next_body.root();
let body = next_body.as_bytes().to_vec();
let store = resolve_store_tip(anchor, chain)?;
let anchored: [u8; 32] = store.info.metadata.root_hash.into();
if anchored == new_root {
return Ok(CommittedEdit {
status: EditStatus::Confirmed { root: new_root },
body,
});
}
let bundle = self.build_and_sign_update(anchor, &wallet, new_root, chain, network)?;
match publisher
.push(&bundle)
.map_err(|e| EditError::ChainUnreachable(e.to_string()))?
{
PushOutcome::Accepted | PushOutcome::AlreadyInMempool => Ok(CommittedEdit {
status: EditStatus::Pushed { new_root },
body,
}),
PushOutcome::Rejected { reason } => Err(EditError::Rejected(reason)),
}
}
fn build_and_sign_update<C>(
&self,
anchor: &ProfileAnchor,
wallet: &WalletKey,
new_root: [u8; 32],
chain: &C,
network: &MintNetwork,
) -> EditResult<SpendBundle>
where
C: ChainSource + ?Sized,
{
let store = resolve_store_tip(anchor, chain)?;
gate_store_identity(wallet, anchor.store_launcher_id(), &store)?;
let metadata = DigDataStoreMetadata {
root_hash: Bytes32::new(new_root),
..store.info.metadata.clone()
};
let update =
dig_merkle::update_root(&store, Owner::Standard(wallet.public_key()), metadata)
.map_err(|e| EditError::Build(format!("store update: {e}")))?;
let coin_spends = update.coin_spends;
let required = required_signatures(&coin_spends, network.constants())
.map_err(|e| EditError::Build(format!("required signatures: {e}")))?;
gate_edit(wallet, &store, &coin_spends, &required, network)?;
let mut signature = Signature::default();
for requirement in &required {
let RequiredSignature::Bls(bls) = requirement else {
return Err(EditError::Refused(
"non-BLS signature requirement in a profile edit".into(),
));
};
signature += &chia_bls::sign(wallet.secret_key(), bls.message());
}
Ok(SpendBundle::new(coin_spends, signature))
}
fn live_wallet_key(&self, ix: ProfileIx) -> EditResult<WalletKey> {
if !self.residency.is_live() {
return Err(EditError::Locked);
}
Ok(WalletKey::from_seed_at(
self.seed.master_seed().as_ref(),
ix,
))
}
}
fn reject_profile_without_schema_version(profile: &Profile) -> EditResult<()> {
if profile.schema_version().is_none() {
return Err(EditError::Refused(
"a published profile may not be without its schema version".into(),
));
}
Ok(())
}
fn reject_protected_removals(edit: &ProfileEdit) -> EditResult<()> {
let removes_schema_version = edit
.slot_edits()
.iter()
.any(|change| matches!(change, SlotEdit::Remove(slot) if *slot == SCHEMA_VERSION));
if removes_schema_version {
return Err(EditError::Refused(
"a published profile may not be without its schema version".into(),
));
}
Ok(())
}
pub(crate) fn gate_store_identity(
wallet: &WalletKey,
expected_launcher_id: Bytes32,
store: &Datastore<DigDataStoreMetadata>,
) -> EditResult<()> {
if store.info.owner_puzzle_hash != wallet.puzzle_hash() {
return Err(EditError::Refused(
"the store to be recreated is owned by a puzzle hash this profile does not hold".into(),
));
}
if store.info.launcher_id != expected_launcher_id {
return Err(EditError::Refused(
"the store to be recreated is not the singleton this profile's anchor names".into(),
));
}
if !store.info.delegated_puzzles.is_empty() {
return Err(EditError::Refused(
"the store to be recreated carries delegated puzzles, which a DIG profile store never has"
.into(),
));
}
Ok(())
}
fn gate_edit(
wallet: &WalletKey,
store: &Datastore<DigDataStoreMetadata>,
coin_spends: &[CoinSpend],
required: &[RequiredSignature],
network: &MintNetwork,
) -> EditResult<()> {
match coin_spends {
[only] if only.coin == store.coin => {}
[_] => {
return Err(EditError::Refused(
"the edit spends a coin that is not the store tip it was built from".into(),
))
}
_ => {
return Err(EditError::Refused(format!(
"the edit's bundle spends {} coins; an edit recreates exactly one singleton",
coin_spends.len()
)))
}
}
for requirement in required {
let RequiredSignature::Bls(bls) = requirement else {
return Err(EditError::Refused(
"an edit signs only BLS AGG_SIG_ME requirements".into(),
));
};
if bls.public_key != wallet.public_key() {
return Err(EditError::Refused(
"the edit asks for a signature under a key this profile does not hold".into(),
));
}
if bls.domain_string != Some(network.constants().me()) {
return Err(EditError::Refused(
"a signature that is not AGG_SIG_ME (an edit never signs an unbound message)"
.into(),
));
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use chia_protocol::{Coin, Program};
use chia_wallet_sdk::prelude::TESTNET11_CONSTANTS;
use chia_wallet_sdk::signer::{AggSigConstants, RequiredBlsSignature};
use dig_merkle::{DatastoreInfo, DelegatedPuzzle, LineageProof, Proof};
const SEED: [u8; 32] = [0x5A; 32];
const OTHER_SEED: [u8; 32] = [0xA5; 32];
fn network() -> MintNetwork {
MintNetwork::from_constants(AggSigConstants::from(&*TESTNET11_CONSTANTS))
}
fn wallet() -> WalletKey {
WalletKey::from_seed_at(&SEED, ProfileIx::ROOT)
}
const LAUNCHER_ID: Bytes32 = Bytes32::new([0x7E; 32]);
fn hydrated_store(
owner: Bytes32,
launcher_id: Bytes32,
delegated_puzzles: Vec<DelegatedPuzzle>,
) -> Datastore<DigDataStoreMetadata> {
Datastore {
coin: Coin::new(Bytes32::new([1; 32]), Bytes32::new([2; 32]), 1),
proof: Proof::Lineage(LineageProof {
parent_parent_coin_info: Bytes32::new([3; 32]),
parent_inner_puzzle_hash: Bytes32::new([4; 32]),
parent_amount: 1,
}),
info: DatastoreInfo {
launcher_id,
metadata: DigDataStoreMetadata {
root_hash: Bytes32::new([5; 32]),
..Default::default()
},
owner_puzzle_hash: owner,
delegated_puzzles,
},
}
}
#[test]
fn this_profiles_own_store_clears_the_identity_gate() {
let wallet = wallet();
let store = hydrated_store(wallet.puzzle_hash(), LAUNCHER_ID, Vec::new());
gate_store_identity(&wallet, LAUNCHER_ID, &store)
.expect("the profile's own store is edited");
}
#[test]
fn a_store_owned_by_another_puzzle_hash_is_refused() {
let stranger = WalletKey::from_seed_at(&OTHER_SEED, ProfileIx::ROOT);
let store = hydrated_store(stranger.puzzle_hash(), LAUNCHER_ID, Vec::new());
let error = gate_store_identity(&wallet(), LAUNCHER_ID, &store)
.expect_err("an edit never recreates a singleton at a stranger's puzzle hash");
assert!(
error
.to_string()
.contains("owned by a puzzle hash this profile does not hold"),
"{error}"
);
}
#[test]
fn a_store_that_is_not_the_anchored_singleton_is_refused() {
let wallet = wallet();
let store = hydrated_store(wallet.puzzle_hash(), Bytes32::new([0x0B; 32]), Vec::new());
let error = gate_store_identity(&wallet, LAUNCHER_ID, &store)
.expect_err("an edit commits to the singleton the anchor names");
assert!(
error.to_string().contains("this profile's anchor names"),
"{error}"
);
}
#[test]
fn a_store_carrying_delegated_puzzles_is_refused() {
let wallet = wallet();
let store = hydrated_store(
wallet.puzzle_hash(),
LAUNCHER_ID,
vec![DelegatedPuzzle::Admin(Bytes32::new([9; 32]).into())],
);
let error = gate_store_identity(&wallet, LAUNCHER_ID, &store)
.expect_err("a DIG profile store never carries delegated puzzles");
assert!(error.to_string().contains("delegated puzzles"), "{error}");
}
#[test]
fn a_bundle_spending_more_than_the_store_tip_is_refused() {
let wallet = wallet();
let store = hydrated_store(wallet.puzzle_hash(), LAUNCHER_ID, Vec::new());
let spends = vec![
CoinSpend::new(store.coin, Program::default(), Program::default()),
CoinSpend::new(
Coin::new(Bytes32::new([8; 32]), wallet.puzzle_hash(), 1_000),
Program::default(),
Program::default(),
),
];
let error = gate_edit(&wallet, &store, &spends, &[], &network())
.expect_err("an edit signs exactly one coin spend");
assert!(error.to_string().contains("spends 2 coins"), "{error}");
}
#[test]
fn a_bundle_spending_some_other_coin_is_refused() {
let wallet = wallet();
let store = hydrated_store(wallet.puzzle_hash(), LAUNCHER_ID, Vec::new());
let spends = vec![CoinSpend::new(
Coin::new(Bytes32::new([8; 32]), wallet.puzzle_hash(), 1_000),
Program::default(),
Program::default(),
)];
let error = gate_edit(&wallet, &store, &spends, &[], &network())
.expect_err("an edit signs only the store tip it was built from");
assert!(error.to_string().contains("not the store tip"), "{error}");
}
fn spends_of(store: &Datastore<DigDataStoreMetadata>) -> Vec<CoinSpend> {
vec![CoinSpend::new(
store.coin,
Program::default(),
Program::default(),
)]
}
fn requirement(
key: chia_bls::PublicKey,
domain_string: Option<Bytes32>,
) -> Vec<RequiredSignature> {
vec![RequiredSignature::Bls(RequiredBlsSignature {
public_key: key,
raw_message: vec![1, 2, 3].into(),
appended_info: Vec::new(),
domain_string,
})]
}
#[test]
fn this_profiles_own_agg_sig_me_requirement_passes_the_gate() {
let wallet = wallet();
let store = hydrated_store(wallet.puzzle_hash(), LAUNCHER_ID, Vec::new());
let required = requirement(wallet.public_key(), Some(network().constants().me()));
gate_edit(&wallet, &store, &spends_of(&store), &required, &network())
.expect("an edit's own bound requirement is signed");
}
#[test]
fn an_unsafe_unbound_signature_requirement_is_refused() {
let wallet = wallet();
let store = hydrated_store(wallet.puzzle_hash(), LAUNCHER_ID, Vec::new());
let required = requirement(wallet.public_key(), None);
let error = gate_edit(&wallet, &store, &spends_of(&store), &required, &network())
.expect_err("an edit never signs an unbound message");
assert!(error.to_string().contains("AGG_SIG_ME"), "{error}");
}
#[test]
fn a_requirement_bound_to_another_network_is_refused() {
let wallet = wallet();
let store = hydrated_store(wallet.puzzle_hash(), LAUNCHER_ID, Vec::new());
let required = requirement(wallet.public_key(), Some(Bytes32::new([0x11; 32])));
let error = gate_edit(&wallet, &store, &spends_of(&store), &required, &network())
.expect_err("an edit signs only for the network it is committing on");
assert!(error.to_string().contains("AGG_SIG_ME"), "{error}");
}
#[test]
fn a_signature_under_another_key_is_refused() {
let stranger = WalletKey::from_seed_at(&OTHER_SEED, ProfileIx::ROOT);
let store = hydrated_store(wallet().puzzle_hash(), LAUNCHER_ID, Vec::new());
let required = requirement(stranger.public_key(), Some(network().constants().me()));
let error = gate_edit(&wallet(), &store, &spends_of(&store), &required, &network())
.expect_err("only this profile's own key signs");
assert!(
error.to_string().contains("this profile does not hold"),
"{error}"
);
}
}