@chaincraft/core 1.2.0 → 1.4.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,11 +1,20 @@
1
1
  # @chaincraft/core
2
2
 
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.
3
+ TypeScript implementation of the Chaincraft wire protocol, object semantics, and
4
+ Level 2 stack (consensus, ledgers, BitTorrent, channels). Same observable
5
+ behaviour as the Python `chaincraft` package and the Rust `chaincraft` crate.
6
+ Release **[1.4.0](https://www.npmjs.com/package/@chaincraft/core)** on npm.
7
+ 1.4.0 adds pedagogical Avalanche (Slush, Snowflake, Snowball) and a
8
+ last-write-wins CRDT.
5
9
 
6
10
  Open-source toolkit for peer-to-peer protocols like blockchains, chat rooms,
7
11
  BitTorrent swarms, and content-addressed stores.
8
12
 
13
+ Node **20+**, ESM only (`"type": "module"`). The default entry and `Mesh` use
14
+ `node:net`; browser consumers can use the `@chaincraft/core/browser` entry.
15
+ Raw UDP is the one registry exemption (browsers have no UDP socket). The
16
+ unscoped npm name `chaincraft` belongs to another project.
17
+
9
18
  ## Install
10
19
 
11
20
  ```bash
@@ -13,11 +22,16 @@ npm install @chaincraft/core
13
22
  npm install --global @chaincraft/core
14
23
  ```
15
24
 
16
- The node binary is `chaincraft-ts-node`. Default listen is `0.0.0.0:9735`.
25
+ Global binaries: `chaincraft-ts-node` (mesh CLI) and `chaincraft-ts-bt-node`
26
+ (BitTorrent client on the same mesh). Default listen is `0.0.0.0:9735`.
27
+
28
+ Without a global install:
17
29
 
18
- The unscoped npm name `chaincraft` belongs to another project. This package is
19
- `@chaincraft/core`, alongside the `chaincraft` crate and the `chaincraft` Python
20
- package.
30
+ ```bash
31
+ npx chaincraft-ts-node
32
+ # or
33
+ node node_modules/@chaincraft/core/dist/node.js
34
+ ```
21
35
 
22
36
  ## Browser
23
37
 
@@ -35,9 +49,40 @@ const peer = new Peer(id, peerOptions());
35
49
  The data channel is the caller's. `EnvelopeRelay` is the in-memory stand-in
36
50
  used by the conformance vectors.
37
51
 
38
- ## Hello World
52
+ ## Envelope
53
+
54
+ `id` is SHA-256 of the canonical payload. Keys are sorted. There is no floating
55
+ point on the wire.
56
+
57
+ ```ts
58
+ import { Envelope, encodeFrame } from "@chaincraft/core";
59
+
60
+ const env = Envelope.build("app.hello", { message: "Hello, Chaincraft!" });
61
+ const frame = encodeFrame(env.toBytes());
62
+ console.log(env.id, frame.length);
63
+ ```
64
+
65
+ ## Object
66
+
67
+ A prototype implements `receive`. Attach it to `Mesh.onApp`. Reject with
68
+ `isValid`. Consensus objects override `addMessage` and the snapshot.
69
+
70
+ ```ts
71
+ import { BaseSharedObject, type JsonValue } from "@chaincraft/core";
72
+
73
+ class Hello extends BaseSharedObject {
74
+ lines: string[] = [];
75
+ receive(message: JsonValue): void {
76
+ const text = (message as { message?: string }).message ?? "";
77
+ this.lines.push(text);
78
+ console.log("Received:", text);
79
+ }
80
+ }
81
+ ```
82
+
83
+ ## Hello World (TCP)
39
84
 
40
- Two TCP nodes in one process. A listens on `9735`, B on `9736`, B dials A and
85
+ Two nodes in one process. A listens on `9735`, B on `9736`, B dials A and
41
86
  gossips `app.hello`. Save as `hello.mjs` and run `node hello.mjs`.
42
87
 
43
88
  ```js
@@ -59,7 +104,24 @@ a.close();
59
104
  b.close();
60
105
  ```
61
106
 
62
- CLI, three languages on one loopback mesh:
107
+ ## CLI
108
+
109
+ JSON lines on stdin. Events on stdout.
110
+
111
+ ```bash
112
+ chaincraft-ts-node
113
+ chaincraft-ts-node 127.0.0.1:9737
114
+ ```
115
+
116
+ | `cmd` | Fields | Effect |
117
+ |---|---|---|
118
+ | `connect` | `addr` | Dial `host:port`, complete `ctl.hello` |
119
+ | `send` | `type`, `data` | Gossip an application envelope |
120
+ | `ids` | — | Payload ids this process has recorded |
121
+ | `quit` | — | Stop |
122
+
123
+ Three languages on one loopback mesh: Python holds `9735`, Rust `9736`,
124
+ TypeScript `9737`.
63
125
 
64
126
  ```bash
65
127
  python3 -m chaincraft.node
@@ -67,14 +129,41 @@ chaincraft-node 127.0.0.1:9736
67
129
  chaincraft-ts-node 127.0.0.1:9737
68
130
  ```
69
131
 
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.
132
+ On terminals 2 and 3:
133
+
134
+ ```json
135
+ {"cmd":"connect","addr":"127.0.0.1:9735"}
136
+ ```
137
+
138
+ On terminal 1:
139
+
140
+ ```json
141
+ {"cmd":"send","type":"app.hello","data":{"message":"Hello, Chaincraft!"}}
142
+ ```
143
+
144
+ `sent.id` is the same digest on every language. `{"cmd":"ids"}` lists it.
145
+ BitTorrent is a separate process: `chaincraft-ts-bt-node`.
146
+
147
+ ## Network
148
+
149
+ Further local nodes take unused ports and `connect`. Remote hosts dial this
150
+ machine's unicast IPv4 or DNS name on 9735. Default bind is `0.0.0.0:9735`;
151
+ loopback Hello World still uses `127.0.0.1:9735`.
152
+
153
+ `connect` allows loopback, RFC1918, public unicast IPv4, `localhost`, `.local`,
154
+ and ordinary DNS names. Unspecified (`0.0.0.0`), link-local, multicast, and
155
+ reserved addresses are refused. One mesh process keeps at most 256 live peers.
156
+
157
+ ## Library
73
158
 
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.
159
+ | Area | Entry |
160
+ |---|---|
161
+ | Wire | `Envelope`, `encodeFrame`, `canonicalJson`, `sign` / `verify` |
162
+ | Objects | `BaseSharedObject`, `ObjectRegistry`, `StateMemento` |
163
+ | Mesh | `Mesh`, `parseListen` |
164
+ | Gossip apps | `PubSub`, `Stream`, `BitTorrentClient` |
165
+ | Chain | `ProofOfWork`, `ProofOfStake`, `PBFT`, `BalanceLedger`, `UtxoLedger`, `Mempool` |
166
+ | Discovery | `AddressBook`, `NatTraversal`, `parseAddress` |
78
167
 
79
- Specification and the other implementations live in the
168
+ Specification and the Python and Rust implementations live in the
80
169
  [monorepo](https://github.com/jose-compu/chaincraft-monorepo).
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  /** Node JSON-lines command surface — SPEC/features/cli-node.md. */
2
2
  import { parseJson, payloadDigest } from "./canonical.js";
3
3
  import { CanonicalError } from "./errors.js";
4
- import { isValidAddress } from "./discovery.js";
4
+ import { parseAddress } from "./channel.js";
5
5
  const TYPE_RE = /^[a-z0-9._-]{1,64}$/;
6
6
  function asRecord(value) {
7
7
  if (value === null || typeof value !== 'object' || Array.isArray(value)) {
@@ -62,7 +62,7 @@ export class NodeSession {
62
62
  }
63
63
  connect(command) {
64
64
  const addr = command['addr'];
65
- if (typeof addr !== 'string' || !isValidAddress(addr))
65
+ if (typeof addr !== 'string' || !parseAddress(addr).ok)
66
66
  return [error('invalid address')];
67
67
  if (!this.peers.includes(addr))
68
68
  this.peers.push(addr);
@@ -0,0 +1,43 @@
1
+ /** Slush, Snowflake, and Snowball — SPEC/features/consensus-avalanche.md. */
2
+ import type { JsonValue } from './canonical.ts';
3
+ import { StateMemento } from './memento.ts';
4
+ import { BaseSharedObject } from './object.ts';
5
+ export declare const PHASES: readonly ["slush", "snowflake", "snowball"];
6
+ export declare const COLORS: readonly ["blue", "red"];
7
+ export declare const DEFAULT_K = 2;
8
+ export declare const DEFAULT_ALPHA = 2;
9
+ export declare const DEFAULT_BETA = 2;
10
+ type Phase = (typeof PHASES)[number];
11
+ export declare class Avalanche extends BaseSharedObject {
12
+ readonly phase: Phase;
13
+ readonly k: number;
14
+ readonly alpha: number;
15
+ readonly beta: number;
16
+ pref: string;
17
+ finalized: boolean;
18
+ cnt: number;
19
+ rounds: number;
20
+ private dBlue;
21
+ private dRed;
22
+ constructor(phase?: string, k?: number, alpha?: number, beta?: number);
23
+ isValid(message: JsonValue): boolean;
24
+ addMessage(message: JsonValue, _frontierState?: StateMemento | undefined): StateMemento | undefined;
25
+ emitStateMemento(): StateMemento;
26
+ getStateDigests(): string[];
27
+ isMerkelized(): boolean;
28
+ state(): {
29
+ cnt: number;
30
+ d: {
31
+ blue: number;
32
+ red: number;
33
+ };
34
+ final: boolean;
35
+ phase: Phase;
36
+ pref: string;
37
+ rounds: number;
38
+ };
39
+ private confidence;
40
+ private applyRound;
41
+ private parse;
42
+ }
43
+ export {};
@@ -0,0 +1,162 @@
1
+ /** Slush, Snowflake, and Snowball — SPEC/features/consensus-avalanche.md. */
2
+ import { StateMemento } from "./memento.js";
3
+ import { BaseSharedObject, merkleDigest } from "./object.js";
4
+ export const PHASES = ['slush', 'snowflake', 'snowball'];
5
+ export const COLORS = ['blue', 'red'];
6
+ export const DEFAULT_K = 2;
7
+ export const DEFAULT_ALPHA = 2;
8
+ export const DEFAULT_BETA = 2;
9
+ function asRecord(message) {
10
+ if (message === null || typeof message !== 'object' || Array.isArray(message)) {
11
+ return undefined;
12
+ }
13
+ return message;
14
+ }
15
+ function isPhase(value) {
16
+ return PHASES.includes(value);
17
+ }
18
+ function isColor(value) {
19
+ return COLORS.includes(value);
20
+ }
21
+ export class Avalanche extends BaseSharedObject {
22
+ phase;
23
+ k;
24
+ alpha;
25
+ beta;
26
+ pref = '';
27
+ finalized = false;
28
+ cnt = 0;
29
+ rounds = 0;
30
+ dBlue = 0;
31
+ dRed = 0;
32
+ constructor(phase = 'snowball', k = DEFAULT_K, alpha = DEFAULT_ALPHA, beta = DEFAULT_BETA) {
33
+ super();
34
+ if (!isPhase(phase)) {
35
+ throw new RangeError('phase must be slush, snowflake, or snowball');
36
+ }
37
+ if (!Number.isSafeInteger(k) || k < 1 || k > 16) {
38
+ throw new RangeError('k must be in 1..16');
39
+ }
40
+ if (!Number.isSafeInteger(alpha) || alpha < 1 || alpha > k || alpha * 2 <= k) {
41
+ throw new RangeError('alpha must be in 1..k and greater than k/2');
42
+ }
43
+ if (!Number.isSafeInteger(beta) || beta < 1 || beta > 16) {
44
+ throw new RangeError('beta must be in 1..16');
45
+ }
46
+ this.phase = phase;
47
+ this.k = k;
48
+ this.alpha = alpha;
49
+ this.beta = beta;
50
+ }
51
+ isValid(message) {
52
+ return this.parse(message) !== undefined;
53
+ }
54
+ addMessage(message, _frontierState) {
55
+ const parsed = this.parse(message);
56
+ if (parsed === undefined)
57
+ return this.emitStateMemento();
58
+ if (parsed.kind === 'init') {
59
+ this.pref = parsed.color;
60
+ }
61
+ else {
62
+ this.applyRound(parsed.winner);
63
+ }
64
+ return this.emitStateMemento();
65
+ }
66
+ emitStateMemento() {
67
+ return StateMemento.normalize(merkleDigest({ state: this.state(), v: 1 }), []);
68
+ }
69
+ getStateDigests() {
70
+ const head = this.emitStateMemento().canonicalDigest;
71
+ return head ? [head] : [];
72
+ }
73
+ isMerkelized() {
74
+ return true;
75
+ }
76
+ state() {
77
+ return {
78
+ cnt: this.cnt,
79
+ d: { blue: this.dBlue, red: this.dRed },
80
+ final: this.finalized,
81
+ phase: this.phase,
82
+ pref: this.pref,
83
+ rounds: this.rounds,
84
+ };
85
+ }
86
+ confidence(color) {
87
+ if (color === 'blue')
88
+ return this.dBlue;
89
+ if (color === 'red')
90
+ return this.dRed;
91
+ return 0;
92
+ }
93
+ applyRound(winner) {
94
+ this.rounds += 1;
95
+ if (winner === undefined) {
96
+ if (this.phase === 'snowflake')
97
+ this.cnt = 0;
98
+ return;
99
+ }
100
+ if (this.phase === 'slush') {
101
+ this.pref = winner;
102
+ return;
103
+ }
104
+ if (this.phase === 'snowflake') {
105
+ if (this.pref === '' || this.pref === winner) {
106
+ this.pref = winner;
107
+ this.cnt += 1;
108
+ }
109
+ else {
110
+ this.pref = winner;
111
+ this.cnt = 1;
112
+ }
113
+ if (this.cnt >= this.beta)
114
+ this.finalized = true;
115
+ return;
116
+ }
117
+ if (winner === 'blue')
118
+ this.dBlue += 1;
119
+ else
120
+ this.dRed += 1;
121
+ const dColor = this.confidence(winner);
122
+ const dPref = this.confidence(this.pref);
123
+ if (this.pref === '' || dColor > dPref || (dColor === dPref && winner < this.pref)) {
124
+ this.pref = winner;
125
+ }
126
+ if (this.confidence(this.pref) >= this.beta)
127
+ this.finalized = true;
128
+ }
129
+ parse(message) {
130
+ const record = asRecord(message);
131
+ if (record === undefined || record['consensus'] !== 'avalanche')
132
+ return undefined;
133
+ const op = record['op'];
134
+ if (op === 'init') {
135
+ const color = record['color'];
136
+ if (typeof color !== 'string' || !isColor(color) || this.pref)
137
+ return undefined;
138
+ return { kind: 'init', color };
139
+ }
140
+ if (op !== 'round' || this.finalized)
141
+ return undefined;
142
+ const votes = record['votes'];
143
+ if (!Array.isArray(votes) || votes.length !== this.k)
144
+ return undefined;
145
+ let blue = 0;
146
+ let red = 0;
147
+ for (const vote of votes) {
148
+ if (vote !== 'blue' && vote !== 'red')
149
+ return undefined;
150
+ if (vote === 'blue')
151
+ blue += 1;
152
+ else
153
+ red += 1;
154
+ }
155
+ let winner;
156
+ if (blue >= this.alpha)
157
+ winner = 'blue';
158
+ if (red >= this.alpha)
159
+ winner = 'red';
160
+ return { kind: 'round', winner };
161
+ }
162
+ }
package/dist/crdt.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ /** Last-write-wins key-value CRDT — SPEC/features/protocol-crdt-kv.md. */
2
+ import { type JsonValue } from './canonical.ts';
3
+ import { BaseSharedObject } from './object.ts';
4
+ export declare const MAX_KEYS = 32;
5
+ export declare const MAX_VALUE = 256;
6
+ export interface CrdtKvState {
7
+ keys: Array<{
8
+ deleted: boolean;
9
+ key: string;
10
+ ts: number;
11
+ value: string;
12
+ writer: string;
13
+ }>;
14
+ }
15
+ export declare class CrdtKv extends BaseSharedObject {
16
+ private readonly keys;
17
+ isValid(message: JsonValue): boolean;
18
+ receive(message: JsonValue): void;
19
+ state(): CrdtKvState;
20
+ private parse;
21
+ }
package/dist/crdt.js ADDED
@@ -0,0 +1,101 @@
1
+ /** Last-write-wins key-value CRDT — SPEC/features/protocol-crdt-kv.md. */
2
+ import { MAX_SAFE_INT, compareCodePoints } from "./canonical.js";
3
+ import { BaseSharedObject } from "./object.js";
4
+ export const MAX_KEYS = 32;
5
+ export const MAX_VALUE = 256;
6
+ const NAME = /^[A-Za-z0-9._-]{1,64}$/;
7
+ function isInt(value) {
8
+ return typeof value === 'number' && Number.isSafeInteger(value);
9
+ }
10
+ function asRecord(message) {
11
+ if (message === null || typeof message !== 'object' || Array.isArray(message)) {
12
+ return undefined;
13
+ }
14
+ return message;
15
+ }
16
+ export class CrdtKv extends BaseSharedObject {
17
+ keys = new Map();
18
+ isValid(message) {
19
+ return this.parse(message) !== undefined;
20
+ }
21
+ receive(message) {
22
+ const parsed = this.parse(message);
23
+ if (parsed === undefined)
24
+ return;
25
+ const current = this.keys.get(parsed.key);
26
+ if (current === undefined) {
27
+ this.keys.set(parsed.key, {
28
+ ts: parsed.ts,
29
+ writer: parsed.writer,
30
+ value: parsed.value,
31
+ deleted: parsed.deleted,
32
+ });
33
+ return;
34
+ }
35
+ if (parsed.ts === current.ts && parsed.writer === current.writer)
36
+ return;
37
+ if (parsed.ts > current.ts ||
38
+ (parsed.ts === current.ts && compareCodePoints(parsed.writer, current.writer) < 0)) {
39
+ this.keys.set(parsed.key, {
40
+ ts: parsed.ts,
41
+ writer: parsed.writer,
42
+ value: parsed.value,
43
+ deleted: parsed.deleted,
44
+ });
45
+ }
46
+ }
47
+ state() {
48
+ const names = Array.from(this.keys.keys()).sort(compareCodePoints);
49
+ return {
50
+ keys: names.map((key) => {
51
+ const item = this.keys.get(key);
52
+ return {
53
+ deleted: item.deleted,
54
+ key,
55
+ ts: item.ts,
56
+ value: item.value,
57
+ writer: item.writer,
58
+ };
59
+ }),
60
+ };
61
+ }
62
+ parse(message) {
63
+ const obj = asRecord(message);
64
+ if (obj === undefined || obj['app'] !== 'crdt')
65
+ return undefined;
66
+ const op = obj['op'];
67
+ const key = obj['key'];
68
+ const writer = obj['writer'];
69
+ const ts = obj['ts'];
70
+ if (op !== 'set' && op !== 'del')
71
+ return undefined;
72
+ if (typeof key !== 'string' || !NAME.test(key))
73
+ return undefined;
74
+ if (typeof writer !== 'string' || !NAME.test(writer))
75
+ return undefined;
76
+ if (!isInt(ts) || ts < 0 || ts > MAX_SAFE_INT)
77
+ return undefined;
78
+ const deleted = op === 'del';
79
+ let value = '';
80
+ if (!deleted) {
81
+ const text = obj['value'];
82
+ if (typeof text !== 'string')
83
+ return undefined;
84
+ const scalars = Array.from(text).length;
85
+ if (scalars < 1 || scalars > MAX_VALUE)
86
+ return undefined;
87
+ value = text;
88
+ }
89
+ const current = this.keys.get(key);
90
+ if (current === undefined) {
91
+ if (this.keys.size >= MAX_KEYS)
92
+ return undefined;
93
+ return { key, ts, writer, value, deleted };
94
+ }
95
+ if (current.ts === ts && current.writer === writer) {
96
+ if (current.deleted !== deleted || current.value !== value)
97
+ return undefined;
98
+ }
99
+ return { key, ts, writer, value, deleted };
100
+ }
101
+ }
@@ -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.2.0";
10
+ export declare const VERSION = "1.4.0";
11
11
  export declare const WIRE_VERSION = 1;
12
- export declare const IMPL = "ts-chaincraft/1.2.0";
12
+ export declare const IMPL = "ts-chaincraft/1.4.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.2.0';
10
+ export const VERSION = '1.4.0';
11
11
  export const WIRE_VERSION = 1;
12
12
  export const IMPL = `ts-chaincraft/${VERSION}`;
13
13
  export const LANGUAGE = 'typescript';
@@ -41,6 +41,7 @@ export const FEATURES = [
41
41
  'consensus.pow',
42
42
  'consensus.pos',
43
43
  'consensus.pbft',
44
+ 'consensus.avalanche',
44
45
  'ledger.balance',
45
46
  'ledger.utxo',
46
47
  'mempool.basic',
@@ -53,10 +54,12 @@ export const FEATURES = [
53
54
  'channel.mailto',
54
55
  'channel.webrtc',
55
56
  'channel.peer',
57
+ 'channel.hybrid',
56
58
  'channel.forum',
57
59
  'channel.pipe',
58
60
  'app.pubsub',
59
61
  'app.stream',
62
+ 'protocol.crdt-kv',
60
63
  ];
61
64
  export function manifest() {
62
65
  return {
@@ -0,0 +1,20 @@
1
+ /** One mesh, one channel per peer — SPEC/features/channel-hybrid.md. */
2
+ import type { JsonValue } from './canonical.ts';
3
+ export declare const HOP_CAP: Readonly<Record<string, number>>;
4
+ export interface HybridItem {
5
+ id: string;
6
+ type: string;
7
+ from: string;
8
+ }
9
+ export declare function helloCaps(udp: boolean): string[];
10
+ export declare class LinkMesh {
11
+ private readonly order;
12
+ private readonly scheme;
13
+ private readonly inbox;
14
+ private readonly seen;
15
+ join(addr: string): boolean;
16
+ gossip(src: string, typeName: string, data: JsonValue): string | undefined;
17
+ direct(src: string, dst: string, typeName: string, data: JsonValue): string | undefined;
18
+ take(addr: string): HybridItem[];
19
+ private send;
20
+ }
package/dist/hybrid.js ADDED
@@ -0,0 +1,105 @@
1
+ /** One mesh, one channel per peer — SPEC/features/channel-hybrid.md. */
2
+ import { parseAddress } from "./channel.js";
3
+ import { Envelope } from "./envelope.js";
4
+ import { ProtocolError } from "./errors.js";
5
+ export const HOP_CAP = {
6
+ tcp: 262144,
7
+ udp: 65507,
8
+ webrtc: 65507,
9
+ pipe: 65507,
10
+ mailto: 4096,
11
+ forum: 4096,
12
+ loop: 64,
13
+ };
14
+ export function helloCaps(udp) {
15
+ const caps = ['digest-sync', 'gossip'];
16
+ if (udp)
17
+ caps.push('udp');
18
+ return caps.sort();
19
+ }
20
+ export class LinkMesh {
21
+ order = [];
22
+ scheme = new Map();
23
+ inbox = new Map();
24
+ seen = new Set();
25
+ join(addr) {
26
+ const parsed = parseAddress(addr);
27
+ if (!parsed.ok || !(parsed.scheme in HOP_CAP))
28
+ return false;
29
+ if (this.inbox.has(parsed.canonical))
30
+ return false;
31
+ this.order.push(parsed.canonical);
32
+ this.scheme.set(parsed.canonical, parsed.scheme);
33
+ this.inbox.set(parsed.canonical, []);
34
+ return true;
35
+ }
36
+ gossip(src, typeName, data) {
37
+ return this.send(src, undefined, typeName, data, true);
38
+ }
39
+ direct(src, dst, typeName, data) {
40
+ return this.send(src, dst, typeName, data, false);
41
+ }
42
+ take(addr) {
43
+ const canonical = canonicalOf(addr);
44
+ if (canonical === undefined)
45
+ return [];
46
+ const box = this.inbox.get(canonical);
47
+ if (box === undefined)
48
+ return [];
49
+ const out = box.slice();
50
+ box.length = 0;
51
+ return out;
52
+ }
53
+ send(src, dst, typeName, data, gossip) {
54
+ const source = canonicalOf(src);
55
+ if (source === undefined || !this.inbox.has(source))
56
+ return undefined;
57
+ let target;
58
+ if (!gossip) {
59
+ target = dst === undefined ? undefined : canonicalOf(dst);
60
+ if (target === undefined || !this.inbox.has(target))
61
+ return undefined;
62
+ }
63
+ let env;
64
+ try {
65
+ env = Envelope.build(typeName, data, { ts: 0 });
66
+ }
67
+ catch (error) {
68
+ if (error instanceof ProtocolError)
69
+ return undefined;
70
+ throw error;
71
+ }
72
+ if (gossip && env.isControl())
73
+ return undefined;
74
+ if (!gossip && !env.isControl())
75
+ return undefined;
76
+ if (this.seen.has(env.id))
77
+ return env.id;
78
+ this.seen.add(env.id);
79
+ const size = env.toBytes().length;
80
+ const item = { id: env.id, type: env.type, from: source };
81
+ if (gossip) {
82
+ for (const member of this.order) {
83
+ if (member === source)
84
+ continue;
85
+ const scheme = this.scheme.get(member) ?? '';
86
+ const cap = HOP_CAP[scheme] ?? 0;
87
+ if (size <= cap)
88
+ this.inbox.get(member)?.push({ ...item });
89
+ }
90
+ }
91
+ else if (target !== undefined) {
92
+ const scheme = this.scheme.get(target) ?? '';
93
+ const cap = HOP_CAP[scheme] ?? 0;
94
+ if (size <= cap)
95
+ this.inbox.get(target)?.push({ ...item });
96
+ }
97
+ return env.id;
98
+ }
99
+ }
100
+ function canonicalOf(addr) {
101
+ const parsed = parseAddress(addr);
102
+ if (!parsed.ok)
103
+ return undefined;
104
+ return parsed.canonical;
105
+ }
package/dist/index.d.ts CHANGED
@@ -14,10 +14,12 @@ export { DEFAULT_CAPACITY, Deduplicator, SeenDigests } from './dedup.ts';
14
14
  export { type StateMementoObject, StateMemento } from './memento.ts';
15
15
  export { type SharedObject, BaseSharedObject, FRONTIER_FORMAT_VERSION, frontierDigest, merkleDigest, winsReplacement, } from './object.ts';
16
16
  export { type ApplyResult, ObjectRegistry } from './pipeline.ts';
17
+ export { Avalanche, DEFAULT_ALPHA as AVALANCHE_DEFAULT_ALPHA, DEFAULT_BETA as AVALANCHE_DEFAULT_BETA, DEFAULT_K as AVALANCHE_DEFAULT_K, } from './consensusAvalanche.ts';
17
18
  export { PBFT, DEFAULT_REPLICAS as PBFT_DEFAULT_REPLICAS } from './consensusPbft.ts';
18
19
  export { ProofOfStake, DEFAULT_SEED, DEFAULT_VALIDATORS, proposerFor } from './consensusPos.ts';
19
20
  export { ProofOfWork, DEFAULT_DIFFICULTY, blockId, meetsWork } from './consensusPow.ts';
20
21
  export { BalanceLedger, DEFAULT_ALLOCATIONS as BALANCE_DEFAULT_ALLOCATIONS } from './ledgerBalance.ts';
22
+ export { CrdtKv, MAX_KEYS as CRDT_MAX_KEYS, MAX_VALUE as CRDT_MAX_VALUE } from './crdt.ts';
21
23
  export { PubSub, MAX_MEMBERS, MAX_POSTS, MAX_ROOMS, MAX_TEXT } from './pubsub.ts';
22
24
  export { Stream, MAX_BATCH, MAX_BROKERS, MAX_EVENTS, MAX_GROUPS, MAX_PARTITIONS, MAX_PAYLOAD, MAX_PRODUCERS, MAX_READ, MAX_STREAMS, } from './stream.ts';
23
25
  export { UtxoLedger, DEFAULT_ALLOCATIONS as UTXO_DEFAULT_ALLOCATIONS, transactionId } from './ledgerUtxo.ts';
@@ -30,6 +32,7 @@ export { NodeSession } from './cli.ts';
30
32
  export { BitTorrentClient, Swarm, WIRE_TYPE, MAX_NAME_LEN, MAX_PEER_ID_LEN, infoHash, pieceHash, splitPayload, } from './bittorrent.ts';
31
33
  export { Mesh } from './mesh.ts';
32
34
  export { DEFAULT_PEER_ORIGIN, PEER_KEY, EnvelopeRelay, fetchPeerId, isPeerId, parsePeerIdBody, peerOptions, type PeerOptions, type RelayItem, } from './peer.ts';
35
+ export { HOP_CAP, LinkMesh, helloCaps, type HybridItem } from './hybrid.ts';
33
36
  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';
34
37
  export * as ecdsa from './ecdsa.ts';
35
38
  export * as vdf from './vdf.ts';
package/dist/index.js CHANGED
@@ -14,10 +14,12 @@ export { DEFAULT_CAPACITY, Deduplicator, SeenDigests } from "./dedup.js";
14
14
  export { StateMemento } from "./memento.js";
15
15
  export { BaseSharedObject, FRONTIER_FORMAT_VERSION, frontierDigest, merkleDigest, winsReplacement, } from "./object.js";
16
16
  export { ObjectRegistry } from "./pipeline.js";
17
+ export { Avalanche, DEFAULT_ALPHA as AVALANCHE_DEFAULT_ALPHA, DEFAULT_BETA as AVALANCHE_DEFAULT_BETA, DEFAULT_K as AVALANCHE_DEFAULT_K, } from "./consensusAvalanche.js";
17
18
  export { PBFT, DEFAULT_REPLICAS as PBFT_DEFAULT_REPLICAS } from "./consensusPbft.js";
18
19
  export { ProofOfStake, DEFAULT_SEED, DEFAULT_VALIDATORS, proposerFor } from "./consensusPos.js";
19
20
  export { ProofOfWork, DEFAULT_DIFFICULTY, blockId, meetsWork } from "./consensusPow.js";
20
21
  export { BalanceLedger, DEFAULT_ALLOCATIONS as BALANCE_DEFAULT_ALLOCATIONS } from "./ledgerBalance.js";
22
+ export { CrdtKv, MAX_KEYS as CRDT_MAX_KEYS, MAX_VALUE as CRDT_MAX_VALUE } from "./crdt.js";
21
23
  export { PubSub, MAX_MEMBERS, MAX_POSTS, MAX_ROOMS, MAX_TEXT } from "./pubsub.js";
22
24
  export { Stream, MAX_BATCH, MAX_BROKERS, MAX_EVENTS, MAX_GROUPS, MAX_PARTITIONS, MAX_PAYLOAD, MAX_PRODUCERS, MAX_READ, MAX_STREAMS, } from "./stream.js";
23
25
  export { UtxoLedger, DEFAULT_ALLOCATIONS as UTXO_DEFAULT_ALLOCATIONS, transactionId } from "./ledgerUtxo.js";
@@ -30,6 +32,7 @@ export { NodeSession } from "./cli.js";
30
32
  export { BitTorrentClient, Swarm, WIRE_TYPE, MAX_NAME_LEN, MAX_PEER_ID_LEN, infoHash, pieceHash, splitPayload, } from "./bittorrent.js";
31
33
  export { Mesh } from "./mesh.js";
32
34
  export { DEFAULT_PEER_ORIGIN, PEER_KEY, EnvelopeRelay, fetchPeerId, isPeerId, parsePeerIdBody, peerOptions, } from "./peer.js";
35
+ export { HOP_CAP, LinkMesh, helloCaps } from "./hybrid.js";
33
36
  export { APP_NAT, NatTraversal, PUNCH_HEX, bindingRequest, bindingSuccess, parseBindingResponse, } from "./nat.js";
34
37
  export * as ecdsa from "./ecdsa.js";
35
38
  export * as vdf from "./vdf.js";
package/dist/mesh.d.ts CHANGED
@@ -33,12 +33,15 @@ export declare class Mesh {
33
33
  data: JsonValue;
34
34
  }>;
35
35
  listenAddr: string;
36
+ private udp;
37
+ private readonly udpPeers;
36
38
  onApp: AppHandler;
37
39
  onLink: LinkHandler;
38
40
  private readonly onEvent;
39
41
  private server;
40
42
  constructor(impl?: string, onEvent?: (event: MeshEvent) => void);
41
43
  start(host?: string, port?: number): Promise<string>;
44
+ bindUdp(): Promise<string>;
42
45
  connect(addr: string): Promise<void>;
43
46
  broadcast(typeName: string, data: JsonValue): string;
44
47
  send(addr: string, typeName: string, data: JsonValue): string;
@@ -48,5 +51,9 @@ export declare class Mesh {
48
51
  private addPeer;
49
52
  private write;
50
53
  private handle;
54
+ private connectUdp;
55
+ private sendUdp;
56
+ private udpLoop;
57
+ private handleDatagram;
51
58
  }
52
59
  export {};
package/dist/mesh.js CHANGED
@@ -12,7 +12,10 @@ import { isConnectAllowed, isResolvedIpAllowed } from "./discovery.js";
12
12
  import { Envelope } from "./envelope.js";
13
13
  import { ProtocolError } from "./errors.js";
14
14
  import { IMPL } from "./features.js";
15
- import { FrameReader, encodeFrame } from "./framing.js";
15
+ import { FrameReader, MAX_UDP_BYTES, encodeFrame } from "./framing.js";
16
+ import { helloCaps } from "./hybrid.js";
17
+ import { UdpLink } from "./adapters.js";
18
+ import { parseAddress } from "./channel.js";
16
19
  export const MAX_PEERS = 256;
17
20
  export const MAX_RECEIVED = 4096;
18
21
  export const CONNECT_TIMEOUT_MS = 5000;
@@ -36,6 +39,8 @@ export class Mesh {
36
39
  peers = [];
37
40
  received = [];
38
41
  listenAddr = '';
42
+ udp;
43
+ udpPeers = [];
39
44
  onApp = () => undefined;
40
45
  onLink = () => undefined;
41
46
  onEvent;
@@ -60,7 +65,22 @@ export class Mesh {
60
65
  });
61
66
  });
62
67
  }
68
+ async bindUdp() {
69
+ if (this.udp === undefined) {
70
+ this.udp = await UdpLink.bind();
71
+ void this.udpLoop();
72
+ }
73
+ return this.udp.hostPort;
74
+ }
63
75
  async connect(addr) {
76
+ const parsed = parseAddress(addr);
77
+ if (parsed.ok && parsed.scheme === 'udp') {
78
+ await this.connectUdp(parsed.canonical.slice('udp://'.length));
79
+ return;
80
+ }
81
+ if (!parsed.ok || parsed.scheme !== 'tcp')
82
+ throw new Error('address not allowed');
83
+ addr = parsed.canonical.slice('tcp://'.length);
64
84
  if (!isConnectAllowed(addr))
65
85
  throw new Error('address not allowed');
66
86
  const [host, port] = splitAddr(addr);
@@ -93,6 +113,7 @@ export class Mesh {
93
113
  for (const peer of this.peers) {
94
114
  this.write(peer, env);
95
115
  }
116
+ this.sendUdp(env);
96
117
  this.onApp(typeName, data);
97
118
  }
98
119
  return env.id;
@@ -112,6 +133,8 @@ export class Mesh {
112
133
  }
113
134
  close() {
114
135
  this.server?.close();
136
+ void this.udp?.close();
137
+ this.udp = undefined;
115
138
  for (const peer of this.peers) {
116
139
  peer.socket.destroy();
117
140
  }
@@ -130,7 +153,7 @@ export class Mesh {
130
153
  const remotePort = socket.remotePort ?? 0;
131
154
  const peer = { socket, addr: addr ?? `${remote}:${remotePort}` };
132
155
  this.peers.push(peer);
133
- this.write(peer, control.hello(this.impl, { listen: this.listenAddr }));
156
+ this.write(peer, control.hello(this.impl, { listen: this.listenAddr, caps: helloCaps(this.udp !== undefined) }));
134
157
  const reader = new FrameReader(NODE_MAX_FRAME);
135
158
  socket.on('data', (chunk) => {
136
159
  try {
@@ -184,6 +207,80 @@ export class Mesh {
184
207
  // drop a broken peer; close will remove it
185
208
  }
186
209
  }
210
+ this.sendUdp(env);
211
+ }
212
+ this.onApp(env.type, env.data);
213
+ }
214
+ async connectUdp(hostPort) {
215
+ if (!isConnectAllowed(hostPort))
216
+ throw new Error('address not allowed');
217
+ await this.bindUdp();
218
+ if (!this.udpPeers.includes(hostPort)) {
219
+ if (this.peers.length + this.udpPeers.length >= MAX_PEERS) {
220
+ throw new Error('too many peers');
221
+ }
222
+ this.udpPeers.push(hostPort);
223
+ }
224
+ const env = control.hello(this.impl, this.listenAddr ? { caps: helloCaps(true), listen: this.listenAddr } : { caps: helloCaps(true) });
225
+ await this.udp?.send(hostPort, env.toBytes());
226
+ }
227
+ sendUdp(env, skip = '') {
228
+ if (this.udp === undefined)
229
+ return;
230
+ const body = env.toBytes();
231
+ if (body.length > MAX_UDP_BYTES)
232
+ return;
233
+ for (const hostPort of this.udpPeers) {
234
+ if (hostPort === skip)
235
+ continue;
236
+ void this.udp.send(hostPort, body).catch(() => undefined);
237
+ }
238
+ }
239
+ async udpLoop() {
240
+ while (this.udp !== undefined) {
241
+ try {
242
+ const message = await this.udp.recv();
243
+ this.handleDatagram(message.from, message.body);
244
+ }
245
+ catch (error) {
246
+ if (String(error).includes('udp timeout'))
247
+ continue;
248
+ return;
249
+ }
250
+ }
251
+ }
252
+ handleDatagram(src, body) {
253
+ if (body.length > MAX_UDP_BYTES)
254
+ return;
255
+ const env = Envelope.parse(body);
256
+ if (!this.udpPeers.includes(src) && this.peers.length + this.udpPeers.length < MAX_PEERS) {
257
+ this.udpPeers.push(src);
258
+ }
259
+ if (env.type.startsWith('ctl.')) {
260
+ if (env.type === control.HELLO) {
261
+ const hello = control.parseHello(env);
262
+ this.onEvent({ event: 'hello', peer: hello.impl, addr: src });
263
+ }
264
+ return;
265
+ }
266
+ if (env.isControl()) {
267
+ this.onLink(src, env.type, env.data);
268
+ return;
269
+ }
270
+ if (!this.dedup.shouldProcess(env))
271
+ return;
272
+ this.record(env);
273
+ this.onEvent({ event: 'received', id: env.id, type: env.type, data: env.data });
274
+ if (this.dedup.shouldRelay(env)) {
275
+ for (const other of this.peers) {
276
+ try {
277
+ this.write(other, env);
278
+ }
279
+ catch {
280
+ // a broken TCP peer is dropped by its close handler
281
+ }
282
+ }
283
+ this.sendUdp(env, src);
187
284
  }
188
285
  this.onApp(env.type, env.data);
189
286
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chaincraft/core",
3
- "version": "1.2.0",
3
+ "version": "1.4.0",
4
4
  "description": "A platform for decentralized protocols — wire, objects, and pedagogical consensus",
5
5
  "license": "MIT",
6
6
  "type": "module",