@chaincraft/core 1.0.0 → 1.2.0

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.
package/README.md CHANGED
@@ -1,27 +1,80 @@
1
1
  # @chaincraft/core
2
2
 
3
3
  TypeScript implementation of the Chaincraft wire protocol and object semantics.
4
+ Release **[1.2.0](https://www.npmjs.com/package/@chaincraft/core)** on npm.
5
+
6
+ Open-source toolkit for peer-to-peer protocols like blockchains, chat rooms,
7
+ BitTorrent swarms, and content-addressed stores.
4
8
 
5
9
  ## Install
6
10
 
7
11
  ```bash
8
12
  npm install @chaincraft/core
13
+ npm install --global @chaincraft/core
9
14
  ```
10
15
 
16
+ The node binary is `chaincraft-ts-node`. Default listen is `0.0.0.0:9735`.
17
+
11
18
  The unscoped npm name `chaincraft` belongs to another project. This package is
12
19
  `@chaincraft/core`, alongside the `chaincraft` crate and the `chaincraft` Python
13
20
  package.
14
21
 
15
- ## Example
22
+ ## Browser
16
23
 
17
- Assumes `@chaincraft/core` is installed.
24
+ `@chaincraft/core/browser` does not import `node:net`. `Mesh` stays on the Node
25
+ entry. A page asks the PeerJS broker for an id and passes `peerOptions()` to
26
+ `Peer`. The default broker is `https://dechess-org-peerjs.vercel.app`.
18
27
 
19
- ```ts
20
- import { Envelope, encodeFrame } from "@chaincraft/core";
28
+ ```js
29
+ import { fetchPeerId, peerOptions } from "@chaincraft/core/browser";
21
30
 
22
- const env = Envelope.build("app.counter", { by: "alice", delta: 1 });
23
- const frame = encodeFrame(env.toBytes());
31
+ const id = await fetchPeerId();
32
+ const peer = new Peer(id, peerOptions());
24
33
  ```
25
34
 
35
+ The data channel is the caller's. `EnvelopeRelay` is the in-memory stand-in
36
+ used by the conformance vectors.
37
+
38
+ ## Hello World
39
+
40
+ Two TCP nodes in one process. A listens on `9735`, B on `9736`, B dials A and
41
+ gossips `app.hello`. Save as `hello.mjs` and run `node hello.mjs`.
42
+
43
+ ```js
44
+ import { Mesh } from "@chaincraft/core";
45
+
46
+ const a = new Mesh();
47
+ const b = new Mesh();
48
+ a.onApp = (_t, data) => {
49
+ console.log("Received:", data.message);
50
+ };
51
+
52
+ console.log("listening", await a.start("127.0.0.1", 9735));
53
+ console.log("listening", await b.start("127.0.0.1", 9736));
54
+ await b.connect(a.listenAddr);
55
+ const id = b.broadcast("app.hello", { message: "Hello, Chaincraft!" });
56
+ await new Promise((r) => setTimeout(r, 400));
57
+ console.log(id);
58
+ a.close();
59
+ b.close();
60
+ ```
61
+
62
+ CLI, three languages on one loopback mesh:
63
+
64
+ ```bash
65
+ python3 -m chaincraft.node
66
+ chaincraft-node 127.0.0.1:9736
67
+ chaincraft-ts-node 127.0.0.1:9737
68
+ ```
69
+
70
+ Then `{"cmd":"connect","addr":"127.0.0.1:9735"}` on the last two, and
71
+ `{"cmd":"send","type":"app.hello","data":{"message":"Hello, Chaincraft!"}}` on
72
+ Python.
73
+
74
+ Further local nodes take unused ports and connect. Remote hosts dial this
75
+ machine's unicast IPv4 or DNS name on 9735. `connect` allows loopback,
76
+ RFC1918, public unicast IPv4, `localhost`, `.local`, and ordinary DNS names.
77
+ Each mesh keeps at most 256 peers.
78
+
26
79
  Specification and the other implementations live in the
27
80
  [monorepo](https://github.com/jose-compu/chaincraft-monorepo).
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Browser entry for @chaincraft/core.
3
+ *
4
+ * No TCP mesh and no UDP socket. PeerJS options default to the public
5
+ * broker at DEFAULT_PEER_ORIGIN. Opening the data channel is the caller's
6
+ * `new Peer(id, peerOptions())`.
7
+ */
8
+ export { Envelope } from './envelope.ts';
9
+ export { BaseSharedObject } from './object.ts';
10
+ export { parseAddress } from './channel.ts';
11
+ export { DEFAULT_PEER_ORIGIN, PEER_KEY, EnvelopeRelay, fetchPeerId, isPeerId, parsePeerIdBody, peerOptions, type PeerOptions, type RelayItem, } from './peer.ts';
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Browser entry for @chaincraft/core.
3
+ *
4
+ * No TCP mesh and no UDP socket. PeerJS options default to the public
5
+ * broker at DEFAULT_PEER_ORIGIN. Opening the data channel is the caller's
6
+ * `new Peer(id, peerOptions())`.
7
+ */
8
+ export { Envelope } from "./envelope.js";
9
+ export { BaseSharedObject } from "./object.js";
10
+ export { parseAddress } from "./channel.js";
11
+ export { DEFAULT_PEER_ORIGIN, PEER_KEY, EnvelopeRelay, fetchPeerId, isPeerId, parsePeerIdBody, peerOptions, } from "./peer.js";
package/dist/btNode.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ #!/usr/bin/env node
1
2
  /**
2
3
  * BitTorrent mesh client — Swarm on top of the Level 0 mesh.
3
4
  *
package/dist/btNode.js CHANGED
@@ -1,3 +1,4 @@
1
+ #!/usr/bin/env node
1
2
  /**
2
3
  * BitTorrent mesh client — Swarm on top of the Level 0 mesh.
3
4
  *
@@ -5,7 +6,7 @@
5
6
  */
6
7
  import * as readline from 'node:readline';
7
8
  import { BitTorrentClient, IMPL, ProtocolError } from "./index.js";
8
- import { Mesh } from "./mesh.js";
9
+ import { Mesh, parseListen } from "./mesh.js";
9
10
  const MAX_STDIN_LINE = 1_048_576;
10
11
  function emit(event) {
11
12
  process.stdout.write(`${JSON.stringify(event)}\n`);
@@ -13,7 +14,8 @@ function emit(event) {
13
14
  const mesh = new Mesh(IMPL, emit);
14
15
  const client = new BitTorrentClient((typeName, data) => mesh.broadcast(typeName, data));
15
16
  mesh.onApp = (typeName, data) => client.onApp(typeName, data);
16
- await mesh.start();
17
+ const listen = parseListen(process.argv[2]);
18
+ await mesh.start(listen.host, listen.port);
17
19
  emit({ event: 'ready', addr: mesh.listenAddr, impl: IMPL });
18
20
  const rl = readline.createInterface({ input: process.stdin });
19
21
  for await (const line of rl) {
package/dist/channel.d.ts CHANGED
@@ -6,6 +6,7 @@ export interface ParsedAddress {
6
6
  canonical: string;
7
7
  cap: string;
8
8
  }
9
+ export declare function isPeerId(value: string): boolean;
9
10
  export declare function parseAddress(raw: string): ParsedAddress;
10
11
  export declare function isConnectAllowed(raw: string): boolean;
11
12
  export interface InboxItem {
package/dist/channel.js CHANGED
@@ -5,7 +5,10 @@ const FAIL = { ok: false, scheme: '', canonical: '', cap: '' };
5
5
  const AUTHORITY = new Set(['tcp', 'udp']);
6
6
  const COLON = ['mailto', 'webrtc', 'forum', 'loop', 'pipe'];
7
7
  const HEX = /^[0-9a-f]+$/;
8
- const HEX64 = /^[0-9a-f]{64}$/;
8
+ const PEER_ID = /^[A-Za-z0-9_-]{1,64}$/;
9
+ export function isPeerId(value) {
10
+ return PEER_ID.test(value);
11
+ }
9
12
  const LOCAL = /^[A-Za-z0-9._+-]{1,64}$/;
10
13
  const LABEL = /^[a-z0-9](?:[a-z0-9-]{0,30}[a-z0-9])?$/;
11
14
  const THREAD = /^[A-Za-z0-9._-]{1,64}$/;
@@ -58,7 +61,7 @@ function parseColon(scheme, rest) {
58
61
  return ok(scheme, `mailto:${rest}`);
59
62
  }
60
63
  if (scheme === 'webrtc') {
61
- if (!HEX64.test(rest))
64
+ if (!isPeerId(rest))
62
65
  return { ...FAIL };
63
66
  return ok(scheme, `webrtc:${rest}`);
64
67
  }
package/dist/discovery.js CHANGED
@@ -8,17 +8,20 @@ export function isResolvedIpAllowed(ip) {
8
8
  const labels = ip.split('.');
9
9
  if (labels.length !== 4 || !labels.every((label) => /^[0-9]+$/.test(label)))
10
10
  return false;
11
- const a = Number(labels[0]);
12
- const b = Number(labels[1]);
13
- if (a === 127)
14
- return true;
15
- if (a === 10)
16
- return true;
17
- if (a === 192 && b === 168)
18
- return true;
19
- if (a === 172 && b >= 16 && b <= 31)
20
- return true;
21
- return false;
11
+ const first = labels[0];
12
+ const second = labels[1];
13
+ if (first === undefined || second === undefined)
14
+ return false;
15
+ const octets = labels.map((label) => Number(label));
16
+ if (octets.some((octet) => !Number.isSafeInteger(octet) || octet > 255))
17
+ return false;
18
+ const a = Number(first);
19
+ const b = Number(second);
20
+ if (a === 0 || a >= 224)
21
+ return false;
22
+ if (a === 169 && b === 254)
23
+ return false;
24
+ return true;
22
25
  }
23
26
  export function isConnectAllowed(address) {
24
27
  if (!isValidAddress(address))
@@ -26,10 +29,11 @@ export function isConnectAllowed(address) {
26
29
  const split = splitHostPort(address);
27
30
  if (!split)
28
31
  return false;
29
- const lowered = split.host.toLowerCase();
30
- if (lowered === 'localhost' || lowered.endsWith('.local'))
31
- return true;
32
- return isResolvedIpAllowed(split.host);
32
+ const labels = split.host.split('.');
33
+ if (labels.length === 4 && labels.every((label) => /^[0-9]+$/.test(label))) {
34
+ return isResolvedIpAllowed(split.host);
35
+ }
36
+ return true;
33
37
  }
34
38
  export function isValidAddress(address) {
35
39
  const split = splitHostPort(address);
@@ -7,9 +7,9 @@
7
7
  *
8
8
  * Add an ID here only when the feature is implemented and its vectors pass.
9
9
  */
10
- export declare const VERSION = "1.0.0";
10
+ export declare const VERSION = "1.2.0";
11
11
  export declare const WIRE_VERSION = 1;
12
- export declare const IMPL = "ts-chaincraft/1.0.0";
12
+ export declare const IMPL = "ts-chaincraft/1.2.0";
13
13
  export declare const LANGUAGE = "typescript";
14
14
  export declare const FEATURES: readonly string[];
15
15
  export interface Manifest {
package/dist/features.js CHANGED
@@ -7,7 +7,7 @@
7
7
  *
8
8
  * Add an ID here only when the feature is implemented and its vectors pass.
9
9
  */
10
- export const VERSION = '1.0.0';
10
+ export const VERSION = '1.2.0';
11
11
  export const WIRE_VERSION = 1;
12
12
  export const IMPL = `ts-chaincraft/${VERSION}`;
13
13
  export const LANGUAGE = 'typescript';
@@ -52,6 +52,7 @@ export const FEATURES = [
52
52
  'channel.udp',
53
53
  'channel.mailto',
54
54
  'channel.webrtc',
55
+ 'channel.peer',
55
56
  'channel.forum',
56
57
  'channel.pipe',
57
58
  'app.pubsub',
package/dist/index.d.ts CHANGED
@@ -29,6 +29,7 @@ export { AdapterBus, AdapterChannel, UdpLink, MAX_FORUM_BYTES, MAX_MAIL_BYTES, M
29
29
  export { NodeSession } from './cli.ts';
30
30
  export { BitTorrentClient, Swarm, WIRE_TYPE, MAX_NAME_LEN, MAX_PEER_ID_LEN, infoHash, pieceHash, splitPayload, } from './bittorrent.ts';
31
31
  export { Mesh } from './mesh.ts';
32
+ export { DEFAULT_PEER_ORIGIN, PEER_KEY, EnvelopeRelay, fetchPeerId, isPeerId, parsePeerIdBody, peerOptions, type PeerOptions, type RelayItem, } from './peer.ts';
32
33
  export { type CodecResult as NatCodecResult, type HandleOut as NatHandle, type NatMessage, type ParsedBinding, type Punch as NatPunch, type RelayOut as NatRelay, APP_NAT, NatTraversal, PUNCH_HEX, bindingRequest, bindingSuccess, parseBindingResponse, } from './nat.ts';
33
34
  export * as ecdsa from './ecdsa.ts';
34
35
  export * as vdf from './vdf.ts';
package/dist/index.js CHANGED
@@ -29,6 +29,7 @@ export { AdapterBus, AdapterChannel, UdpLink, MAX_FORUM_BYTES, MAX_MAIL_BYTES, M
29
29
  export { NodeSession } from "./cli.js";
30
30
  export { BitTorrentClient, Swarm, WIRE_TYPE, MAX_NAME_LEN, MAX_PEER_ID_LEN, infoHash, pieceHash, splitPayload, } from "./bittorrent.js";
31
31
  export { Mesh } from "./mesh.js";
32
+ export { DEFAULT_PEER_ORIGIN, PEER_KEY, EnvelopeRelay, fetchPeerId, isPeerId, parsePeerIdBody, peerOptions, } from "./peer.js";
32
33
  export { APP_NAT, NatTraversal, PUNCH_HEX, bindingRequest, bindingSuccess, parseBindingResponse, } from "./nat.js";
33
34
  export * as ecdsa from "./ecdsa.js";
34
35
  export * as vdf from "./vdf.js";
package/dist/mesh.d.ts CHANGED
@@ -6,10 +6,15 @@
6
6
  import * as net from 'node:net';
7
7
  import { type JsonValue } from './canonical.ts';
8
8
  import { Deduplicator } from './dedup.ts';
9
- export declare const MAX_PEERS = 16;
9
+ export declare const MAX_PEERS = 256;
10
10
  export declare const MAX_RECEIVED = 4096;
11
11
  export declare const CONNECT_TIMEOUT_MS = 5000;
12
12
  export declare const NODE_MAX_FRAME = 262144;
13
+ export declare const DEFAULT_LISTEN = "0.0.0.0:9735";
14
+ export declare function parseListen(raw?: string): {
15
+ host: string;
16
+ port: number;
17
+ };
13
18
  export type MeshEvent = Record<string, unknown>;
14
19
  export type AppHandler = (typeName: string, data: JsonValue) => void;
15
20
  export type LinkHandler = (addr: string, typeName: string, data: JsonValue) => void;
package/dist/mesh.js CHANGED
@@ -13,10 +13,23 @@ import { Envelope } from "./envelope.js";
13
13
  import { ProtocolError } from "./errors.js";
14
14
  import { IMPL } from "./features.js";
15
15
  import { FrameReader, encodeFrame } from "./framing.js";
16
- export const MAX_PEERS = 16;
16
+ export const MAX_PEERS = 256;
17
17
  export const MAX_RECEIVED = 4096;
18
18
  export const CONNECT_TIMEOUT_MS = 5000;
19
19
  export const NODE_MAX_FRAME = 262_144;
20
+ export const DEFAULT_LISTEN = '0.0.0.0:9735';
21
+ export function parseListen(raw) {
22
+ const text = raw && raw.length > 0 ? raw : DEFAULT_LISTEN;
23
+ const idx = text.lastIndexOf(':');
24
+ if (idx <= 0)
25
+ throw new Error('listen must be host:port');
26
+ const host = text.slice(0, idx);
27
+ const port = Number(text.slice(idx + 1));
28
+ if (!host || !Number.isInteger(port) || port < 0 || port > 65535) {
29
+ throw new Error('invalid listen');
30
+ }
31
+ return { host, port };
32
+ }
20
33
  export class Mesh {
21
34
  impl;
22
35
  dedup = new Deduplicator();
package/dist/node.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ #!/usr/bin/env node
1
2
  /**
2
3
  * Minimal TCP mesh node — SPEC/wire-v1.md §4, §5, §7, §8.
3
4
  *
package/dist/node.js CHANGED
@@ -1,3 +1,4 @@
1
+ #!/usr/bin/env node
1
2
  /**
2
3
  * Minimal TCP mesh node — SPEC/wire-v1.md §4, §5, §7, §8.
3
4
  *
@@ -5,13 +6,14 @@
5
6
  */
6
7
  import * as readline from 'node:readline';
7
8
  import { IMPL, ProtocolError } from "./index.js";
8
- import { Mesh } from "./mesh.js";
9
+ import { Mesh, parseListen } from "./mesh.js";
9
10
  const MAX_STDIN_LINE = 1_048_576;
10
11
  function emit(event) {
11
12
  process.stdout.write(`${JSON.stringify(event)}\n`);
12
13
  }
13
14
  const mesh = new Mesh(IMPL, emit);
14
- await mesh.start();
15
+ const listen = parseListen(process.argv[2]);
16
+ await mesh.start(listen.host, listen.port);
15
17
  emit({ event: 'ready', addr: mesh.listenAddr, impl: IMPL });
16
18
  const rl = readline.createInterface({ input: process.stdin });
17
19
  for await (const line of rl) {
package/dist/peer.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ /** PeerJS ids, broker options, and an in-memory cross-scheme relay.
2
+ *
3
+ * SPEC/features/channel-peer.md. Signaling is an HTTP GET. The relay does not
4
+ * open an ICE data channel. This module does not import node:net.
5
+ */
6
+ import type { JsonValue } from './canonical.ts';
7
+ import { isPeerId } from './channel.ts';
8
+ export declare const DEFAULT_PEER_ORIGIN = "https://dechess-org-peerjs.vercel.app";
9
+ export declare const PEER_KEY = "peerjs";
10
+ export interface PeerOptions {
11
+ host: string;
12
+ port: number;
13
+ path: string;
14
+ secure: boolean;
15
+ key: string;
16
+ }
17
+ export interface RelayItem {
18
+ id: string;
19
+ type: string;
20
+ from: string;
21
+ }
22
+ export { isPeerId };
23
+ export declare function parsePeerIdBody(text: string): string | undefined;
24
+ export declare function peerOptions(origin?: string): PeerOptions;
25
+ export declare function fetchPeerId(origin?: string): Promise<string>;
26
+ export declare class EnvelopeRelay {
27
+ private readonly order;
28
+ private readonly inbox;
29
+ private readonly seen;
30
+ join(addr: string): boolean;
31
+ publish(src: string, typeName: string, data: JsonValue): string | undefined;
32
+ take(addr: string): RelayItem[];
33
+ }
package/dist/peer.js ADDED
@@ -0,0 +1,92 @@
1
+ /** PeerJS ids, broker options, and an in-memory cross-scheme relay.
2
+ *
3
+ * SPEC/features/channel-peer.md. Signaling is an HTTP GET. The relay does not
4
+ * open an ICE data channel. This module does not import node:net.
5
+ */
6
+ import { isPeerId, parseAddress } from "./channel.js";
7
+ import { Envelope } from "./envelope.js";
8
+ import { ProtocolError } from "./errors.js";
9
+ export const DEFAULT_PEER_ORIGIN = 'https://dechess-org-peerjs.vercel.app';
10
+ export const PEER_KEY = 'peerjs';
11
+ const RELAY = new Set(['udp', 'mailto', 'webrtc', 'forum', 'pipe']);
12
+ export { isPeerId };
13
+ export function parsePeerIdBody(text) {
14
+ const ident = text.trim();
15
+ if (!isPeerId(ident))
16
+ return undefined;
17
+ return ident;
18
+ }
19
+ export function peerOptions(origin = DEFAULT_PEER_ORIGIN) {
20
+ const parsed = new URL(origin);
21
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
22
+ throw new Error('peer origin must be http or https');
23
+ }
24
+ const secure = parsed.protocol === 'https:';
25
+ const port = parsed.port ? Number(parsed.port) : secure ? 443 : 80;
26
+ if (!parsed.hostname)
27
+ throw new Error('peer origin must be http or https');
28
+ return { host: parsed.hostname, port, path: '/', secure, key: PEER_KEY };
29
+ }
30
+ export async function fetchPeerId(origin = DEFAULT_PEER_ORIGIN) {
31
+ const response = await fetch(`${origin.replace(/\/$/, '')}/peerjs/id`, {
32
+ headers: { Accept: 'text/plain' },
33
+ });
34
+ if (!response.ok)
35
+ throw new Error(`peer id fetch failed: ${response.status}`);
36
+ const ident = parsePeerIdBody(await response.text());
37
+ if (ident === undefined)
38
+ throw new Error('invalid peer id');
39
+ return ident;
40
+ }
41
+ export class EnvelopeRelay {
42
+ order = [];
43
+ inbox = new Map();
44
+ seen = new Set();
45
+ join(addr) {
46
+ const parsed = parseAddress(addr);
47
+ if (!parsed.ok || !RELAY.has(parsed.scheme))
48
+ return false;
49
+ if (this.inbox.has(parsed.canonical))
50
+ return false;
51
+ this.order.push(parsed.canonical);
52
+ this.inbox.set(parsed.canonical, []);
53
+ return true;
54
+ }
55
+ publish(src, typeName, data) {
56
+ const parsed = parseAddress(src);
57
+ if (!parsed.ok || !this.inbox.has(parsed.canonical))
58
+ return undefined;
59
+ let env;
60
+ try {
61
+ env = Envelope.build(typeName, data, { ts: 0 });
62
+ }
63
+ catch (error) {
64
+ if (error instanceof ProtocolError)
65
+ return undefined;
66
+ throw error;
67
+ }
68
+ if (this.seen.has(env.id))
69
+ return env.id;
70
+ this.seen.add(env.id);
71
+ const item = { id: env.id, type: env.type, from: parsed.canonical };
72
+ for (const member of this.order) {
73
+ if (member === parsed.canonical)
74
+ continue;
75
+ const box = this.inbox.get(member);
76
+ if (box)
77
+ box.push({ ...item });
78
+ }
79
+ return env.id;
80
+ }
81
+ take(addr) {
82
+ const parsed = parseAddress(addr);
83
+ if (!parsed.ok)
84
+ return [];
85
+ const box = this.inbox.get(parsed.canonical);
86
+ if (!box)
87
+ return [];
88
+ const out = box.slice();
89
+ box.length = 0;
90
+ return out;
91
+ }
92
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chaincraft/core",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "A platform for decentralized protocols — wire, objects, and pedagogical consensus",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -23,8 +23,16 @@
23
23
  ".": {
24
24
  "types": "./dist/index.d.ts",
25
25
  "default": "./dist/index.js"
26
+ },
27
+ "./browser": {
28
+ "types": "./dist/browser.d.ts",
29
+ "default": "./dist/browser.js"
26
30
  }
27
31
  },
32
+ "bin": {
33
+ "chaincraft-ts-node": "dist/node.js",
34
+ "chaincraft-ts-bt-node": "dist/btNode.js"
35
+ },
28
36
  "files": [
29
37
  "dist",
30
38
  "README.md",