Skip to main content

clm_rust_core/cpn/
parameter_cards.rs

1//! Contract parameters as `PrimitivePCard` tokens under Function-Number Duality (INV-597).
2//!
3//! A parameter value of type `tau_p` is the constant morphism `1 -> tau_p`: it reifies to the
4//! `TokenMCard` bound at `urn:mcard:mcard:contract:param:<key>` and reflects back unchanged. A
5//! `ParameterContext` is the contract `NetMCard` whose marking holds one token per parameter; its
6//! digest is the context's identity, and the default context must digest to `CONTRACT_NET_DIGEST`.
7
8use std::collections::BTreeMap;
9
10use serde_json::Value;
11
12use crate::cpn::mcard_token::{reflect_mcard_to_pcard, reify_pcard_to_mcard, NetMCard, PrimitiveConstant, TokenMCard};
13use crate::layer0::parameter_context::{ParameterContext, ParameterValue, CONTRACT_NET_DIGEST, PARAMETER_TYPES};
14use crate::layer0::vocabulary::{HANDLE_CONTRACT_PARAM, HANDLE_CONTRACT_RUNTIME, HANDLE_VCARD_CONTRACT_PARAM};
15use crate::layer0::vocabulary_types::TYPE_URI_PARAM;
16
17/// Why a parameter card could not be reified, reflected, or verified.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub enum ParameterCardError {
20    /// The key names no contract parameter.
21    UnknownParameter(String),
22    /// The token is not bound under `urn:mcard:mcard:contract:param:`.
23    ForeignToken(String),
24    /// The token's type URI is not the parameter's refinement type.
25    WrongType { key: String, found: String },
26    /// The recomputed contract `NetMCard` digest differs from the compiled-in seed.
27    DigestMismatch(String),
28    /// The token envelope could not be built.
29    Reify(String),
30}
31
32impl std::fmt::Display for ParameterCardError {
33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
34        write!(f, "{self:?}")
35    }
36}
37
38impl std::error::Error for ParameterCardError {}
39
40/// `urn:mcard:mcard:contract:param:<key>`, the handle that binds the parameter's card.
41pub fn parameter_handle(key: &str) -> String {
42    HANDLE_CONTRACT_PARAM.to_string() + key
43}
44
45/// `urn:vcard:contract:param:<key>`, the VCard that guards the parameter's refinement.
46pub fn parameter_vcard_handle(key: &str) -> String {
47    HANDLE_VCARD_CONTRACT_PARAM.to_string() + key
48}
49
50fn type_uri(key: &str) -> Result<String, ParameterCardError> {
51    PARAMETER_TYPES
52        .iter()
53        .find(|(name, _)| *name == key)
54        .map(|(_, base)| TYPE_URI_PARAM.to_string() + base)
55        .ok_or_else(|| ParameterCardError::UnknownParameter(key.to_string()))
56}
57
58fn json_value(value: &ParameterValue) -> Value {
59    match value {
60        ParameterValue::Int(number) => Value::from(*number),
61        ParameterValue::Text(text) => Value::from(text.clone()),
62        ParameterValue::Bool(flag) => Value::from(*flag),
63    }
64}
65
66/// Phi: the parameter as the `TokenMCard` bound at its handle.
67pub fn reify_parameter(key: &str, value: &ParameterValue) -> Result<TokenMCard, ParameterCardError> {
68    let pcard = PrimitiveConstant { constant_value: json_value(value), output_type: type_uri(key)? };
69    reify_pcard_to_mcard(&pcard, &parameter_handle(key), None, None).map_err(ParameterCardError::Reify)
70}
71
72/// Psi: `(key, value)` from a parameter `TokenMCard`; rejects any other token.
73pub fn reflect_parameter(token: &TokenMCard) -> Result<(String, Value), ParameterCardError> {
74    let key = token
75        .token_id
76        .strip_prefix(HANDLE_CONTRACT_PARAM)
77        .ok_or_else(|| ParameterCardError::ForeignToken(token.token_id.clone()))?;
78    let pcard = reflect_mcard_to_pcard(token);
79    if pcard.output_type != type_uri(key)? {
80        return Err(ParameterCardError::WrongType { key: key.to_string(), found: pcard.output_type });
81    }
82    Ok((key.to_string(), pcard.constant_value))
83}
84
85/// The contract `NetMCard`: each parameter handle marks the token of its resolved value.
86pub fn contract_net_mcard(context: &ParameterContext) -> Result<NetMCard, ParameterCardError> {
87    let mut marking = BTreeMap::new();
88    for (key, value) in context.as_mapping() {
89        marking.insert(parameter_handle(key), vec![reify_parameter(key, &value)?]);
90    }
91    NetMCard::create(HANDLE_CONTRACT_RUNTIME, Vec::new(), Vec::new(), marking, None, None).map_err(ParameterCardError::Reify)
92}
93
94/// BLAKE3 digest of the context's contract `NetMCard`; the defaults hash to `CONTRACT_NET_DIGEST`.
95pub fn parameter_context_hash(context: &ParameterContext) -> Result<String, ParameterCardError> {
96    Ok(contract_net_mcard(context)?.card.hash.clone())
97}
98
99/// Recompute the default contract `NetMCard` and require the compiled-in digest (process bootstrap).
100pub fn verify_contract_digest() -> Result<String, ParameterCardError> {
101    let digest = parameter_context_hash(&ParameterContext::default())?;
102    if digest != CONTRACT_NET_DIGEST {
103        return Err(ParameterCardError::DigestMismatch(digest));
104    }
105    Ok(digest)
106}