space-data-module-sdk 0.9.3 → 0.9.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,7 +29,9 @@ import {
29
29
  hkdfBytes,
30
30
  secp256k1PublicKey,
31
31
  secp256k1SignDigest,
32
+ secp256k1SignMessage,
32
33
  secp256k1VerifyDigest,
34
+ secp256k1VerifyMessage,
33
35
  sha512Bytes,
34
36
  x25519PublicKey,
35
37
  x25519SharedSecret,
@@ -43,6 +45,7 @@ import {
43
45
  import {
44
46
  ADAPTER_CAPABILITIES,
45
47
  ADAPTER_OPERATIONS,
48
+ IPFS_ADAPTER_OPERATIONS,
46
49
  callServiceAdapter,
47
50
  normalizePluginConfig,
48
51
  resolveServiceAdapters,
@@ -112,6 +115,7 @@ export const NodeHostSupportedOperations = Object.freeze([
112
115
  "ipfs.invoke",
113
116
  "ipfs.add",
114
117
  "ipfs.cat",
118
+ ...IPFS_ADAPTER_OPERATIONS,
115
119
  "protocol_handle.register",
116
120
  "protocol_handle.unregister",
117
121
  "protocol_dial.dial",
@@ -2077,6 +2081,12 @@ export class NodeHost {
2077
2081
  this.#withCapability("ipfs", "ipfs.cat", async () =>
2078
2082
  invokeAdapterMethod(this._ipfsAdapter, "cat", params, "ipfs"),
2079
2083
  ),
2084
+ // ls, pin_add, pin_rm, pin_ls, dag_get, id, swarm_peers, name_resolve, name_publish, pubsub_publish
2085
+ ...Object.fromEntries(IPFS_ADAPTER_OPERATIONS.map((operation) => [operation.slice(5), async (params = {}) =>
2086
+ this.#withCapability("ipfs", operation, async () =>
2087
+ invokeAdapterMethod(this._ipfsAdapter, operation.slice(5), params, "ipfs"),
2088
+ ),
2089
+ ])),
2080
2090
  });
2081
2091
 
2082
2092
  this.protocolHandle = Object.freeze({
@@ -2392,6 +2402,9 @@ export class NodeHost {
2392
2402
  if (ADAPTER_OPERATIONS[normalized]) {
2393
2403
  return this.serveAdapterOperation(normalized, params);
2394
2404
  }
2405
+ if (IPFS_ADAPTER_OPERATIONS.includes(normalized)) {
2406
+ return this.ipfs[normalized.slice(5)](params);
2407
+ }
2395
2408
  throw new Error(`Unknown Node host operation "${normalized}".`);
2396
2409
  }
2397
2410
  }
@@ -2510,13 +2523,12 @@ export class NodeHost {
2510
2523
  ),
2511
2524
  ),
2512
2525
  // Message-based ECDSA-DER contract (parity with the Go/C++ hosts and the
2513
- // synchronous host-crypto ABI): sha256 the message internally, then use
2514
- // the digest-based primitives with DER <-> raw conversion.
2526
+ // synchronous host-crypto ABI): ECDSA over sha256(message) - the wallet's
2527
+ // message API hashes once - with DER <-> raw conversion.
2515
2528
  sign: async (message, privateKey) =>
2516
2529
  this.#withCapability("crypto_sign", "crypto.secp256k1.sign", async () => {
2517
- const digest = await sha256Bytes(toUint8Array(message));
2518
- const rawSignature = await secp256k1SignDigest(
2519
- toUint8Array(digest),
2530
+ const rawSignature = await secp256k1SignMessage(
2531
+ toUint8Array(message),
2520
2532
  toUint8Array(privateKey),
2521
2533
  );
2522
2534
  return rawSignatureToDer(rawSignature);
@@ -2526,9 +2538,8 @@ export class NodeHost {
2526
2538
  "crypto_verify",
2527
2539
  "crypto.secp256k1.verify",
2528
2540
  async () => {
2529
- const digest = await sha256Bytes(toUint8Array(message));
2530
- const result = await secp256k1VerifyDigest(
2531
- toUint8Array(digest),
2541
+ const result = await secp256k1VerifyMessage(
2542
+ toUint8Array(message),
2532
2543
  derSignatureToRaw(signature),
2533
2544
  toUint8Array(publicKey),
2534
2545
  );
@@ -2640,8 +2651,9 @@ export class NodeHost {
2640
2651
  `keyslot "${slotId}" is not a 32-byte secp256k1 private key`,
2641
2652
  );
2642
2653
  }
2643
- const digest = await sha256Bytes(payload);
2644
- const rawSignature = await secp256k1SignDigest(digest, keyMaterial);
2654
+ // ECDSA over sha256(payload), as the Go node's ecdsa.Sign(sha256(payload)):
2655
+ // the wallet's message API hashes once.
2656
+ const rawSignature = await secp256k1SignMessage(payload, keyMaterial);
2645
2657
  return {
2646
2658
  signature: bytesToBase64(rawSignatureToDer(rawSignature)),
2647
2659
  algorithm: "secp256k1",
@@ -65,6 +65,8 @@ function serializeChannelError(error, operation) {
65
65
  code: error?.code ?? null,
66
66
  operation: error?.operation ?? operation ?? null,
67
67
  capability: error?.capability ?? null,
68
+ // the typed hostcall's error code (typedDispatch.js hostcallErrorCode), so it survives the channel
69
+ hostcallCode: error?.hostcallCode ?? null,
68
70
  };
69
71
  }
70
72
 
@@ -141,6 +143,7 @@ export function createSabHostcallClientDispatch(options = {}) {
141
143
  error.code = value?.code ?? null;
142
144
  error.operation = value?.operation ?? operation;
143
145
  error.capability = value?.capability ?? null;
146
+ if (value?.hostcallCode) error.hostcallCode = value.hostcallCode;
144
147
  throw error;
145
148
  }
146
149
  return value;
@@ -11,7 +11,7 @@ import {
11
11
  encodeSqlValues,
12
12
  } from "../standards/runtimeContracts.js";
13
13
  import * as hostOps from "../generated/runtime/aligned/HostOps_aligned.js";
14
- import { deliverMode, reconcileKind, sandboxWant } from "../generated/runtime/aligned/HostOps_enums.js";
14
+ import { cryptoAlgorithm, deliverMode, reconcileKind, sandboxWant } from "../generated/runtime/aligned/HostOps_enums.js";
15
15
  import { base64ToBytes, bytesToBase64 } from "../utils/encoding.js";
16
16
 
17
17
  const textDecoder = new TextDecoder();
@@ -248,6 +248,58 @@ function pnmEntry(e) {
248
248
  });
249
249
  }
250
250
  const p2pRecords = (v) => (binary(v?.records) ? { records: binary(v.records) } : {});
251
+
252
+ // ---- keyslot, ipfs, pubsub, protocol: the Go node's request maps (bytes as base64) and answers ----------------------
253
+ // the HostOps cryptoAlgorithm enum -> the handlers' algorithm names (the Go node's cryptoAlgorithmNames; "" = default)
254
+ const KEYSLOT_ALGORITHMS = {
255
+ Default: "", Ed25519: "ed25519", Secp256k1: "secp256k1", X25519: "x25519", Sha256: "sha256", Sha512: "sha512", Aes256Gcm: "aes-256-gcm", HkdfSha256: "hkdf-sha256",
256
+ };
257
+ const BASE64 = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
258
+ /**
259
+ * A handler's binary answer (the Go node's bytesOf): bytes (Uint8Array, a typed view, an ArrayBuffer), base64 text or
260
+ * {__type: "bytes", base64}; undefined when it is none of them.
261
+ */
262
+ function answerBytes(v) {
263
+ const b = binary(v);
264
+ if (b) return b;
265
+ const encoded = typeof v === "string" ? v : v && typeof v === "object" && v.__type === "bytes" ? str(v.base64) : undefined;
266
+ if (encoded === undefined || !BASE64.test(encoded)) return undefined;
267
+ return base64ToBytes(encoded);
268
+ }
269
+ /** The bytes as one raw port (the Go node's dataAnswer / fieldBytes): no bytes is a failure. */
270
+ function bytesAnswer(port, field) {
271
+ return (v, { op }) => {
272
+ const value = field === undefined ? v : v && typeof v === "object" && !binary(v) ? v[field] : undefined;
273
+ const bytes = answerBytes(value);
274
+ if (!bytes) throw failed(`${op}: the host answered no ${field ?? "bytes"}`);
275
+ return { raw: { [port]: bytes } };
276
+ };
277
+ }
278
+ /** A raw port's bytes as base64 under `key` when the module sent it (the Go node's rawB64). */
279
+ function rawBase64(request, key, raw, port) {
280
+ if (raw[port] !== undefined) request[key] = bytesToBase64(raw[port]);
281
+ return request;
282
+ }
283
+ const intOf = (v) => { const n = Number(v); return Number.isFinite(n) ? Math.trunc(n) : 0; };
284
+ /** The answer's `field` (a list) as sorted text items (the Go node's listOfText). */
285
+ const textListOf = (field) => (v) => ({ lists: { items: (Array.isArray(v?.[field]) ? v[field] : []).map(str).sort().map((value) => ({ VALUE: value })) } });
286
+ const GO_DURATION_UNITS = { ns: 1e-6, us: 1e-3, "µs": 1e-3, "μs": 1e-3, ms: 1, s: 1000, m: 60_000, h: 3_600_000 };
287
+ /** A Go duration ("1h2m3.5s", "350µs", "-12ms") in milliseconds; 0 when unreadable (time.ParseDuration's error). */
288
+ function goDurationMs(v) {
289
+ const s = str(v);
290
+ if (s === "0") return 0;
291
+ const m = /^([-+]?)((?:(?:\d+\.?\d*|\.\d+)(?:ns|us|µs|μs|ms|s|m|h))+)$/.exec(s);
292
+ if (!m) return 0;
293
+ let total = 0;
294
+ for (const [, n, unit] of m[2].matchAll(/(\d+\.?\d*|\.\d+)(ns|us|µs|μs|ms|s|m|h)/g)) total += Number(n) * GO_DURATION_UNITS[unit];
295
+ return m[1] === "-" ? -total : total;
296
+ }
297
+ /** encoding/json's Marshal of a decoded JSON value: object keys sorted, <, >, & and U+2028 / U+2029 escaped. */
298
+ function goJson(v) {
299
+ const sortKeys = (x) => (Array.isArray(x) ? x.map(sortKeys) : x && typeof x === "object" ? Object.fromEntries(Object.keys(x).sort().map((k) => [k, sortKeys(x[k])])) : x);
300
+ return JSON.stringify(sortKeys(v) ?? null).replace(/[<>&\u2028\u2029]/g, (c) => `\\u${c.charCodeAt(0).toString(16).padStart(4, "0")}`);
301
+ }
302
+ const objectOf = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {});
251
303
  const p2pRequest = ({ params }) => withDeliver(lower(params), params);
252
304
  const objects = (v) => (Array.isArray(v) ? v.filter((x) => x && typeof x === "object") : []);
253
305
 
@@ -484,6 +536,66 @@ const ADAPTERS = {
484
536
  return { result, raw: binary(serving.stream) ? { stream: binary(serving.stream) } : {} };
485
537
  },
486
538
  },
539
+ // keyslot: the host's crypto oracle takes and answers base64 ({signature} / {plaintext})
540
+ "keyslot.sign": {
541
+ in: ({ params, raw }) => {
542
+ const request = { slotId: str(params?.SLOT_ID) };
543
+ const algorithm = KEYSLOT_ALGORITHMS[enumName(cryptoAlgorithm, params?.ALGORITHM)];
544
+ if (algorithm) request.algorithm = algorithm;
545
+ return rawBase64(request, "payload", raw, "payload");
546
+ },
547
+ out: bytesAnswer("data", "signature"),
548
+ },
549
+ "keyslot.unwrap": {
550
+ in: ({ params, raw }) => {
551
+ const request = { slotId: str(params?.SLOT_ID) };
552
+ rawBase64(request, "ephemeralPublicKey", raw, "ephemeral_public_key");
553
+ rawBase64(request, "nonce", raw, "nonce");
554
+ return rawBase64(request, "ciphertext", raw, "ciphertext");
555
+ },
556
+ out: bytesAnswer("data", "plaintext"),
557
+ },
558
+ // protocol: {target, protocolId, timeoutMs, payloadBase64} -> the peer's answer bytes
559
+ "protocol.request": {
560
+ in: ({ params, raw }) => {
561
+ const request = { target: str(params?.TARGET), protocolId: str(params?.PROTOCOL_ID) };
562
+ if (Number(params?.TIMEOUT_MS) > 0) request.timeoutMs = Number(params.TIMEOUT_MS);
563
+ return rawBase64(request, "payloadBase64", raw, "payload");
564
+ },
565
+ out: bytesAnswer("data"),
566
+ },
567
+ "pubsub.list_topics": { in: () => ({}), out: textListOf("topics") },
568
+ // ipfs: the record's set fields as lower-case keys; Kubo's answers ({Objects: [{Links}]}, {Pins}, {Keys}, {ID, ...})
569
+ "ipfs.cat": { in: ({ params }) => lower(params), out: bytesAnswer("data") },
570
+ // the DAG node as Kubo encodes it (dag-json); bytes pass as they are
571
+ "ipfs.dag_get": { in: ({ params }) => lower(params), out: (v) => ({ raw: { data: binary(v) ?? textEncoder.encode(goJson(v)) } }) },
572
+ "ipfs.ls": {
573
+ in: ({ params }) => lower(params),
574
+ out: (v) => ({ lists: { links: objects(objectOf(v).Objects).flatMap((o) => objects(o.Links)).map((l) => fit("IpfsLink", { NAME: str(l.Name), CID: str(l.Hash), SIZE: intOf(l.Size), TYPE: intOf(l.Type) })) } }),
575
+ },
576
+ "ipfs.pin_add": { in: ({ params }) => lower(params), out: textListOf("Pins") },
577
+ "ipfs.pin_rm": { in: ({ params }) => lower(params), out: textListOf("Pins") },
578
+ "ipfs.pin_ls": {
579
+ in: ({ params }) => lower(params),
580
+ out: (v) => {
581
+ const keys = objectOf(objectOf(v).Keys);
582
+ return { lists: { pins: Object.keys(keys).sort().map((cid) => fit("IpfsPin", { CID: cid, TYPE: str(objectOf(keys[cid]).Type) })) } };
583
+ },
584
+ },
585
+ "ipfs.name_resolve": { in: ({ params }) => lower(params), out: (v) => ({ result: fit("IpfsResult", { VALUE: str(v?.Path) }) }) },
586
+ "ipfs.name_publish": { in: ({ params }) => lower(params), out: (v) => ({ result: fit("IpfsResult", { NAME: str(v?.Name), VALUE: str(v?.Value) }) }) },
587
+ "ipfs.id": {
588
+ in: () => ({}),
589
+ out: (v) => ({
590
+ result: fit("IpfsResult", { NAME: str(v?.ID), VALUE: str(v?.PublicKey), AGENT_VERSION: str(v?.AgentVersion), PROTOCOL_VERSION: str(v?.ProtocolVersion) }),
591
+ lists: { addresses: (Array.isArray(v?.Addresses) ? v.Addresses : []).map((a) => ({ VALUE: str(a) })) },
592
+ }),
593
+ },
594
+ "ipfs.swarm_peers": {
595
+ in: () => ({}),
596
+ out: (v) => ({ lists: { peers: objects(objectOf(v).Peers).map((p) => fit("IpfsSwarmPeer", { PEER_ID: str(p.Peer), ADDRESS: str(p.Addr), LATENCY_MS: goDurationMs(p.Latency) })) } }),
597
+ },
598
+ "ipfs.pubsub_publish": { in: ({ params, raw }) => rawBase64({ topic: str(params?.TOPIC) }, "base64", raw, "data"), out: () => ({}) },
487
599
  // node status and activity
488
600
  "node_status_read.status": {
489
601
  in: () => ({}),
@@ -513,7 +625,8 @@ const ADAPTERS = {
513
625
  },
514
626
  };
515
627
  function data(v) { return { raw: { data: bytesOf(v) ?? new Uint8Array(0) } }; }
516
- function bool(v) { return { result: { VALUE: Boolean(v) } }; }
628
+ // a verify's answer: a boolean, or the hosts' {result: boolean} (the secp256k1 verifies) - an object is not "true"
629
+ function bool(v) { return { result: { VALUE: v !== null && typeof v === "object" ? v.result === true : Boolean(v) } }; }
517
630
  function socket(extra = () => ({})) {
518
631
  return {
519
632
  in: (call) => {
@@ -554,7 +667,8 @@ export function hostcallErrorCode(error) {
554
667
  if (/^Unknown .* operation|not available in the synchronous hostcall ABI|does not implement/.test(error?.message ?? "")) return "unsupported";
555
668
  // a string or list that does not fit its aligned record (the Go node's recordErr)
556
669
  if (/exceeds? the record/.test(error?.message ?? "")) return "too-large";
557
- if (error instanceof RangeError || error instanceof TypeError) return "invalid-params";
670
+ // (by name too: an error that crossed the worker harness's channel is a plain Error carrying the name)
671
+ if (error instanceof RangeError || error instanceof TypeError || name === "RangeError" || name === "TypeError") return "invalid-params";
558
672
  return "failed";
559
673
  }
560
674
 
package/src/index.d.ts CHANGED
@@ -680,6 +680,7 @@ export function assertDeploymentAuthorization(options: {
680
680
  now?: number;
681
681
  }): boolean;
682
682
 
683
+ /** signDigest signs the 32-byte digest as given (no further hashing). */
683
684
  export function createHdWalletSigner(options: {
684
685
  signDigest: (digest: Uint8Array) => Promise<Uint8Array>;
685
686
  publicKeyHex: string;
@@ -689,6 +690,7 @@ export function createHdWalletSigner(options: {
689
690
  curve?: string;
690
691
  }): Signer;
691
692
 
693
+ /** verifyDigest checks a signature over sha256(canonical bytes) as given (no further hashing). */
692
694
  export function createHdWalletVerifier(options: {
693
695
  verifyDigest: (
694
696
  digest: Uint8Array,
@@ -34,7 +34,6 @@ RUN set -eux; \
34
34
  ENV PATH="/opt/wasmedge/bin:${PATH}" \
35
35
  LD_LIBRARY_PATH="/opt/wasmedge/lib64:/opt/wasmedge/lib"
36
36
 
37
- COPY native/wasmedge_wasi_threads_runner.c /tmp/sdm-wasi-threads-runner.c
38
37
  # The SDN WasmEdge 0.16.4 patch series, byte-identical to SDN's testdata/
39
38
  # (sdn-server/internal/wasmrt/SUBSTRATE.md): 01-atomic-wait, 02-stop-token,
40
39
  # 03-fault-jmp, 04-atomic-memarg-offset. Order matters (02 and 04 both touch
@@ -69,6 +68,9 @@ RUN git clone --depth 1 --branch 0.16.4 https://github.com/WasmEdge/WasmEdge.git
69
68
  && cmake --install /tmp/wasmedge-build \
70
69
  && rm -rf /tmp/wasmedge-source /tmp/wasmedge-build \
71
70
  /tmp/01-atomic-wait.patch /tmp/02-stop-token.patch /tmp/03-fault-jmp.patch /tmp/04-atomic-memarg-offset.patch
71
+ # The runner (thread spawn + the hostcall bridge) last, so a runner change
72
+ # reuses the patched WasmEdge build layer above.
73
+ COPY native/wasmedge_wasi_threads_runner.c /tmp/sdm-wasi-threads-runner.c
72
74
  RUN cc /tmp/sdm-wasi-threads-runner.c -std=c11 -O2 -pthread -Wall -Wextra -Werror \
73
75
  -I/opt/sdm-wasmedge/include -L/opt/sdm-wasmedge/lib64 -L/opt/sdm-wasmedge/lib -lwasmedge \
74
76
  -Wl,--disable-new-dtags,-rpath,/opt/sdm-wasmedge/lib64,-rpath,/opt/sdm-wasmedge/lib \
@@ -2,6 +2,11 @@
2
2
  // CLI enables atomics but does not implement wasi.thread-spawn. Like the SDN
3
3
  // Go host, use a fresh instance per worker, shared memory, and ONE executor:
4
4
  // atomic.wait/notify waiters belong to the executor in this runtime revision.
5
+ // It also serves the typed hostcall bridge (space_data_module_host.call /
6
+ // response_len / read_response) of a module that imports it, single-threaded
7
+ // or not: the parity orchestrator stages the $PIV answers (plugin.getConfig ->
8
+ // the case's ModuleConfig, every other operation STATUS FAILED "unsupported"),
9
+ // encoded by the SDK's own encoder, and this runner replays them.
5
10
  #define _POSIX_C_SOURCE 200809L
6
11
  #include <wasmedge/wasmedge.h>
7
12
  #include <pthread.h>
@@ -31,6 +36,15 @@ typedef struct {
31
36
  bool exited;
32
37
  } Threads;
33
38
 
39
+ typedef struct {
40
+ uint8_t *data;
41
+ uint32_t size;
42
+ } Bytes;
43
+
44
+ // The staged answers; each thread reads back the answer to its own last call.
45
+ static Bytes hostcall_config, hostcall_unsupported;
46
+ static _Thread_local const Bytes *hostcall_response;
47
+
34
48
  static WasmEdge_String name(const char *s) {
35
49
  return WasmEdge_StringWrap(s, (uint32_t)strlen(s));
36
50
  }
@@ -150,6 +164,121 @@ static WasmEdge_ModuleInstanceContext *memory_import(Threads *g) {
150
164
  return env;
151
165
  }
152
166
 
167
+ static Bytes read_answer(const char *path) {
168
+ FILE *file = fopen(path, "rb");
169
+ if (!file) { fprintf(stderr, "cannot open hostcall answer %s\n", path); exit(2); }
170
+ Bytes bytes = {0};
171
+ if (fseek(file, 0, SEEK_END) != 0) exit(2);
172
+ long size = ftell(file);
173
+ if (size <= 0 || size > (1L << 30) || fseek(file, 0, SEEK_SET) != 0) { fprintf(stderr, "bad hostcall answer %s\n", path); exit(2); }
174
+ bytes.size = (uint32_t)size;
175
+ bytes.data = malloc(bytes.size);
176
+ if (!bytes.data || fread(bytes.data, 1, bytes.size, file) != bytes.size) { fprintf(stderr, "cannot read hostcall answer %s\n", path); exit(2); }
177
+ fclose(file);
178
+ return bytes;
179
+ }
180
+
181
+ // call(op_ptr, op_len, payload_ptr, payload_len) -> status: the answer is chosen by the operation name.
182
+ static WasmEdge_Result hostcall_call(void *data,
183
+ const WasmEdge_CallingFrameContext *frame, const WasmEdge_Value *in,
184
+ WasmEdge_Value *out) {
185
+ (void)data;
186
+ static const char config_op[] = "plugin.getConfig";
187
+ WasmEdge_MemoryInstanceContext *memory = WasmEdge_CallingFrameGetMemoryInstance(frame, 0);
188
+ uint32_t op_ptr = (uint32_t)WasmEdge_ValueGetI32(in[0]);
189
+ uint32_t op_len = (uint32_t)WasmEdge_ValueGetI32(in[1]);
190
+ const uint8_t *op = memory && op_len ? WasmEdge_MemoryInstanceGetPointerConst(memory, op_ptr, op_len) : NULL;
191
+ bool config = op && op_len == sizeof(config_op) - 1 && memcmp(op, config_op, op_len) == 0;
192
+ hostcall_response = config ? &hostcall_config : &hostcall_unsupported;
193
+ out[0] = WasmEdge_ValueGenI32(0);
194
+ return WasmEdge_Result_Success;
195
+ }
196
+
197
+ static WasmEdge_Result hostcall_response_len(void *data,
198
+ const WasmEdge_CallingFrameContext *frame, const WasmEdge_Value *in,
199
+ WasmEdge_Value *out) {
200
+ (void)data; (void)frame; (void)in;
201
+ out[0] = WasmEdge_ValueGenI32(hostcall_response ? (int32_t)hostcall_response->size : 0);
202
+ return WasmEdge_Result_Success;
203
+ }
204
+
205
+ // read_response(dst_ptr, dst_len) -> bytes copied (out of bounds traps, as in the JS bridge).
206
+ static WasmEdge_Result hostcall_read_response(void *data,
207
+ const WasmEdge_CallingFrameContext *frame, const WasmEdge_Value *in,
208
+ WasmEdge_Value *out) {
209
+ (void)data;
210
+ WasmEdge_MemoryInstanceContext *memory = WasmEdge_CallingFrameGetMemoryInstance(frame, 0);
211
+ int32_t dst_len = WasmEdge_ValueGetI32(in[1]);
212
+ uint32_t size = hostcall_response ? hostcall_response->size : 0;
213
+ if (dst_len < 0) return WasmEdge_Result_Fail;
214
+ uint32_t n = (uint32_t)dst_len < size ? (uint32_t)dst_len : size;
215
+ if (n) {
216
+ if (!memory) return WasmEdge_Result_Fail;
217
+ WasmEdge_Result result = WasmEdge_MemoryInstanceSetData(memory, hostcall_response->data, (uint32_t)WasmEdge_ValueGetI32(in[0]), n);
218
+ if (!WasmEdge_ResultOK(result)) return result;
219
+ }
220
+ out[0] = WasmEdge_ValueGenI32((int32_t)n);
221
+ return WasmEdge_Result_Success;
222
+ }
223
+
224
+ static WasmEdge_Result hostcall_clear_response(void *data,
225
+ const WasmEdge_CallingFrameContext *frame, const WasmEdge_Value *in,
226
+ WasmEdge_Value *out) {
227
+ (void)data; (void)frame; (void)in;
228
+ hostcall_response = NULL;
229
+ out[0] = WasmEdge_ValueGenI32(0);
230
+ return WasmEdge_Result_Success;
231
+ }
232
+
233
+ static WasmEdge_Result hostcall_last_status(void *data,
234
+ const WasmEdge_CallingFrameContext *frame, const WasmEdge_Value *in,
235
+ WasmEdge_Value *out) {
236
+ (void)data; (void)frame; (void)in;
237
+ out[0] = WasmEdge_ValueGenI32(0);
238
+ return WasmEdge_Result_Success;
239
+ }
240
+
241
+ static void add_host_function(WasmEdge_ModuleInstanceContext *module, const char *field,
242
+ uint32_t params, WasmEdge_HostFunc_t function) {
243
+ WasmEdge_ValType i32[4] = {WasmEdge_ValTypeGenI32(), WasmEdge_ValTypeGenI32(),
244
+ WasmEdge_ValTypeGenI32(), WasmEdge_ValTypeGenI32()};
245
+ WasmEdge_FunctionTypeContext *type = WasmEdge_FunctionTypeCreate(i32, params, i32, 1);
246
+ WasmEdge_FunctionInstanceContext *instance = WasmEdge_FunctionInstanceCreate(type, function, NULL, 0);
247
+ WasmEdge_FunctionTypeDelete(type);
248
+ if (!instance) exit(1);
249
+ WasmEdge_ModuleInstanceAddFunction(module, name(field), instance);
250
+ }
251
+
252
+ // The bridge, registered when the module imports space_data_module_host; NULL otherwise.
253
+ static WasmEdge_ModuleInstanceContext *hostcall_import(Threads *g,
254
+ const char *config_path, const char *unsupported_path) {
255
+ uint32_t count = WasmEdge_ASTModuleListImportsLength(g->ast);
256
+ const WasmEdge_ImportTypeContext **imports = calloc(count, sizeof(*imports));
257
+ if (count && !imports) exit(1);
258
+ WasmEdge_ASTModuleListImports(g->ast, imports, count);
259
+ bool bridged = false;
260
+ for (uint32_t i = 0; i < count; ++i) {
261
+ if (WasmEdge_StringIsEqual(WasmEdge_ImportTypeGetModuleName(imports[i]), name("space_data_module_host"))) bridged = true;
262
+ }
263
+ free(imports);
264
+ if (!bridged) return NULL;
265
+ if (!config_path || !unsupported_path) {
266
+ fprintf(stderr, "module imports space_data_module_host: pass --sdm-hostcall-config and --sdm-hostcall-unsupported\n");
267
+ exit(2);
268
+ }
269
+ hostcall_config = read_answer(config_path);
270
+ hostcall_unsupported = read_answer(unsupported_path);
271
+ WasmEdge_ModuleInstanceContext *host = WasmEdge_ModuleInstanceCreate(name("space_data_module_host"));
272
+ if (!host) exit(1);
273
+ add_host_function(host, "call", 4, hostcall_call);
274
+ add_host_function(host, "response_len", 0, hostcall_response_len);
275
+ add_host_function(host, "read_response", 2, hostcall_read_response);
276
+ add_host_function(host, "clear_response", 0, hostcall_clear_response);
277
+ add_host_function(host, "last_status_code", 0, hostcall_last_status);
278
+ require_result("register hostcall bridge", WasmEdge_ExecutorRegisterImport(g->executor, g->store, host));
279
+ return host;
280
+ }
281
+
153
282
  // Direct calls use the same PIV request/response bytes as commands. Stage the
154
283
  // request through the public allocator, then monitor the direct call with the
155
284
  // same worker-group lifecycle as _start. No guest ABI is reimplemented. The
@@ -217,7 +346,7 @@ int main(int argc, char **argv) {
217
346
  return 2;
218
347
  }
219
348
  if (argc == 2 && strcmp(argv[1], "--version") == 0) {
220
- printf("wasmedge version %s\nsdm-wasi-threads-runner 1\n",
349
+ printf("wasmedge version %s\nsdm-wasi-threads-runner 2\n",
221
350
  WasmEdge_VersionGet());
222
351
  return 0;
223
352
  }
@@ -229,11 +358,20 @@ int main(int argc, char **argv) {
229
358
  uint32_t env_count = 0;
230
359
  bool stats = false;
231
360
  bool force_direct = false;
361
+ const char *hostcall_config_path = NULL, *hostcall_unsupported_path = NULL;
232
362
  int first = 1;
233
363
  for (; first < argc; ++first) {
234
364
  if (strcmp(argv[first], "--enable-threads") == 0) continue;
235
365
  if (strcmp(argv[first], "--sdm-thread-stats") == 0) { stats = true; continue; }
236
366
  if (strcmp(argv[first], "--sdm-direct") == 0) { force_direct = true; continue; }
367
+ if (strcmp(argv[first], "--sdm-hostcall-config") == 0 && first + 1 < argc) {
368
+ hostcall_config_path = argv[++first];
369
+ continue;
370
+ }
371
+ if (strcmp(argv[first], "--sdm-hostcall-unsupported") == 0 && first + 1 < argc) {
372
+ hostcall_unsupported_path = argv[++first];
373
+ continue;
374
+ }
237
375
  if (strcmp(argv[first], "--env") == 0 && first + 1 < argc) {
238
376
  envs[env_count++] = argv[++first];
239
377
  continue;
@@ -241,7 +379,7 @@ int main(int argc, char **argv) {
241
379
  break;
242
380
  }
243
381
  if (first >= argc || argv[first][0] == '-') {
244
- fprintf(stderr, "usage: %s [--sdm-direct] [--env NAME=VALUE] module.wasm [args...]\n", argv[0]);
382
+ fprintf(stderr, "usage: %s [--sdm-direct] [--sdm-hostcall-config FILE --sdm-hostcall-unsupported FILE] [--env NAME=VALUE] module.wasm [args...]\n", argv[0]);
245
383
  free(envs);
246
384
  return 2;
247
385
  }
@@ -262,6 +400,7 @@ int main(int argc, char **argv) {
262
400
  require_result("register WASI", WasmEdge_ExecutorRegisterImport(
263
401
  g.executor, g.store, wasi));
264
402
  WasmEdge_ModuleInstanceContext *env = memory_import(&g);
403
+ WasmEdge_ModuleInstanceContext *host = hostcall_import(&g, hostcall_config_path, hostcall_unsupported_path);
265
404
  WasmEdge_ModuleInstanceContext *threads = WasmEdge_ModuleInstanceCreate(name("wasi"));
266
405
  WasmEdge_ValType i32 = WasmEdge_ValTypeGenI32();
267
406
  WasmEdge_FunctionTypeContext *type = WasmEdge_FunctionTypeCreate(&i32, 1, &i32, 1);
@@ -341,6 +480,9 @@ int main(int argc, char **argv) {
341
480
  WasmEdge_ModuleInstanceDelete(instance);
342
481
  WasmEdge_ModuleInstanceDelete(threads);
343
482
  if (env) WasmEdge_ModuleInstanceDelete(env);
483
+ if (host) WasmEdge_ModuleInstanceDelete(host);
484
+ free(hostcall_config.data);
485
+ free(hostcall_unsupported.data);
344
486
  WasmEdge_ModuleInstanceDelete(wasi);
345
487
  WasmEdge_StoreDelete(g.store);
346
488
  WasmEdge_ASTModuleDelete(g.ast);
@@ -7,12 +7,13 @@
7
7
  * realities, which is exactly what this lane exists to catch.
8
8
  *
9
9
  * Protocol with the lane server (same origin):
10
- * GET /plan -> {threadEnvVar, cases:[{id, stdinBase64, env, args, threadCounts}]}
10
+ * GET /plan -> {threadEnvVar, cases:[{id, stdinBase64, env, args, threadCounts, config}]}
11
11
  * GET /module.wasm -> the ONE isomorphic artifact
12
12
  * POST /done -> {runs:[...]} on completion or {fatal} on runner failure
13
13
  */
14
14
 
15
15
  import { createBrowserModuleHarness } from "../host/browserModuleHarness.js";
16
+ import { parityHostcallDispatch } from "./parityHostcalls.js";
16
17
 
17
18
  const OK = "ok";
18
19
  const GUEST_ERROR = "guest-error";
@@ -107,6 +108,9 @@ export async function runParityPlanInBrowser({ baseUrl = "" } = {}) {
107
108
  maxThreads: threadCount,
108
109
  wasiThreadWorkerUrl: new URL("/wasi-thread-worker.js", globalThis.location.href).href,
109
110
  args: planCase.args,
111
+ // the hostcall bridge (an artifact that imports it): plugin.getConfig answers the case's config, any other
112
+ // operation is unsupported - the answers the WasmEdge lanes' runner replays
113
+ hostcallDispatch: parityHostcallDispatch(planCase.config),
110
114
  env: {
111
115
  ...planCase.env,
112
116
  [plan.threadEnvVar]: String(threadCount),
@@ -162,6 +162,14 @@ function normalizeEnv(env, label) {
162
162
  return normalized;
163
163
  }
164
164
 
165
+ function normalizeConfig(config, label) {
166
+ if (config === undefined || config === null) return null;
167
+ if (typeof config !== "object" || Array.isArray(config)) {
168
+ throw new Error(`Parity fixture ${label}: config must be an object.`);
169
+ }
170
+ return Object.freeze(structuredClone(config));
171
+ }
172
+
165
173
  function normalizeExpect(expect, label) {
166
174
  if (expect === undefined || expect === null) return null;
167
175
  const value = String(expect);
@@ -208,9 +216,14 @@ function normalizeThreadCounts(threadCounts, label) {
208
216
  * id,
209
217
  * request?: {methodId, inputs:[{portId, payloadFile|payloadBase64|payloadHex|payloadUtf8, typeRef?}], ...},
210
218
  * stdinFile? | stdinBase64? | stdinHex? | stdinUtf8?,
211
- * env?, args?, expect?: "ok"|"guest-error"|"trap", threadCounts?
212
- * }]
219
+ * env?, args?, expect?: "ok"|"guest-error"|"trap", threadCounts?,
220
+ * config?
221
+ * }],
222
+ * config?
213
223
  * }
224
+ *
225
+ * config (an object; the case's replaces the fixture's, default {}) is what
226
+ * the module's plugin.getConfig hostcall answers in every lane.
214
227
  */
215
228
  export async function normalizeParityFixture(fixture, options = {}) {
216
229
  if (!fixture || typeof fixture !== "object") {
@@ -222,6 +235,7 @@ export async function normalizeParityFixture(fixture, options = {}) {
222
235
  const fixtureThreadCounts =
223
236
  normalizeThreadCounts(fixture.threadCounts, name) ?? DEFAULT_THREAD_COUNTS;
224
237
  const fixtureEnv = normalizeEnv(fixture.env, name);
238
+ const fixtureConfig = normalizeConfig(fixture.config, name) ?? {};
225
239
  const fixtureArgs = Array.isArray(fixture.args)
226
240
  ? fixture.args.map(String)
227
241
  : [];
@@ -281,6 +295,7 @@ export async function normalizeParityFixture(fixture, options = {}) {
281
295
  Array.isArray(caseSpec.args) ? caseSpec.args.map(String) : fixtureArgs,
282
296
  ),
283
297
  expect: normalizeExpect(caseSpec.expect, label),
298
+ config: normalizeConfig(caseSpec.config, label) ?? fixtureConfig,
284
299
  threadCounts:
285
300
  normalizeThreadCounts(caseSpec.threadCounts, label) ??
286
301
  fixtureThreadCounts,
@@ -0,0 +1,40 @@
1
+ // The typed hostcall bridge (space_data_module_host.call / response_len / read_response, src/host/cpp/typedHostcall.hpp)
2
+ // as every parity lane serves it: plugin.getConfig answers the case's config as one ModuleConfig on raw "config" - the
3
+ // answer the SDK JS hosts give (typedDispatch.js) - and every other operation a STATUS FAILED "unsupported" $PIV
4
+ // answer. The browser lane dispatches through answerTypedHostCall; the WasmEdge lanes' runner replays these bytes,
5
+ // encoded here by the SDK's own encoder and staged beside the module.
6
+ import { DEFAULT_HOSTCALL_IMPORT_MODULE } from "../host/abi.js";
7
+ import { hostcallErrorCode, typedResultOf } from "../host/typedDispatch.js";
8
+ import { encodeHostCallResult } from "../standards/runtimeContracts.js";
9
+
10
+ export const PARITY_HOSTCALL_MODULE = DEFAULT_HOSTCALL_IMPORT_MODULE;
11
+ export const PARITY_UNSUPPORTED_MESSAGE = "the parity harness serves only plugin.getConfig";
12
+ /** The staged answers' file names (the WasmEdge runner's --sdm-hostcall-config / --sdm-hostcall-unsupported). */
13
+ export const PARITY_HOSTCALL_FILES = Object.freeze({ config: "sdm-hostcall-config.piv", unsupported: "sdm-hostcall-unsupported.piv" });
14
+
15
+ const unsupported = () => Object.assign(new Error(PARITY_UNSUPPORTED_MESSAGE), { hostcallCode: "unsupported" });
16
+
17
+ /** Whether a compiled module imports the hostcall bridge. */
18
+ export function importsHostcallBridge(wasmModule) {
19
+ return WebAssembly.Module.imports(wasmModule).some((entry) => entry.module === PARITY_HOSTCALL_MODULE);
20
+ }
21
+
22
+ /** The bridge's dispatch for one case (the browser lane): plugin.getConfig -> the config; anything else unsupported. */
23
+ export function parityHostcallDispatch(config) {
24
+ return (operation) => {
25
+ if (operation === "plugin.getConfig") return config ?? {};
26
+ throw unsupported();
27
+ };
28
+ }
29
+
30
+ /** The $PIV answers the WasmEdge runner replays for one case: {config, unsupported} bytes. */
31
+ export function encodeParityHostcallAnswers(config) {
32
+ const failure = (error) => encodeHostCallResult({ ok: false, error: { code: hostcallErrorCode(error), message: String(error?.message ?? error) } });
33
+ let answer;
34
+ try {
35
+ answer = encodeHostCallResult({ ok: true, op: "plugin.getConfig", ...typedResultOf({ op: "plugin.getConfig" }, config ?? {}) });
36
+ } catch (error) {
37
+ answer = failure(error);
38
+ }
39
+ return { config: answer, unsupported: failure(unsupported()) };
40
+ }