interplane.Get Omega
Read in your language

physics-mv

FORGE: request-bound machine realization, providers and verification for AienOS. Host, simulated and GB10 hardware paths have separate evidence.

Brought by drakestapleton

branch main Branches Tags History

physics-mv / forge / v2 / forge_substrate_v2.c

791 lines · 36965 bytes Raw Blame History
1/* forge/v2/forge_substrate_v2.c -- FORGE SUBSTRATE V2 reference serializer,
2 * digest and strict decoder/validator. Host-only: no hardware access, no
3 * heap allocation. See docs/FORGE_SUBSTRATE_V2_SPEC.md.
4 */
5#include "forge_substrate_v2.h"
6#include "forge_sha256.h"
7
8#include <string.h>
9
10/* ------------------------------------------------------------------ */
11/* primitives */
12/* ------------------------------------------------------------------ */
13
14void forge_v2_sha256(const uint8_t *data, size_t len, uint8_t out[32])
15{
16 uint8_t scratch[128];
17 uint32_t st[8];
18 sha256_compute(data, (uint64_t)len, scratch, st);
19 for (unsigned i = 0; i < 8; i++) {
20 out[4 * i + 0] = (uint8_t)(st[i] >> 24);
21 out[4 * i + 1] = (uint8_t)(st[i] >> 16);
22 out[4 * i + 2] = (uint8_t)(st[i] >> 8);
23 out[4 * i + 3] = (uint8_t)(st[i]);
24 }
25}
26
27static void put_u16(uint8_t *p, uint16_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); }
28static void put_u32(uint8_t *p, uint32_t v)
29{
30 p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24);
31}
32static void put_u64(uint8_t *p, uint64_t v) { put_u32(p, (uint32_t)v); put_u32(p + 4, (uint32_t)(v >> 32)); }
33static uint16_t get_u16(const uint8_t *p) { return (uint16_t)(p[0] | (p[1] << 8)); }
34static uint32_t get_u32(const uint8_t *p)
35{
36 return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
37}
38static uint64_t get_u64(const uint8_t *p) { return (uint64_t)get_u32(p) | ((uint64_t)get_u32(p + 4) << 32); }
39
40static int is_zero(const uint8_t *p, size_t n)
41{
42 uint8_t acc = 0;
43 for (size_t i = 0; i < n; i++) acc |= p[i];
44 return acc == 0;
45}
46
47/* ------------------------------------------------------------------ */
48/* schema tables */
49/* ------------------------------------------------------------------ */
50
51enum { T_U32 = 1, T_U64, T_I32, T_I64, T_D32, T_NEST, T_NEST_REP };
52enum { F_OPT = 1, F_GEN64 = 2, F_PROV = 4 };
53
54typedef struct Schema Schema;
55typedef struct {
56 uint32_t tag;
57 uint8_t type;
58 uint8_t flags;
59 uint32_t max; /* T_NEST_REP: max element count */
60 size_t off; /* value offset in the struct */
61 size_t aux; /* F_OPT: presence byte; T_NEST_REP: u32 count */
62 size_t stride; /* T_NEST_REP: element size */
63 const Schema *sub; /* T_NEST / T_NEST_REP */
64} Field;
65
66struct Schema {
67 uint16_t kind;
68 const Field *f;
69 size_t n;
70 int (*validate)(const void *obj);
71};
72
73#define FLD(tag, ty, st, m) { tag, ty, 0, 0, offsetof(st, m), 0, 0, 0 }
74#define OPT(tag, ty, st, m, p) { tag, ty, F_OPT, 0, offsetof(st, m), offsetof(st, p), 0, 0 }
75
76static int val_profile(const void *o);
77static int val_substrate(const void *o);
78static int val_machine(const void *o);
79static int val_contract(const void *o);
80static int val_calibration(const void *o);
81static int val_evidence(const void *o);
82static int val_ref(const void *o);
83
84#define P ForgeNumericalProfile
85static const Field F_PROFILE[] = {
86 FLD(0x0401, T_U32, P, dynamic_range_mdb),
87 FLD(0x0402, T_U32, P, resolution_bits),
88 FLD(0x0403, T_U32, P, repeatability_ppb),
89 FLD(0x0404, T_U32, P, drift_ppb_per_hour),
90 FLD(0x0405, T_U32, P, temperature_ppb_per_k),
91 FLD(0x0406, T_U64, P, settling_ns),
92 FLD(0x0407, T_U64, P, sample_rate_hz),
93 FLD(0x0408, T_U64, P, calibration_validity_s),
94};
95#undef P
96static const Schema S_PROFILE = { FORGE_V2_KIND_NUMERICAL_PROFILE, F_PROFILE,
97 sizeof F_PROFILE / sizeof F_PROFILE[0], val_profile };
98
99#define S ForgeSubstrateDescriptor
100static const Field F_SUBSTRATE[] = {
101 FLD(0x0201, T_D32, S, substrate_identity),
102 FLD(0x0202, T_U32, S, substrate_class),
103 FLD(0x0203, T_U64, S, operation_families),
104 FLD(0x0210, T_U32, S, input_repr),
105 FLD(0x0211, T_U32, S, input_bits),
106 FLD(0x0212, T_U32, S, output_repr),
107 FLD(0x0213, T_U32, S, output_bits),
108 FLD(0x0220, T_U32, S, state_model),
109 FLD(0x0221, T_U32, S, sync_model),
110 FLD(0x0230, T_U32, S, memory_model),
111 FLD(0x0231, T_U64, S, memory_capacity_bytes),
112 { 0x0240, T_NEST, 0, 0, offsetof(S, numerical), 0, 0, &S_PROFILE },
113 FLD(0x0250, T_U32, S, calibration_required),
114 FLD(0x0251, T_U32, S, calibration_method_mask),
115 FLD(0x0252, T_U64, S, calibration_max_window_s),
116 FLD(0x0253, T_U32, S, calibration_min_fixtures),
117 FLD(0x0260, T_U32, S, error_kind),
118 FLD(0x0261, T_U32, S, error_rel_ppb),
119 FLD(0x0262, T_U64, S, error_abs),
120 FLD(0x0263, T_U32, S, fault_detect_mask),
121 FLD(0x0270, T_U64, S, timing_min_latency_ns),
122 FLD(0x0271, T_U64, S, timing_setup_ns),
123 FLD(0x0272, T_U64, S, timing_conversion_ns),
124 FLD(0x0273, T_U32, S, timing_deterministic),
125 FLD(0x0280, T_U32, S, limit_max_rows),
126 FLD(0x0281, T_U32, S, limit_max_cols),
127 FLD(0x0282, T_U64, S, limit_max_state_bytes),
128 FLD(0x0283, T_U32, S, limit_max_concurrent),
129 FLD(0x0290, T_U32, S, evidence_capabilities),
130 OPT(0x02F0, T_D32, S, legacy_v1_descriptor_digest, has_legacy_v1),
131};
132#undef S
133static const Schema S_SUBSTRATE = { FORGE_V2_KIND_SUBSTRATE, F_SUBSTRATE,
134 sizeof F_SUBSTRATE / sizeof F_SUBSTRATE[0], val_substrate };
135
136#define M ForgeMachineDescriptorV2
137static const Field F_MACHINE[] = {
138 FLD(0x0101, T_D32, M, machine_identity),
139 FLD(0x0102, T_D32, M, authority_domain),
140 FLD(0x0110, T_U64, M, memory_nominal_bytes),
141 FLD(0x0111, T_U32, M, memory_numa_domains),
142 FLD(0x0112, T_U32, M, memory_coherency),
143 FLD(0x0120, T_U32, M, interconnect_topology),
144 FLD(0x0121, T_U32, M, interconnect_links),
145 FLD(0x0130, T_U32, M, transport_class),
146 FLD(0x0131, T_U32, M, transport_bandwidth_mbps),
147 FLD(0x0132, T_U32, M, transport_latency_ns),
148 { 0x0140, T_NEST_REP, 0, FORGE_V2_MAX_SUBSTRATES, offsetof(M, substrates),
149 offsetof(M, substrate_count), sizeof(ForgeSubstrateDescriptor), &S_SUBSTRATE },
150};
151#undef M
152static const Schema S_MACHINE = { FORGE_V2_KIND_MACHINE_DESCRIPTOR, F_MACHINE,
153 sizeof F_MACHINE / sizeof F_MACHINE[0], val_machine };
154
155#define C ForgeSemanticResultContract
156static const Field F_CONTRACT[] = {
157 FLD(0x0301, T_U32, C, operation_family),
158 FLD(0x0302, T_D32, C, reference_oracle_digest),
159 FLD(0x0310, T_U32, C, shape_rank),
160 FLD(0x0311, T_U32, C, shape_dim[0]),
161 FLD(0x0312, T_U32, C, shape_dim[1]),
162 FLD(0x0313, T_U32, C, shape_dim[2]),
163 FLD(0x0314, T_U32, C, shape_dim[3]),
164 FLD(0x0320, T_U32, C, error_kind),
165 FLD(0x0321, T_U32, C, error_rel_ppb),
166 FLD(0x0322, T_U64, C, error_abs),
167 FLD(0x0323, T_U32, C, error_norm),
168 FLD(0x0330, T_U32, C, confidence_ppm),
169 FLD(0x0331, T_U32, C, min_samples),
170 FLD(0x0340, T_U32, C, allowed_nondeterminism),
171};
172#undef C
173static const Schema S_CONTRACT = { FORGE_V2_KIND_RESULT_CONTRACT, F_CONTRACT,
174 sizeof F_CONTRACT / sizeof F_CONTRACT[0], val_contract };
175
176#define A ForgeCalibrationArtifact
177static const Field F_CALIBRATION[] = {
178 FLD(0x0501, T_D32, A, substrate_id),
179 FLD(0x0502, T_D32, A, calibration_id),
180 FLD(0x0503, T_U32, A, method),
181 FLD(0x0504, T_U64, A, epoch_s),
182 FLD(0x0505, T_U64, A, validity_window_s),
183 FLD(0x0510, T_I32, A, env_temp_min_mc),
184 FLD(0x0511, T_I32, A, env_temp_max_mc),
185 FLD(0x0512, T_U32, A, env_supply_min_uv),
186 FLD(0x0513, T_U32, A, env_supply_max_uv),
187 FLD(0x0520, T_I64, A, transfer_gain_ppb),
188 FLD(0x0521, T_I64, A, transfer_offset_lsb),
189 FLD(0x0522, T_U32, A, transfer_linearity_ppb),
190 FLD(0x0530, T_U32, A, noise_rms_ppb),
191 FLD(0x0531, T_U32, A, noise_peak_ppb),
192 FLD(0x0532, T_U32, A, noise_samples),
193 FLD(0x0540, T_U32, A, drift_ppb_per_hour),
194 FLD(0x0541, T_U32, A, drift_temp_ppb_per_k),
195 FLD(0x0542, T_U64, A, drift_observed_span_s),
196 FLD(0x0550, T_U32, A, fixture_count),
197 FLD(0x0551, T_D32, A, fixtures_digest),
198 FLD(0x0560, T_D32, A, evidence_root),
199};
200#undef A
201static const Schema S_CALIBRATION = { FORGE_V2_KIND_CALIBRATION, F_CALIBRATION,
202 sizeof F_CALIBRATION / sizeof F_CALIBRATION[0], val_calibration };
203
204#define E ForgeExecutionEvidenceV2
205static const Field F_EVIDENCE[] = {
206 FLD(0x0601, T_D32, E, realization_identity),
207 FLD(0x0602, T_D32, E, machine_identity),
208 FLD(0x0603, T_D32, E, substrate_identity),
209 FLD(0x0604, T_D32, E, semantic_contract_digest),
210 OPT(0x0605, T_D32, E, calibration_digest, has_calibration),
211 FLD(0x0606, T_D32, E, input_identity),
212 FLD(0x0607, T_D32, E, output_identity),
213 FLD(0x0610, T_U64, E, execution_epoch_s),
214 FLD(0x0611, T_U64, E, execution_duration_ns),
215 FLD(0x0612, T_U64, E, conversion_duration_ns),
216 FLD(0x0620, T_U64, E, energy_nj),
217 FLD(0x0621, T_U32, E, energy_source),
218 FLD(0x0630, T_I32, E, env_temperature_mc),
219 FLD(0x0631, T_U32, E, env_supply_uv),
220 FLD(0x0640, T_U32, E, measured_error_rel_ppb),
221 FLD(0x0641, T_U64, E, measured_error_abs),
222 FLD(0x0642, T_U32, E, confidence_ppm),
223 FLD(0x0650, T_U32, E, repeat_runs),
224 FLD(0x0651, T_U32, E, repeat_passes),
225 FLD(0x0652, T_U64, E, repeat_mean_ns),
226 FLD(0x0653, T_U64, E, repeat_spread_ns),
227 FLD(0x0654, T_U32, E, repeat_error_spread_ppb),
228 FLD(0x0660, T_U32, E, hardware_status),
229 FLD(0x0661, T_U32, E, fault_state),
230 { 0x0670, T_U32, F_PROV, 0, offsetof(E, provenance_class), 0, 0, 0 },
231};
232#undef E
233static const Schema S_EVIDENCE = { FORGE_V2_KIND_EXECUTION_EVIDENCE, F_EVIDENCE,
234 sizeof F_EVIDENCE / sizeof F_EVIDENCE[0], val_evidence };
235
236#define R ForgeCrossMachineRef
237static const Field F_REF[] = {
238 FLD(0x0701, T_D32, R, program_digest),
239 FLD(0x0702, T_D32, R, semantic_object_id),
240 FLD(0x0703, T_D32, R, ir_reference),
241 FLD(0x0710, T_U64, R, ir_size),
242 FLD(0x0711, T_U64, R, range_offset),
243 FLD(0x0712, T_U64, R, range_length),
244 FLD(0x0720, T_U32, R, target_kind),
245 FLD(0x0721, T_D32, R, target_digest),
246 { 0x0730, T_U64, F_GEN64, 0, offsetof(R, generation), 0, 0, 0 },
247 FLD(0x0740, T_U64, R, rights),
248};
249#undef R
250static const Schema S_REF = { FORGE_V2_KIND_CROSS_MACHINE_REF, F_REF,
251 sizeof F_REF / sizeof F_REF[0], val_ref };
252
253/* ------------------------------------------------------------------ */
254/* validators */
255/* ------------------------------------------------------------------ */
256
257static int in_range(uint32_t v, uint32_t lo, uint32_t hi) { return v >= lo && v <= hi; }
258
259static int class_known(uint32_t c)
260{
261 return c == FORGE_V2_SUBSTRATE_DIGITAL_CPU || c == FORGE_V2_SUBSTRATE_DIGITAL_GPU ||
262 c == FORGE_V2_SUBSTRATE_ANALOG_IN_MEMORY || c == FORGE_V2_SUBSTRATE_NEUROMORPHIC_SPIKING ||
263 c == FORGE_V2_SUBSTRATE_FPGA_CGRA_DATAFLOW || c == FORGE_V2_SUBSTRATE_OPTICAL_PHOTONIC;
264}
265
266static int class_digital(uint32_t c)
267{
268 return c == FORGE_V2_SUBSTRATE_DIGITAL_CPU || c == FORGE_V2_SUBSTRATE_DIGITAL_GPU;
269}
270
271/* shared rule for (kind, rel bound, abs bound) triples */
272static int error_triple_ok(uint32_t kind, uint32_t rel, uint64_t abs)
273{
274 if (!in_range(kind, FORGE_V2_ERROR_EXACT, FORGE_V2_ERROR_LAST)) return 0;
275 if (kind == FORGE_V2_ERROR_EXACT) return rel == 0 && abs == 0;
276 if (kind == FORGE_V2_ERROR_MEASURED_DISTRIBUTION) return 1;
277 return rel != 0 || abs != 0;
278}
279
280static int val_profile(const void *o)
281{
282 const ForgeNumericalProfile *p = o;
283 if (!in_range(p->resolution_bits, 1, 128)) return FORGE_V2_ERR_VALUE;
284 return FORGE_V2_OK;
285}
286
287static int val_substrate(const void *o)
288{
289 const ForgeSubstrateDescriptor *s = o;
290 int rc;
291 if (is_zero(s->substrate_identity, 32)) return FORGE_V2_ERR_VALUE;
292 if (!class_known(s->substrate_class)) return FORGE_V2_ERR_VALUE;
293 if (s->operation_families == 0 || (s->operation_families & ~(uint64_t)FORGE_V2_OP_KNOWN_MASK))
294 return FORGE_V2_ERR_VALUE;
295 if (!in_range(s->input_repr, 1, FORGE_V2_REPR_LAST) || !in_range(s->output_repr, 1, FORGE_V2_REPR_LAST))
296 return FORGE_V2_ERR_VALUE;
297 if (!in_range(s->input_bits, 1, 128) || !in_range(s->output_bits, 1, 128)) return FORGE_V2_ERR_VALUE;
298 if (!in_range(s->state_model, 1, FORGE_V2_STATE_LAST)) return FORGE_V2_ERR_VALUE;
299 if (!in_range(s->sync_model, 1, FORGE_V2_SYNC_LAST)) return FORGE_V2_ERR_VALUE;
300 if (!in_range(s->memory_model, 1, FORGE_V2_MEM_LAST)) return FORGE_V2_ERR_VALUE;
301 if ((rc = val_profile(&s->numerical)) != FORGE_V2_OK) return rc;
302 if (s->calibration_required > 1) return FORGE_V2_ERR_VALUE;
303 if (s->calibration_required) {
304 uint32_t known = 0;
305 for (uint32_t m = 1; m <= FORGE_V2_CAL_LAST; m++) known |= 1u << m;
306 if (s->calibration_method_mask == 0 || (s->calibration_method_mask & ~known)) return FORGE_V2_ERR_VALUE;
307 if (s->calibration_max_window_s == 0 || s->calibration_min_fixtures == 0) return FORGE_V2_ERR_VALUE;
308 if (s->numerical.calibration_validity_s == 0 ||
309 s->numerical.calibration_validity_s > s->calibration_max_window_s)
310 return FORGE_V2_ERR_VALUE;
311 } else {
312 if (s->calibration_method_mask || s->calibration_max_window_s || s->calibration_min_fixtures ||
313 s->numerical.calibration_validity_s)
314 return FORGE_V2_ERR_VALUE;
315 }
316 if (!error_triple_ok(s->error_kind, s->error_rel_ppb, s->error_abs)) return FORGE_V2_ERR_VALUE;
317 if (s->timing_deterministic > 1) return FORGE_V2_ERR_VALUE;
318 if (s->limit_max_concurrent == 0) return FORGE_V2_ERR_VALUE;
319 if (s->evidence_capabilities & ~(uint32_t)FORGE_V2_EVCAP_KNOWN_MASK) return FORGE_V2_ERR_VALUE;
320 if (s->has_legacy_v1 > 1) return FORGE_V2_ERR_VALUE;
321 if (s->has_legacy_v1) {
322 /* a v1 record describes a digital device; nothing else may wrap one */
323 if (!class_digital(s->substrate_class)) return FORGE_V2_ERR_VALUE;
324 if (is_zero(s->legacy_v1_descriptor_digest, 32)) return FORGE_V2_ERR_VALUE;
325 } else if (!is_zero(s->legacy_v1_descriptor_digest, 32)) {
326 return FORGE_V2_ERR_VALUE;
327 }
328 return FORGE_V2_OK;
329}
330
331static int val_machine(const void *o)
332{
333 const ForgeMachineDescriptorV2 *m = o;
334 int rc;
335 if (is_zero(m->machine_identity, 32) || is_zero(m->authority_domain, 32)) return FORGE_V2_ERR_VALUE;
336 if (!in_range(m->memory_coherency, 1, FORGE_V2_COHERENCY_LAST)) return FORGE_V2_ERR_VALUE;
337 if (!in_range(m->interconnect_topology, 1, FORGE_V2_TOPO_LAST)) return FORGE_V2_ERR_VALUE;
338 if (!in_range(m->transport_class, 1, FORGE_V2_TRANSPORT_LAST)) return FORGE_V2_ERR_VALUE;
339 if (m->substrate_count < 1 || m->substrate_count > FORGE_V2_MAX_SUBSTRATES) return FORGE_V2_ERR_COUNT;
340 for (uint32_t i = 0; i < m->substrate_count; i++) {
341 if ((rc = val_substrate(&m->substrates[i])) != FORGE_V2_OK) return rc;
342 if (i > 0) {
343 int c = memcmp(m->substrates[i - 1].substrate_identity, m->substrates[i].substrate_identity, 32);
344 if (c == 0) return FORGE_V2_ERR_DUPLICATE_ID;
345 if (c > 0) return FORGE_V2_ERR_ORDER;
346 }
347 }
348 /* A Machine may carry only non-digital substrates (e.g. an external
349 * analog node on the Fabric). The digital fallback is a property of the
350 * eligible set for a contract, not of any one Machine: see
351 * forge_v2_eligible_set_has_digital_fallback(). */
352 return FORGE_V2_OK;
353}
354
355static int single_bit(uint32_t v) { return v != 0 && (v & (v - 1)) == 0; }
356
357static int val_contract(const void *o)
358{
359 const ForgeSemanticResultContract *c = o;
360 if (!single_bit(c->operation_family) || (c->operation_family & ~(uint32_t)FORGE_V2_OP_KNOWN_MASK))
361 return FORGE_V2_ERR_VALUE;
362 if (is_zero(c->reference_oracle_digest, 32)) return FORGE_V2_ERR_VALUE;
363 if (!in_range(c->error_norm, 1, FORGE_V2_NORM_LAST)) return FORGE_V2_ERR_VALUE;
364 if (c->min_samples == 0) return FORGE_V2_ERR_VALUE;
365 if (!in_range(c->shape_rank, 1, 4)) return FORGE_V2_ERR_VALUE;
366 for (uint32_t i = 0; i < 4; i++) {
367 if (i < c->shape_rank && c->shape_dim[i] == 0) return FORGE_V2_ERR_VALUE;
368 if (i >= c->shape_rank && c->shape_dim[i] != 0) return FORGE_V2_ERR_VALUE;
369 }
370 if (!error_triple_ok(c->error_kind, c->error_rel_ppb, c->error_abs)) return FORGE_V2_ERR_VALUE;
371 if (!in_range(c->confidence_ppm, 1, 1000000)) return FORGE_V2_ERR_VALUE;
372 if (c->allowed_nondeterminism & ~(uint32_t)FORGE_V2_NONDET_KNOWN_MASK) return FORGE_V2_ERR_VALUE;
373 switch (c->error_kind) {
374 case FORGE_V2_ERROR_EXACT:
375 if (c->confidence_ppm != 1000000) return FORGE_V2_ERR_VALUE;
376 if (c->allowed_nondeterminism & (FORGE_V2_NONDET_ROUNDING | FORGE_V2_NONDET_STOCHASTIC_NOISE))
377 return FORGE_V2_ERR_VALUE;
378 break;
379 case FORGE_V2_ERROR_BOUNDED_DETERMINISTIC:
380 if (c->confidence_ppm != 1000000) return FORGE_V2_ERR_VALUE;
381 if (c->allowed_nondeterminism & FORGE_V2_NONDET_STOCHASTIC_NOISE) return FORGE_V2_ERR_VALUE;
382 break;
383 default: /* stochastic kinds must admit noise explicitly */
384 if (!(c->allowed_nondeterminism & FORGE_V2_NONDET_STOCHASTIC_NOISE)) return FORGE_V2_ERR_VALUE;
385 if (c->min_samples < 2) return FORGE_V2_ERR_VALUE; /* one run cannot show a spread */
386 break;
387 }
388 return FORGE_V2_OK;
389}
390
391static int val_calibration(const void *o)
392{
393 const ForgeCalibrationArtifact *a = o;
394 if (is_zero(a->substrate_id, 32) || is_zero(a->calibration_id, 32)) return FORGE_V2_ERR_VALUE;
395 if (!in_range(a->method, 1, FORGE_V2_CAL_LAST)) return FORGE_V2_ERR_VALUE;
396 if (a->validity_window_s == 0 || a->epoch_s > UINT64_MAX - a->validity_window_s) return FORGE_V2_ERR_VALUE;
397 if (a->env_temp_min_mc > a->env_temp_max_mc) return FORGE_V2_ERR_VALUE;
398 if (a->env_supply_min_uv > a->env_supply_max_uv) return FORGE_V2_ERR_VALUE;
399 if (a->fixture_count == 0 || is_zero(a->fixtures_digest, 32)) return FORGE_V2_ERR_VALUE;
400 if (is_zero(a->evidence_root, 32)) return FORGE_V2_ERR_VALUE;
401 return FORGE_V2_OK;
402}
403
404static int val_evidence(const void *o)
405{
406 const ForgeExecutionEvidenceV2 *e = o;
407 if (!in_range(e->provenance_class, FORGE_V2_PROVENANCE_PHYSICAL, FORGE_V2_PROVENANCE_LAST))
408 return FORGE_V2_ERR_PROVENANCE;
409 if (is_zero(e->realization_identity, 32) || is_zero(e->machine_identity, 32) ||
410 is_zero(e->substrate_identity, 32) || is_zero(e->semantic_contract_digest, 32) ||
411 is_zero(e->input_identity, 32) || is_zero(e->output_identity, 32))
412 return FORGE_V2_ERR_VALUE;
413 if (e->has_calibration > 1) return FORGE_V2_ERR_VALUE;
414 if (e->has_calibration ? is_zero(e->calibration_digest, 32) : !is_zero(e->calibration_digest, 32))
415 return FORGE_V2_ERR_VALUE;
416 if (e->energy_source > FORGE_V2_ENERGY_LAST) return FORGE_V2_ERR_VALUE;
417 if (e->energy_source == FORGE_V2_ENERGY_NOT_MEASURED && e->energy_nj != 0) return FORGE_V2_ERR_VALUE;
418 if (e->confidence_ppm > 1000000) return FORGE_V2_ERR_VALUE;
419 if (e->repeat_passes > e->repeat_runs) return FORGE_V2_ERR_VALUE;
420 if (e->fault_state > FORGE_V2_FAULT_LAST) return FORGE_V2_ERR_VALUE;
421 return FORGE_V2_OK;
422}
423
424static int val_ref(const void *o)
425{
426 const ForgeCrossMachineRef *r = o;
427 if (is_zero(r->program_digest, 32) || is_zero(r->semantic_object_id, 32) ||
428 is_zero(r->ir_reference, 32) || is_zero(r->target_digest, 32))
429 return FORGE_V2_ERR_VALUE;
430 if (r->range_length == 0 || r->range_offset > UINT64_MAX - r->range_length ||
431 r->range_offset + r->range_length > r->ir_size)
432 return FORGE_V2_ERR_RANGE;
433 if (r->target_kind != FORGE_V2_TARGET_MACHINE && r->target_kind != FORGE_V2_TARGET_SUBSTRATE)
434 return FORGE_V2_ERR_VALUE;
435 if (r->generation == 0) return FORGE_V2_ERR_STALE_GENERATION;
436 if (r->rights == 0 || (r->rights & ~(uint64_t)FORGE_V2_RIGHT_KNOWN_MASK)) return FORGE_V2_ERR_VALUE;
437 return FORGE_V2_OK;
438}
439
440/* ------------------------------------------------------------------ */
441/* generic encoder / decoder */
442/* ------------------------------------------------------------------ */
443
444static size_t type_width(uint8_t t)
445{
446 switch (t) {
447 case T_U32: case T_I32: return 4;
448 case T_U64: case T_I64: return 8;
449 case T_D32: return 32;
450 default: return 0;
451 }
452}
453
454static int enc_obj(const Schema *sc, const void *obj, uint8_t *buf, size_t cap, size_t *out_len);
455
456static int enc_value(const Field *f, const uint8_t *src, uint8_t *buf, size_t cap, size_t *pos)
457{
458 size_t w, n = 0;
459 int rc;
460 if (cap - *pos < FORGE_V2_TLV_HEAD_LEN) return FORGE_V2_ERR_SPACE;
461 uint8_t *head = buf + *pos;
462 uint8_t *val = head + FORGE_V2_TLV_HEAD_LEN;
463 size_t room = cap - *pos - FORGE_V2_TLV_HEAD_LEN;
464 if (f->type == T_NEST || f->type == T_NEST_REP) {
465 if ((rc = enc_obj(f->sub, src, val, room, &n)) != FORGE_V2_OK) return rc;
466 } else {
467 w = type_width(f->type);
468 if (room < w) return FORGE_V2_ERR_SPACE;
469 switch (f->type) {
470 case T_U32: { uint32_t v; memcpy(&v, src, 4); put_u32(val, v); break; }
471 case T_I32: { int32_t v; memcpy(&v, src, 4); put_u32(val, (uint32_t)v); break; }
472 case T_U64: { uint64_t v; memcpy(&v, src, 8); put_u64(val, v); break; }
473 case T_I64: { int64_t v; memcpy(&v, src, 8); put_u64(val, (uint64_t)v); break; }
474 default: memcpy(val, src, 32); break;
475 }
476 n = w;
477 }
478 put_u32(head, f->tag);
479 put_u32(head + 4, (uint32_t)n);
480 *pos += FORGE_V2_TLV_HEAD_LEN + n;
481 return FORGE_V2_OK;
482}
483
484static int enc_obj(const Schema *sc, const void *obj, uint8_t *buf, size_t cap, size_t *out_len)
485{
486 const uint8_t *base = obj;
487 size_t pos = FORGE_V2_HEADER_LEN;
488 int rc;
489 if (!obj || !buf || !out_len) return FORGE_V2_ERR_ARG;
490 if ((rc = sc->validate(obj)) != FORGE_V2_OK) return rc;
491 if (cap < FORGE_V2_HEADER_LEN) return FORGE_V2_ERR_SPACE;
492 if (cap > FORGE_V2_MAX_OBJECT_LEN) cap = FORGE_V2_MAX_OBJECT_LEN;
493 for (size_t i = 0; i < sc->n; i++) {
494 const Field *f = &sc->f[i];
495 if ((f->flags & F_OPT) && base[f->aux] == 0) continue;
496 if (f->type == T_NEST_REP) {
497 uint32_t count;
498 memcpy(&count, base + f->aux, 4);
499 for (uint32_t k = 0; k < count; k++)
500 if ((rc = enc_value(f, base + f->off + (size_t)k * f->stride, buf, cap, &pos)) != FORGE_V2_OK)
501 return rc;
502 } else if ((rc = enc_value(f, base + f->off, buf, cap, &pos)) != FORGE_V2_OK) {
503 return rc;
504 }
505 }
506 buf[0] = FORGE_V2_MAGIC0; buf[1] = FORGE_V2_MAGIC1; buf[2] = FORGE_V2_MAGIC2; buf[3] = FORGE_V2_MAGIC3;
507 put_u16(buf + 4, sc->kind);
508 put_u16(buf + 6, FORGE_V2_WIRE_VERSION);
509 put_u32(buf + 8, (uint32_t)(pos - FORGE_V2_HEADER_LEN));
510 *out_len = pos;
511 return FORGE_V2_OK;
512}
513
514static int check_header(const Schema *sc, const uint8_t *buf, size_t len)
515{
516 if (!buf) return FORGE_V2_ERR_ARG;
517 if (len < FORGE_V2_HEADER_LEN) return FORGE_V2_ERR_TRUNCATED;
518 if (len > FORGE_V2_MAX_OBJECT_LEN) return FORGE_V2_ERR_LENGTH;
519 if (buf[0] != FORGE_V2_MAGIC0 || buf[1] != FORGE_V2_MAGIC1 || buf[2] != FORGE_V2_MAGIC2 ||
520 buf[3] != FORGE_V2_MAGIC3)
521 return FORGE_V2_ERR_MAGIC;
522 if (get_u16(buf + 4) != sc->kind) return FORGE_V2_ERR_KIND;
523 uint16_t ver = get_u16(buf + 6);
524 if (ver == FORGE_V2_LEGACY_VERSION) return FORGE_V2_ERR_LEGACY_VERSION;
525 if (ver != FORGE_V2_WIRE_VERSION) return FORGE_V2_ERR_VERSION;
526 if ((size_t)get_u32(buf + 8) != len - FORGE_V2_HEADER_LEN) return FORGE_V2_ERR_LENGTH;
527 return FORGE_V2_OK;
528}
529
530static int dec_obj(const Schema *sc, const uint8_t *buf, size_t len, int strict, void *obj)
531{
532 uint8_t *base = obj;
533 uint8_t seen[64];
534 uint32_t prev_tag = 0;
535 size_t pos = FORGE_V2_HEADER_LEN;
536 int rc;
537 if (!obj) return FORGE_V2_ERR_ARG;
538 if ((rc = check_header(sc, buf, len)) != FORGE_V2_OK) return rc;
539 if (sc->n > sizeof seen) return FORGE_V2_ERR_ARG;
540 memset(seen, 0, sizeof seen);
541 while (pos < len) {
542 if (len - pos < FORGE_V2_TLV_HEAD_LEN) return FORGE_V2_ERR_TRUNCATED;
543 uint32_t tag = get_u32(buf + pos);
544 size_t flen = get_u32(buf + pos + 4);
545 const uint8_t *val = buf + pos + FORGE_V2_TLV_HEAD_LEN;
546 if (flen > len - pos - FORGE_V2_TLV_HEAD_LEN) return FORGE_V2_ERR_TRUNCATED;
547 size_t idx = sc->n;
548 for (size_t i = 0; i < sc->n; i++)
549 if (sc->f[i].tag == tag) { idx = i; break; }
550 int repeat_ok = idx < sc->n && sc->f[idx].type == T_NEST_REP;
551 if (tag < prev_tag || (tag == prev_tag && !repeat_ok)) return FORGE_V2_ERR_ORDER;
552 prev_tag = tag;
553 pos += FORGE_V2_TLV_HEAD_LEN + flen;
554 if (idx == sc->n) {
555 if (strict) return FORGE_V2_ERR_UNKNOWN_TAG;
556 continue;
557 }
558 const Field *f = &sc->f[idx];
559 if (f->type == T_NEST) {
560 if ((rc = dec_obj(f->sub, val, flen, strict, base + f->off)) != FORGE_V2_OK) return rc;
561 } else if (f->type == T_NEST_REP) {
562 uint32_t count;
563 memcpy(&count, base + f->aux, 4);
564 if (count >= f->max) return FORGE_V2_ERR_COUNT;
565 if ((rc = dec_obj(f->sub, val, flen, strict, base + f->off + (size_t)count * f->stride)) != FORGE_V2_OK)
566 return rc;
567 count++;
568 memcpy(base + f->aux, &count, 4);
569 } else {
570 size_t w = type_width(f->type);
571 if (flen != w) {
572 if ((f->flags & F_GEN64) && flen == 4) return FORGE_V2_ERR_GENERATION_32;
573 return FORGE_V2_ERR_WIDTH;
574 }
575 uint8_t *dst = base + f->off;
576 switch (f->type) {
577 case T_U32: { uint32_t v = get_u32(val); memcpy(dst, &v, 4); break; }
578 case T_I32: { int32_t v = (int32_t)get_u32(val); memcpy(dst, &v, 4); break; }
579 case T_U64: { uint64_t v = get_u64(val); memcpy(dst, &v, 8); break; }
580 case T_I64: { int64_t v = (int64_t)get_u64(val); memcpy(dst, &v, 8); break; }
581 default: memcpy(dst, val, 32); break;
582 }
583 if (f->flags & F_OPT) base[f->aux] = 1;
584 }
585 seen[idx] = 1;
586 }
587 for (size_t i = 0; i < sc->n; i++) {
588 if (seen[i] || (sc->f[i].flags & F_OPT)) continue;
589 if (sc->f[i].flags & F_PROV) return FORGE_V2_ERR_PROVENANCE;
590 if (sc->f[i].type == T_NEST_REP) return FORGE_V2_ERR_COUNT;
591 return FORGE_V2_ERR_MISSING;
592 }
593 return sc->validate(obj);
594}
595
596/* Public decode: structural decode + validation; in strict mode the input
597 * must also equal the canonical re-encoding byte for byte. */
598static int dec_public(const Schema *sc, const uint8_t *buf, size_t len, int strict, void *obj, size_t obj_size)
599{
600 uint8_t again[FORGE_V2_MAX_OBJECT_LEN];
601 size_t n = 0;
602 int rc;
603 if (!obj) return FORGE_V2_ERR_ARG;
604 memset(obj, 0, obj_size);
605 if ((rc = dec_obj(sc, buf, len, strict, obj)) != FORGE_V2_OK) {
606 memset(obj, 0, obj_size);
607 return rc;
608 }
609 if (strict) {
610 rc = enc_obj(sc, obj, again, sizeof again, &n);
611 if (rc == FORGE_V2_OK && (n != len || memcmp(again, buf, len) != 0)) rc = FORGE_V2_ERR_NONCANONICAL;
612 if (rc != FORGE_V2_OK) {
613 memset(obj, 0, obj_size);
614 return rc;
615 }
616 }
617 return FORGE_V2_OK;
618}
619
620static int digest_obj(const Schema *sc, const void *obj, uint8_t out[32])
621{
622 uint8_t buf[FORGE_V2_MAX_OBJECT_LEN];
623 size_t n = 0;
624 int rc;
625 if (!out) return FORGE_V2_ERR_ARG;
626 if ((rc = enc_obj(sc, obj, buf, sizeof buf, &n)) != FORGE_V2_OK) return rc;
627 forge_v2_sha256(buf, n, out);
628 return FORGE_V2_OK;
629}
630
631/* ------------------------------------------------------------------ */
632/* public wrappers */
633/* ------------------------------------------------------------------ */
634
635#define WRAP(name, type, schema) \
636 int forge_v2_encode_##name(const type *o, uint8_t *buf, size_t cap, size_t *out_len) \
637 { return enc_obj(&schema, o, buf, cap, out_len); } \
638 int forge_v2_decode_##name(const uint8_t *buf, size_t len, int strict, type *o) \
639 { return dec_public(&schema, buf, len, strict, o, sizeof *o); }
640
641WRAP(machine, ForgeMachineDescriptorV2, S_MACHINE)
642WRAP(substrate, ForgeSubstrateDescriptor, S_SUBSTRATE)
643WRAP(contract, ForgeSemanticResultContract, S_CONTRACT)
644WRAP(profile, ForgeNumericalProfile, S_PROFILE)
645WRAP(calibration, ForgeCalibrationArtifact, S_CALIBRATION)
646WRAP(evidence, ForgeExecutionEvidenceV2, S_EVIDENCE)
647WRAP(ref, ForgeCrossMachineRef, S_REF)
648#undef WRAP
649
650int forge_v2_digest_machine(const ForgeMachineDescriptorV2 *m, uint8_t out[32]) { return digest_obj(&S_MACHINE, m, out); }
651int forge_v2_digest_substrate(const ForgeSubstrateDescriptor *s, uint8_t out[32]) { return digest_obj(&S_SUBSTRATE, s, out); }
652int forge_v2_digest_contract(const ForgeSemanticResultContract *c, uint8_t out[32]) { return digest_obj(&S_CONTRACT, c, out); }
653int forge_v2_digest_calibration(const ForgeCalibrationArtifact *a, uint8_t out[32]) { return digest_obj(&S_CALIBRATION, a, out); }
654int forge_v2_digest_evidence(const ForgeExecutionEvidenceV2 *e, uint8_t out[32]) { return digest_obj(&S_EVIDENCE, e, out); }
655int forge_v2_digest_ref(const ForgeCrossMachineRef *r, uint8_t out[32]) { return digest_obj(&S_REF, r, out); }
656
657/* ------------------------------------------------------------------ */
658/* realization identity, calibration, eligibility, authority */
659/* ------------------------------------------------------------------ */
660
661void forge_v2_realization_identity(const uint8_t contract_digest[32], const uint8_t machine_identity[32],
662 const uint8_t substrate_digest[32], const uint8_t code_digest[32],
663 const uint8_t *calibration_digest, uint8_t out[32])
664{
665 static const char domain[16] = { 'F','O','R','G','E','-','V','2','-','R','E','A','L','I','Z','E' };
666 uint8_t in[16 + 32 * 4 + 1 + 32];
667 memcpy(in, domain, 16);
668 memcpy(in + 16, contract_digest, 32);
669 memcpy(in + 48, machine_identity, 32);
670 memcpy(in + 80, substrate_digest, 32);
671 memcpy(in + 112, code_digest, 32);
672 in[144] = calibration_digest ? 1 : 0;
673 if (calibration_digest) memcpy(in + 145, calibration_digest, 32);
674 else memset(in + 145, 0, 32);
675 forge_v2_sha256(in, sizeof in, out);
676}
677
678int forge_v2_calibration_check(const ForgeSubstrateDescriptor *s, const ForgeCalibrationArtifact *a,
679 const ForgeV2Conditions *now)
680{
681 if (!s || !now) return FORGE_V2_ERR_ARG;
682 if (!s->calibration_required) return FORGE_V2_OK;
683 if (!a) return FORGE_V2_ERR_CAL_MISSING;
684 if (val_calibration(a) != FORGE_V2_OK) return FORGE_V2_ERR_VALUE;
685 if (memcmp(a->substrate_id, s->substrate_identity, 32) != 0) return FORGE_V2_ERR_CAL_MISMATCH;
686 if (!(s->calibration_method_mask & (1u << a->method))) return FORGE_V2_ERR_VALUE;
687 if (a->fixture_count < s->calibration_min_fixtures) return FORGE_V2_ERR_VALUE;
688 /* the artifact may not claim a longer window than the substrate allows */
689 uint64_t window = a->validity_window_s;
690 if (window > s->calibration_max_window_s) window = s->calibration_max_window_s;
691 if (now->execution_epoch_s < a->epoch_s) return FORGE_V2_ERR_CAL_STALE; /* from the future */
692 if (now->execution_epoch_s - a->epoch_s >= window) return FORGE_V2_ERR_CAL_STALE;
693 /* conditions outside the calibrated envelope invalidate the calibration */
694 if (now->temperature_mc < a->env_temp_min_mc || now->temperature_mc > a->env_temp_max_mc ||
695 now->supply_uv < a->env_supply_min_uv || now->supply_uv > a->env_supply_max_uv)
696 return FORGE_V2_ERR_OUT_OF_ENVELOPE;
697 return FORGE_V2_OK;
698}
699
700int forge_v2_substrate_eligible(const ForgeSubstrateDescriptor *s, const ForgeSemanticResultContract *c,
701 const ForgeCalibrationArtifact *cal, uint32_t fault_state,
702 const ForgeV2Conditions *now)
703{
704 int rc;
705 if (!s || !c) return FORGE_V2_ERR_ARG;
706 if (val_substrate(s) != FORGE_V2_OK || val_contract(c) != FORGE_V2_OK) return FORGE_V2_ERR_VALUE;
707 if (fault_state != FORGE_V2_FAULT_NONE) return FORGE_V2_ERR_FAULTED;
708 if (!(s->operation_families & c->operation_family)) return FORGE_V2_ERR_VALUE;
709 /* the substrate's error class must be no looser than the contract's */
710 if (s->error_kind > c->error_kind) return FORGE_V2_ERR_VALUE;
711 /* acceptance is |err| <= abs + rel_ppb * |reference| / 1e9, so a
712 * non-exact substrate fits only if both of its guaranteed bounds are
713 * within the contract's (a MEASURED_DISTRIBUTION contract with no
714 * bounds leaves the judgement to the measured evidence) */
715 if (s->error_kind != FORGE_V2_ERROR_EXACT && (c->error_rel_ppb != 0 || c->error_abs != 0)) {
716 if (s->error_rel_ppb > c->error_rel_ppb || s->error_abs > c->error_abs) return FORGE_V2_ERR_VALUE;
717 }
718 if ((rc = forge_v2_calibration_check(s, cal, now)) != FORGE_V2_OK) return rc;
719 return FORGE_V2_OK;
720}
721
722int forge_v2_validate_capability_ref(const ForgeCrossMachineRef *r, uint32_t effect_class, uint64_t current_generation)
723{
724 uint64_t need;
725 int rc;
726 if (!r) return FORGE_V2_ERR_ARG;
727 if ((rc = val_ref(r)) != FORGE_V2_OK) return rc;
728 switch (effect_class) {
729 case FORGE_V2_FX_PURE: need = FORGE_V2_RIGHT_EXECUTE_PURE; break;
730 case FORGE_V2_FX_READ: need = FORGE_V2_RIGHT_READ; break;
731 case FORGE_V2_FX_EXTERNAL_WRITE: need = FORGE_V2_RIGHT_CONFIGURE_REVERSIBLE; break;
732 case FORGE_V2_FX_EXTERNAL_IRREVERSIBLE: need = FORGE_V2_RIGHT_CONFIGURE_IRREVERSIBLE; break;
733 default: return FORGE_V2_ERR_ARG;
734 }
735 /* no stale handles: the full 64-bit generation must match exactly */
736 if (r->generation != current_generation) return FORGE_V2_ERR_STALE_GENERATION;
737 if (!(r->rights & need)) return FORGE_V2_ERR_RIGHTS;
738 return FORGE_V2_OK;
739}
740
741int forge_v2_eligible_set_has_digital_fallback(const ForgeV2Candidate *set, size_t n,
742 const uint8_t contract_digest[32])
743{
744 if (!set || !contract_digest) return 0;
745 for (size_t i = 0; i < n; i++)
746 if (class_digital(set[i].substrate_class) && memcmp(set[i].contract_digest, contract_digest, 32) == 0)
747 return 1;
748 return 0;
749}
750
751int forge_v2_admit_plan(const ForgeV2Candidate *set, size_t n, const uint8_t contract_digest[32])
752{
753 if (!contract_digest) return FORGE_V2_ERR_ARG;
754 return forge_v2_eligible_set_has_digital_fallback(set, n, contract_digest) ? FORGE_V2_OK
755 : FORGE_V2_ERR_NO_DIGITAL_FALLBACK;
756}
757
758const char *forge_v2_strerror(int err)
759{
760 switch (err) {
761 case FORGE_V2_OK: return "ok";
762 case FORGE_V2_ERR_ARG: return "bad argument";
763 case FORGE_V2_ERR_SPACE: return "output buffer too small";
764 case FORGE_V2_ERR_TRUNCATED: return "truncated input";
765 case FORGE_V2_ERR_MAGIC: return "bad magic";
766 case FORGE_V2_ERR_KIND: return "wrong object kind";
767 case FORGE_V2_ERR_VERSION: return "unknown version";
768 case FORGE_V2_ERR_LEGACY_VERSION: return "legacy version 1 refused";
769 case FORGE_V2_ERR_LENGTH: return "length mismatch";
770 case FORGE_V2_ERR_ORDER: return "fields out of canonical order";
771 case FORGE_V2_ERR_UNKNOWN_TAG: return "unknown tag (strict)";
772 case FORGE_V2_ERR_WIDTH: return "field width mismatch";
773 case FORGE_V2_ERR_MISSING: return "required field missing";
774 case FORGE_V2_ERR_COUNT: return "repeat count out of range";
775 case FORGE_V2_ERR_VALUE: return "value rule violated";
776 case FORGE_V2_ERR_NONCANONICAL: return "non-canonical encoding";
777 case FORGE_V2_ERR_GENERATION_32: return "32-bit capability generation refused";
778 case FORGE_V2_ERR_PROVENANCE: return "provenance_class missing or invalid";
779 case FORGE_V2_ERR_CAL_STALE: return "calibration stale";
780 case FORGE_V2_ERR_CAL_MISSING: return "calibration required but absent";
781 case FORGE_V2_ERR_CAL_MISMATCH: return "calibration names another substrate";
782 case FORGE_V2_ERR_FAULTED: return "substrate faulted or unavailable";
783 case FORGE_V2_ERR_STALE_GENERATION: return "stale capability generation";
784 case FORGE_V2_ERR_RIGHTS: return "right not held";
785 case FORGE_V2_ERR_RANGE: return "offset/length outside referenced object";
786 case FORGE_V2_ERR_DUPLICATE_ID: return "duplicate substrate identity";
787 case FORGE_V2_ERR_OUT_OF_ENVELOPE: return "conditions outside calibration envelope";
788 case FORGE_V2_ERR_NO_DIGITAL_FALLBACK: return "no digital fallback in eligible set";
789 default: return "unknown error";
790 }
791}