use crate::epiplexity::{compute_epiplexity_for_transition, EpiplexityMetrics};
use crate::runtime_adapter::RuntimeDispatcher;
use crate::signing_provider::{DalekSigningProvider, SigningProvider};
use ed25519_dalek::{Verifier, VerifyingKey};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::cell::RefCell;
use std::collections::HashMap;
pub type HandlerError = String;
pub type HandlerResult = Result<String, HandlerError>;
pub type RuntimeHandler = fn(&str) -> HandlerResult;
thread_local! {
static DISPATCHER: RefCell<RuntimeDispatcher> = RefCell::new(RuntimeDispatcher::with_defaults());
}
pub fn register_handler(runtime: &str, handler: RuntimeHandler) {
struct FnAdapter(RuntimeHandler, &'static str);
impl crate::runtime_adapter::RuntimeAdapter for FnAdapter {
fn name(&self) -> &str { self.1 }
fn execute(&self, script: &str, _input: &Value) -> Result<Value, String> {
(self.0)(script).map(Value::String)
}
}
let name: &'static str = match runtime {
"echo" => "echo",
"noop" => "noop",
"math" => "math",
_ => "custom",
};
DISPATCHER.with(|d| {
d.borrow_mut().register(runtime, Box::new(FnAdapter(handler, name)));
});
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PlaceYaml {
pub id: String,
#[serde(default)]
pub tokens: i64,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct BindingYaml {
pub runtime: String,
#[serde(default)]
pub content: String,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct TransitionYaml {
pub id: String,
#[serde(default)]
pub inputs: Vec<String>,
#[serde(default)]
pub outputs: Vec<String>,
#[serde(default)]
pub binding: Option<BindingYaml>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NetYaml {
#[serde(default)]
pub places: Vec<PlaceYaml>,
#[serde(default)]
pub transitions: Vec<TransitionYaml>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct VCard {
pub operation: String,
pub runtime: String,
pub result: String,
pub exit_code: i32,
pub timestamp: String,
pub pcard_hash: String,
pub verifying_key: String,
pub signature: String,
pub epiplexity_metrics: Option<EpiplexityMetrics>,
}
fn sha256_hex(input: &str) -> String {
crate::hash::raw_hash_string(input)
}
fn now_iso() -> String {
chrono::Utc::now().to_rfc3339()
}
fn value_to_string(val: &Value) -> String {
match val {
Value::String(s) => s.clone(),
Value::Number(n) => n.to_string(),
Value::Bool(b) => b.to_string(),
Value::Null => String::new(),
other => other.to_string(),
}
}
pub fn run_net(yaml_body: &str) -> Result<String, String> {
let net: NetYaml = serde_yaml::from_str(yaml_body).map_err(|e| e.to_string())?;
let mut places: HashMap<String, i64> = net.places.into_iter().map(|p| (p.id, p.tokens)).collect();
let mut vcards: Vec<VCard> = Vec::new();
let signer = DalekSigningProvider::generate();
let verifying_key_bytes = signer.verifying_key_bytes();
let verifying_key_hex = hex::encode(verifying_key_bytes);
let mut previous_metrics: Option<EpiplexityMetrics> = None;
for t in &net.transitions {
for input in &t.inputs {
let tokens = places.get(input).copied().unwrap_or(0);
if tokens < 1 {
return Err(format!(
"transition {} cannot fire: place {} has {} tokens",
t.id, input, tokens
));
}
}
for input in &t.inputs {
*places.get_mut(input).unwrap() -= 1;
}
let (runtime, content, result, exit_code): (String, String, String, i32) =
if let Some(binding) = &t.binding {
let dispatch_result = DISPATCHER.with(|d| {
d.borrow().dispatch(&binding.runtime, &binding.content, &Value::Null)
});
match dispatch_result {
Ok(val) => {
let output = value_to_string(&val);
(binding.runtime.clone(), binding.content.clone(), output, 0)
}
Err(err) => {
(binding.runtime.clone(), binding.content.clone(), err.clone(), 1)
}
}
} else {
("noop".to_string(), "".to_string(), "".to_string(), 0)
};
for output in &t.outputs {
*places.entry(output.clone()).or_insert(0) += 1;
}
let metrics = compute_epiplexity_for_transition(&[], 0, 0, previous_metrics.as_ref());
previous_metrics = Some(metrics);
let pcard_body = format!(
"pcard_token:\n operation: {}\n runtime: {}\n content: {}\n transition: {}\n",
t.id, runtime, content, t.id
);
let pcard_hash = sha256_hex(&pcard_body);
let timestamp = now_iso();
let metrics_yaml = serde_yaml::to_string(&metrics).unwrap_or_default().replace('\n', " ");
let vcard_preimage = format!(
"vcard:\n operation: {}\n runtime: {}\n result: {}\n exit_code: {}\n timestamp: {}\n pcard_hash: {}\n epiplexity_metrics: {}\n",
t.id, runtime, result, exit_code, timestamp, pcard_hash, metrics_yaml
);
let vcard_hash = sha256_hex(&vcard_preimage);
let signature_bytes = signer.sign(vcard_hash.as_bytes()).map_err(|e| format!("signing failed: {e}"))?;
let signature_hex = hex::encode(&signature_bytes);
vcards.push(VCard {
operation: t.id.clone(),
runtime,
result,
exit_code,
timestamp,
pcard_hash,
verifying_key: verifying_key_hex.clone(),
signature: signature_hex,
epiplexity_metrics: Some(metrics),
});
}
serde_yaml::to_string(&vcards).map_err(|e| e.to_string())
}
pub fn verify_vcard(vcard: &VCard, preimage: &str) -> Result<bool, String> {
let bytes = hex::decode(&vcard.verifying_key).map_err(|e| e.to_string())?;
let verifying_key = VerifyingKey::from_bytes(&bytes.try_into().map_err(|_| "bad key length")?)
.map_err(|e| e.to_string())?;
let sig_bytes = hex::decode(&vcard.signature).map_err(|e| e.to_string())?;
let signature = ed25519_dalek::Signature::from_slice(&sig_bytes)
.map_err(|e| e.to_string())?;
let vcard_hash = sha256_hex(preimage);
verifying_key
.verify(vcard_hash.as_bytes(), &signature)
.map(|_| true)
.map_err(|e| e.to_string())
}
#[cfg(all(test, target_arch = "wasm32"))]
mod tests {
use super::*;
use wasm_bindgen_test::*;
#[wasm_bindgen_test]
fn test_run_three_transition_net() {
let yaml = r#"
places:
- id: start
tokens: 1
- id: mid
tokens: 0
- id: end
tokens: 0
transitions:
- id: t1
inputs: [start]
outputs: [mid]
binding:
runtime: echo
content: hello
- id: t2
inputs: [mid]
outputs: [buffer]
binding:
runtime: math
content: 3 + 4
- id: t3
inputs: [buffer]
outputs: [end]
binding:
runtime: echo
content: done
"#;
let output = run_net(yaml).unwrap();
assert!(output.contains("t1"));
assert!(output.contains("t2"));
assert!(output.contains("t3"));
assert!(output.contains("hello"));
assert!(output.contains("7"));
assert!(output.contains("done"));
}
#[wasm_bindgen_test]
fn test_vcard_signature_verifies() {
let yaml = r#"
places:
- id: start
tokens: 1
- id: end
tokens: 0
transitions:
- id: seal
inputs: [start]
outputs: [end]
binding:
runtime: echo
content: sealed
"#;
let output = run_net(yaml).unwrap();
let vcards: Vec<VCard> = serde_yaml::from_str(&output).unwrap();
assert_eq!(vcards.len(), 1);
let vcard = &vcards[0];
let metrics_yaml = serde_yaml::to_string(&vcard.epiplexity_metrics.as_ref().unwrap()).unwrap_or_default().replace('\n', " ");
assert!(verify_vcard(vcard, &format!(
"vcard:\n operation: {}\n runtime: {}\n result: {}\n exit_code: {}\n timestamp: {}\n pcard_hash: {}\n epiplexity_metrics: {}\n",
vcard.operation, vcard.runtime, vcard.result, vcard.exit_code, vcard.timestamp, vcard.pcard_hash, metrics_yaml
)).unwrap());
}
#[wasm_bindgen_test]
fn test_missing_token_blocks_transition() {
let yaml = r#"
places:
- id: start
tokens: 0
- id: end
tokens: 0
transitions:
- id: t1
inputs: [start]
outputs: [end]
binding:
runtime: echo
content: hello
"#;
assert!(run_net(yaml).is_err());
}
}