SDK library · Browser and Node

# mesh-transport

Carry sealed TSP bytes through simulated or LoRa links and courier bundles using trust-core's `Transport` contract. Simulation tests cover delivery and adapters; the README still identifies real-radio limits, sync-word format, and turnaround timing as assumptions to verify on hardware.

`@toip-tools/mesh-transport` · v0.1.0 · [Source](https://github.com/yourbuddyconner/toip-tools/blob/main/packages/mesh-transport/src/index.ts)

## Setup

Install the package from npm. It needs Node 22.13 or later, or a bundler for browser entry points.

Install:

```bash
npm install @toip-tools/mesh-transport
```

**Runtime:** Browsers and Node. The \`/gwmp\`, \`/detect\` and \`/node\` entry points are Node only.

Import:

```ts
import { MeshTransport, MeshGateway, ChallengeBeacon } from "@toip-tools/mesh-transport";
```

## Usage

### Run a Trust Task over simulated radio

Import `SimMedium` from `/sim`, create a `VirtualScheduler`, connect named nodes, and construct `MeshTransport` with local identities and links. Start it and pass it to trust-core's `Endpoint`; advance virtual time with `scheduler.run(requestPromise)`. Select trust-core's `ctt1` body codec only when `supportsCompact(peer)` is true, and size request deadlines using `suggestedTimeoutMs`.

[`MeshTransport`](https://toip.tools/toolkit/mesh-transport/api/MeshTransport/) · [`VirtualScheduler`](https://toip.tools/toolkit/mesh-transport/api/VirtualScheduler/) · [`plans`](https://toip.tools/toolkit/mesh-transport/api/plans/) · [`regions`](https://toip.tools/toolkit/mesh-transport/api/regions/) · [`MeshOptions`](https://toip.tools/toolkit/mesh-transport/api/MeshOptions/)

### Configure a real link and diagnose delivery

Choose matching regional/channel plans for both ends. Import `RakP2PLink` from `/rak` with a `/serial` Web Serial port or `/node` serial wrapper; Node's `/node` or `/gwmp` entry provides `GwmpServer` for a gateway packet forwarder. Monitor link state, mesh `onEvent`, and `stats()`. A GWMP link is not ready to send until the gateway has sent PULL\_DATA, even though `open()` resolves.

[`Link`](https://toip.tools/toolkit/mesh-transport/api/Link/) · [`LinkState`](https://toip.tools/toolkit/mesh-transport/api/LinkState/) · [`plans`](https://toip.tools/toolkit/mesh-transport/api/plans/) · [`MeshEvent`](https://toip.tools/toolkit/mesh-transport/api/MeshEvent/) · [`MeshStats`](https://toip.tools/toolkit/mesh-transport/api/MeshStats/) · [`AirtimeBudget`](https://toip.tools/toolkit/mesh-transport/api/AirtimeBudget/)

### Hand messages to a gateway or courier

Create `MeshGateway` with a mesh identity, relay transport, and custody store, then call `start()`. A custody receipt means the gateway or its relay outbox has responsibility, not that the recipient opened the task. For manual delivery, export pending messages with `mesh.exportBundle({ sealTo: courierDid })`, open them with `openBundle(bytes, courier)`, and pass items to `postBundle` through a relay.

[`MeshGateway`](https://toip.tools/toolkit/mesh-transport/api/MeshGateway/) · [`GatewayStore`](https://toip.tools/toolkit/mesh-transport/api/GatewayStore/) · [`exportBundle`](https://toip.tools/toolkit/mesh-transport/api/exportBundle/) · [`openBundle`](https://toip.tools/toolkit/mesh-transport/api/openBundle/) · [`postBundle`](https://toip.tools/toolkit/mesh-transport/api/postBundle/)

## Example

A signed, encrypted Trust Task crosses a simulated radio link, with no relay.

site/examples/snippets/mesh-transport.ts:

```ts
import { MeshTransport, plans, regions } from "@toip-tools/mesh-transport";
import { SimMedium, VirtualScheduler } from "@toip-tools/mesh-transport/sim";
import { Endpoint, ctt1, identityFromSeed, ourSpec, seedFrom } from "@toip-tools/trust-core";

// Demo seeds make identities repeatable. Real devices need securely generated seeds.
const guest = identityFromSeed(seedFrom("mesh-example/guest"));
const door = identityFromSeed(seedFrom("mesh-example/door"));
const scheduler = new VirtualScheduler();
const medium = new SimMedium({ scheduler, seed: 1 });
const radio = { setting: plans["us915-a"].tx, mtu: 250, budget: regions.us915 };
// Fixed radio jitter makes the simulation's scheduling repeatable.
const guestMesh = new MeshTransport({
  identities: [guest], links: [medium.node("guest", radio)], scheduler, random: () => 0.5,
});
const doorMesh = new MeshTransport({
  identities: [door], links: [medium.node("door", radio)], scheduler, random: () => 0.5,
});
medium.connect("guest", "door"); // Both radios are in range; the default is no loss.

// Endpoint still signs and seals the request. CTT1 compacts its signed body;
// MeshTransport fragments the sealed envelope and reassembles it at the door.
const guestEndpoint = new Endpoint({
  identity: guest, transport: guestMesh, clock: scheduler,
  bodyCodecFor: (to) => guestMesh.supportsCompact(to) ? ctt1 : undefined,
});
const doorEndpoint = new Endpoint({
  identity: door, transport: doorMesh, clock: scheduler,
  bodyCodecFor: (to) => doorMesh.supportsCompact(to) ? ctt1 : undefined,
});

const CHECK = ourSpec("example/door/check");
doorEndpoint.handle<{ challenge: string }, { accepted: boolean }>(CHECK, (doc) => ({
  accepted: doc.payload.challenge === "9f3a",
}));

try {
  await guestMesh.start();
  await doorMesh.start();
  // Resolve the peer's did:key locally. The first packet introduces the sender.
  guestMesh.addContact(door.did);
  doorMesh.addContact(guest.did);

  // run() advances virtual radio timers while the request waits for its reply.
  // Real radio adapters use real time; they do not need VirtualScheduler.run().
  const reply = await scheduler.run(guestEndpoint.request<{ challenge: string }, { accepted: boolean }>(
    door.did, CHECK, { challenge: "9f3a" }, { timeoutMs: 60_000 },
  ));
  console.log("Challenge accepted:", reply.payload.accepted);
  console.log("Reply signed by the door:", reply.issuer === door.did);
  console.log("Every radio frame fits the MTU:", medium.records().every((frame) => frame.bytes.length <= radio.mtu));
} finally {
  guestEndpoint.close();
  doorEndpoint.close();
  await guestMesh.stop();
  await doorMesh.stop();
}
```

Run from the repository root:

```bash
npx tsx --tsconfig site/tsconfig.json site/examples/snippets/mesh-transport.ts
```

Output:

```text
Challenge accepted: true
Reply signed by the door: true
Every radio frame fits the MTU: true
```

## Lifecycle and persistence

- Call `Endpoint.close()` to detach its application receiver, stop `ChallengeBeacon` and `MeshGateway` timers/handlers, then await `MeshTransport.stop()` to cancel mesh timers, unsubscribe link listeners, and close owned links. Gateway stop does not stop the mesh or relay transport; stop those separately.

- Contacts, outbox, and gateway custody records default to memory. Supply durable stores, or Node's `/node` file stores, to retain routing/introduction and delivery state across restarts. Pair the endpoint with a persistent replay guard when duplicate execution must survive reboot.

- Keep queued and custody items until your application's reconciliation policy resolves them. Check `pending()` and receipt/application responses; a transport return value is not proof that an external action occurred. Hardware adapters require deployment verification; Bluetooth, RNode link behavior, DOWN/PUBLIC delivery, and reliable-link mode are not implemented.

## Error handling

### `Delivery: undelivered / queued`

`post` returns `undelivered` for unusable local identities, unsplittable or mismatched TSP envelopes, unresolved recipients without a gateway, oversized packets, or explicit delivery refusal. Unconfirmed transmissions can remain `queued` for retry.

Check local identity/contact keys, packet size, route, and link state. Use transport events and application replies to distinguish refusal from a message still awaiting delivery.

### `MeshEvent: dropped`

Drop reasons include `regulatory`, `send-failed`, `incomplete`, `signature`, and `intro-refused`; counts appear in `stats().dropped`.

Investigate airtime/channel configuration and hardware errors for send failures, loss/MTU for incomplete packets, and peer keys/admission policy for signature or introduction failures. Never bypass airtime limits to force a retry.

### `Bundle-open exception`

`openBundle` throws for malformed/truncated bundles or a sealed bundle without the correct courier identity. `postBundle` reports counts of accepted and refused items.

Keep the original bundle, use the intended courier key, and inspect refused counts before considering the handoff complete.

### Limitations

- Hiding where you are. A transmitting radio can be located.

- Large payloads: a radio frame holds about 250 bytes.

## API reference

Choose an entry point for the complete export list. Each export has a reference page with its signature, parameter types, return type, fields, and public methods where applicable.

- [`@toip-tools/mesh-transport`](https://toip.tools/toolkit/mesh-transport/api/)

  Browser and Node · 70 exports

- [`@toip-tools/mesh-transport/sim`](https://toip.tools/toolkit/mesh-transport/api/sim/)

  Browser and Node · 9 exports

- [`@toip-tools/mesh-transport/serial`](https://toip.tools/toolkit/mesh-transport/api/serial/)

  Browser and Node · 3 exports

- [`@toip-tools/mesh-transport/rak`](https://toip.tools/toolkit/mesh-transport/api/rak/)

  Browser and Node · 2 exports

- [`@toip-tools/mesh-transport/gwmp`](https://toip.tools/toolkit/mesh-transport/api/gwmp/)

  Node only · 5 exports

- [`@toip-tools/mesh-transport/detect`](https://toip.tools/toolkit/mesh-transport/api/detect/)

  Node only · 6 exports

- [`@toip-tools/mesh-transport/node`](https://toip.tools/toolkit/mesh-transport/api/node/)

  Node only · 18 exports

## Related

### Guides

- [Send Trust Tasks over LoRa radio](https://toip.tools/guides/trust-tasks-over-lora/)

### Built on

- [`@toip-tools/trust-core`](https://toip.tools/toolkit/trust-core/): Identities, signed and encrypted Trust Tasks over TSP, credentials, status lists and local policy.

### Used by these examples

- [Capture](https://toip.tools/examples/#capture): Verifiable origins for photos and sensor readings.
- [Mesh](https://toip.tools/examples/#mesh): Trust Tasks beyond an internet connection.

### Concepts

[Concepts](https://toip.tools/concepts/) explains the protocols behind mesh-transport; the [FAQ](https://toip.tools/faq/) covers install, runtimes and support.

---

This is the Markdown version of https://toip.tools/toolkit/mesh-transport/. An index of the documentation for AI assistants is at https://toip.tools/llms.txt.
