@chaincraft/core 0.0.0-stage → 1.0.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.
Files changed (73) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +26 -2
  3. package/dist/adapters.d.ts +44 -0
  4. package/dist/adapters.js +136 -0
  5. package/dist/bittorrent.d.ts +47 -0
  6. package/dist/bittorrent.js +313 -0
  7. package/dist/btNode.d.ts +6 -0
  8. package/dist/btNode.js +55 -0
  9. package/dist/canonical.d.ts +42 -0
  10. package/dist/canonical.js +429 -0
  11. package/dist/channel.d.ts +29 -0
  12. package/dist/channel.js +141 -0
  13. package/dist/cli.d.ts +20 -0
  14. package/dist/cli.js +91 -0
  15. package/dist/consensusPbft.d.ts +40 -0
  16. package/dist/consensusPbft.js +141 -0
  17. package/dist/consensusPos.d.ts +27 -0
  18. package/dist/consensusPos.js +103 -0
  19. package/dist/consensusPow.d.ts +27 -0
  20. package/dist/consensusPow.js +116 -0
  21. package/dist/control.d.ts +46 -0
  22. package/dist/control.js +112 -0
  23. package/dist/crypto.d.ts +29 -0
  24. package/dist/crypto.js +68 -0
  25. package/dist/dedup.d.ts +32 -0
  26. package/dist/dedup.js +62 -0
  27. package/dist/discovery.d.ts +37 -0
  28. package/dist/discovery.js +208 -0
  29. package/dist/ecdsa.d.ts +4 -0
  30. package/dist/ecdsa.js +29 -0
  31. package/dist/envelope.d.ts +45 -0
  32. package/dist/envelope.js +227 -0
  33. package/dist/errors.d.ts +18 -0
  34. package/dist/errors.js +21 -0
  35. package/dist/features.d.ts +22 -0
  36. package/dist/features.js +68 -0
  37. package/dist/featuresCli.d.ts +7 -0
  38. package/dist/featuresCli.js +8 -0
  39. package/dist/fees.d.ts +10 -0
  40. package/dist/fees.js +76 -0
  41. package/dist/framing.d.ts +27 -0
  42. package/dist/framing.js +82 -0
  43. package/dist/index.d.ts +37 -0
  44. package/dist/index.js +37 -0
  45. package/dist/ledgerBalance.d.ts +23 -0
  46. package/dist/ledgerBalance.js +110 -0
  47. package/dist/ledgerUtxo.d.ts +31 -0
  48. package/dist/ledgerUtxo.js +137 -0
  49. package/dist/memento.d.ts +34 -0
  50. package/dist/memento.js +57 -0
  51. package/dist/mempool.d.ts +33 -0
  52. package/dist/mempool.js +164 -0
  53. package/dist/mesh.d.ts +47 -0
  54. package/dist/mesh.js +181 -0
  55. package/dist/nat.d.ts +50 -0
  56. package/dist/nat.js +310 -0
  57. package/dist/node.d.ts +6 -0
  58. package/dist/node.js +49 -0
  59. package/dist/object.d.ts +60 -0
  60. package/dist/object.js +59 -0
  61. package/dist/pipeline.d.ts +32 -0
  62. package/dist/pipeline.js +62 -0
  63. package/dist/pubsub.d.ts +28 -0
  64. package/dist/pubsub.js +120 -0
  65. package/dist/storage.d.ts +24 -0
  66. package/dist/storage.js +88 -0
  67. package/dist/stream.d.ts +55 -0
  68. package/dist/stream.js +381 -0
  69. package/dist/vdf.d.ts +6 -0
  70. package/dist/vdf.js +60 -0
  71. package/dist/vrf.d.ts +8 -0
  72. package/dist/vrf.js +32 -0
  73. package/package.json +59 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chaincraft Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,27 @@
1
- # Temporary Holding Version
1
+ # @chaincraft/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ TypeScript implementation of the Chaincraft wire protocol and object semantics.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install @chaincraft/core
9
+ ```
10
+
11
+ The unscoped npm name `chaincraft` belongs to another project. This package is
12
+ `@chaincraft/core`, alongside the `chaincraft` crate and the `chaincraft` Python
13
+ package.
14
+
15
+ ## Example
16
+
17
+ Assumes `@chaincraft/core` is installed.
18
+
19
+ ```ts
20
+ import { Envelope, encodeFrame } from "@chaincraft/core";
21
+
22
+ const env = Envelope.build("app.counter", { by: "alice", delta: 1 });
23
+ const frame = encodeFrame(env.toBytes());
24
+ ```
25
+
26
+ Specification and the other implementations live in the
27
+ [monorepo](https://github.com/jose-compu/chaincraft-monorepo).
@@ -0,0 +1,44 @@
1
+ /** Channel adapters — SPEC/features/channel-adapters.md. */
2
+ export declare const MAX_UDP_PAYLOAD = 65507;
3
+ export declare const MAX_MAIL_BYTES = 4096;
4
+ export declare const MAX_WEBRTC_BYTES = 65507;
5
+ export declare const MAX_FORUM_BYTES = 4096;
6
+ export declare const MAX_PIPE_BYTES = 65507;
7
+ export interface InboxItem {
8
+ data: string;
9
+ from: string;
10
+ }
11
+ export declare class AdapterBus {
12
+ readonly scheme: string;
13
+ readonly maxBytes: number;
14
+ readonly bound: Map<string, AdapterChannel>;
15
+ constructor(scheme: string, maxBytes: number);
16
+ static udp(): AdapterBus;
17
+ static mail(): AdapterBus;
18
+ static webrtc(): AdapterBus;
19
+ static forum(): AdapterBus;
20
+ static pipe(): AdapterBus;
21
+ }
22
+ export declare class AdapterChannel {
23
+ #private;
24
+ listenAddr: string;
25
+ constructor(bus: AdapterBus);
26
+ listen(addr: string): boolean;
27
+ dial(addr: string): boolean;
28
+ send(addr: string, data: string): boolean;
29
+ recv(): InboxItem[];
30
+ inbox(): InboxItem[];
31
+ close(): void;
32
+ }
33
+ export declare class UdpLink {
34
+ #private;
35
+ readonly hostPort: string;
36
+ private constructor();
37
+ static bind(): Promise<UdpLink>;
38
+ send(hostPort: string, body: Uint8Array): Promise<void>;
39
+ recv(): Promise<{
40
+ from: string;
41
+ body: Uint8Array;
42
+ }>;
43
+ close(): Promise<void>;
44
+ }
@@ -0,0 +1,136 @@
1
+ /** Channel adapters — SPEC/features/channel-adapters.md. */
2
+ import dgram from 'node:dgram';
3
+ import { parseAddress } from "./channel.js";
4
+ import { MAX_UDP_BYTES, decodeDatagram } from "./framing.js";
5
+ export const MAX_UDP_PAYLOAD = MAX_UDP_BYTES;
6
+ export const MAX_MAIL_BYTES = 4096;
7
+ export const MAX_WEBRTC_BYTES = MAX_UDP_BYTES;
8
+ export const MAX_FORUM_BYTES = 4096;
9
+ export const MAX_PIPE_BYTES = MAX_UDP_BYTES;
10
+ const HEX = /^[0-9a-f]+$/;
11
+ export class AdapterBus {
12
+ scheme;
13
+ maxBytes;
14
+ bound = new Map();
15
+ constructor(scheme, maxBytes) {
16
+ this.scheme = scheme;
17
+ this.maxBytes = maxBytes;
18
+ }
19
+ static udp() {
20
+ return new AdapterBus('udp', MAX_UDP_PAYLOAD);
21
+ }
22
+ static mail() {
23
+ return new AdapterBus('mailto', MAX_MAIL_BYTES);
24
+ }
25
+ static webrtc() {
26
+ return new AdapterBus('webrtc', MAX_WEBRTC_BYTES);
27
+ }
28
+ static forum() {
29
+ return new AdapterBus('forum', MAX_FORUM_BYTES);
30
+ }
31
+ static pipe() {
32
+ return new AdapterBus('pipe', MAX_PIPE_BYTES);
33
+ }
34
+ }
35
+ export class AdapterChannel {
36
+ listenAddr = '';
37
+ #inbox = [];
38
+ #bus;
39
+ constructor(bus) {
40
+ this.#bus = bus;
41
+ }
42
+ listen(addr) {
43
+ const parsed = parseAddress(addr);
44
+ if (!parsed.ok || parsed.scheme !== this.#bus.scheme || this.listenAddr !== '')
45
+ return false;
46
+ if (this.#bus.bound.has(parsed.canonical))
47
+ return false;
48
+ this.listenAddr = parsed.canonical;
49
+ this.#bus.bound.set(parsed.canonical, this);
50
+ return true;
51
+ }
52
+ dial(addr) {
53
+ const parsed = parseAddress(addr);
54
+ if (!parsed.ok || parsed.scheme !== this.#bus.scheme)
55
+ return false;
56
+ return this.#bus.bound.has(parsed.canonical);
57
+ }
58
+ send(addr, data) {
59
+ const parsed = parseAddress(addr);
60
+ if (!parsed.ok || parsed.scheme !== this.#bus.scheme || !validPayload(data, this.#bus.maxBytes)) {
61
+ return false;
62
+ }
63
+ const dest = this.#bus.bound.get(parsed.canonical);
64
+ if (dest === undefined)
65
+ return false;
66
+ dest.#inbox.push({ data, from: this.listenAddr });
67
+ return true;
68
+ }
69
+ recv() {
70
+ return this.#inbox.splice(0, this.#inbox.length);
71
+ }
72
+ inbox() {
73
+ return this.#inbox.slice();
74
+ }
75
+ close() {
76
+ if (this.listenAddr !== '') {
77
+ if (this.#bus.bound.get(this.listenAddr) === this)
78
+ this.#bus.bound.delete(this.listenAddr);
79
+ this.listenAddr = '';
80
+ }
81
+ this.#inbox.splice(0, this.#inbox.length);
82
+ }
83
+ }
84
+ function validPayload(data, maxBytes) {
85
+ if (data.length < 2 || data.length % 2 !== 0 || !HEX.test(data))
86
+ return false;
87
+ const n = data.length / 2;
88
+ return n >= 1 && n <= maxBytes;
89
+ }
90
+ export class UdpLink {
91
+ #socket;
92
+ hostPort;
93
+ constructor(socket, hostPort) {
94
+ this.#socket = socket;
95
+ this.hostPort = hostPort;
96
+ }
97
+ static bind() {
98
+ return new Promise((resolve, reject) => {
99
+ const socket = dgram.createSocket('udp4');
100
+ socket.once('error', reject);
101
+ socket.bind(0, '127.0.0.1', () => {
102
+ const addr = socket.address();
103
+ resolve(new UdpLink(socket, `${addr.address}:${addr.port}`));
104
+ });
105
+ });
106
+ }
107
+ send(hostPort, body) {
108
+ decodeDatagram(body);
109
+ const idx = hostPort.lastIndexOf(':');
110
+ const host = hostPort.slice(0, idx);
111
+ const port = Number(hostPort.slice(idx + 1));
112
+ return new Promise((resolve, reject) => {
113
+ this.#socket.send(Buffer.from(body), port, host, (error) => {
114
+ if (error)
115
+ reject(error);
116
+ else
117
+ resolve();
118
+ });
119
+ });
120
+ }
121
+ recv() {
122
+ return new Promise((resolve, reject) => {
123
+ const timer = setTimeout(() => reject(new Error('udp timeout')), 2000);
124
+ this.#socket.once('message', (msg, rinfo) => {
125
+ clearTimeout(timer);
126
+ const body = decodeDatagram(new Uint8Array(msg));
127
+ resolve({ from: `${rinfo.address}:${rinfo.port}`, body });
128
+ });
129
+ });
130
+ }
131
+ close() {
132
+ return new Promise((resolve) => {
133
+ this.#socket.close(() => resolve());
134
+ });
135
+ }
136
+ }
@@ -0,0 +1,47 @@
1
+ /** Prototype BitTorrent swarm — SPEC/features/bittorrent-swarm.md. */
2
+ import { type JsonValue } from './canonical.ts';
3
+ import { BaseSharedObject } from './object.ts';
4
+ export declare const WIRE_TYPE = "app.bittorrent";
5
+ export declare const MAX_TORRENTS = 8;
6
+ export declare const MAX_PIECES = 64;
7
+ export declare const MAX_PIECE_BYTES = 65536;
8
+ export declare const MAX_NAME_LEN = 64;
9
+ export declare const MAX_PEER_ID_LEN = 64;
10
+ export declare const MAX_HAVE_PEERS = 32;
11
+ export declare const MAX_SEED_BYTES: number;
12
+ export declare function pieceHash(data: Uint8Array): string;
13
+ export declare function infoHash(name: string, pieces: readonly string[]): string;
14
+ export declare function splitPayload(name: string, text: string, pieceSize: number): {
15
+ infoHash: string;
16
+ length: number;
17
+ payloads: string[];
18
+ pieces: string[];
19
+ };
20
+ export declare class Swarm extends BaseSharedObject {
21
+ private readonly torrents;
22
+ isValid(message: JsonValue): boolean;
23
+ receive(message: JsonValue): void;
24
+ state(): {
25
+ torrents: Record<string, JsonValue>;
26
+ v: number;
27
+ };
28
+ assembled(digest: string): string | null;
29
+ missing(digest: string): number[];
30
+ pieceHex(digest: string, index: number): string | undefined;
31
+ known(): string[];
32
+ private mark;
33
+ private snapshot;
34
+ private parse;
35
+ }
36
+ export declare class BitTorrentClient {
37
+ readonly swarm: Swarm;
38
+ localPeer: string;
39
+ readonly broadcast: (typeName: string, data: JsonValue) => string;
40
+ constructor(broadcast: (typeName: string, data: JsonValue) => string);
41
+ onApp(typeName: string, data: JsonValue): void;
42
+ handleCommand(cmd: Record<string, unknown>): Record<string, unknown> | undefined;
43
+ seed(peer: string, name: string, data: unknown, pieceSize: unknown): Record<string, unknown>;
44
+ leech(peer: string, infoHashValue: unknown): Record<string, unknown>;
45
+ status(): Record<string, unknown>;
46
+ private serveRequest;
47
+ }
@@ -0,0 +1,313 @@
1
+ /** Prototype BitTorrent swarm — SPEC/features/bittorrent-swarm.md. */
2
+ import { sha256 } from '@noble/hashes/sha2.js';
3
+ import { bytesToHex, compareCodePoints, hexToBytes, } from "./canonical.js";
4
+ import { BaseSharedObject, merkleDigest } from "./object.js";
5
+ export const WIRE_TYPE = 'app.bittorrent';
6
+ export const MAX_TORRENTS = 8;
7
+ export const MAX_PIECES = 64;
8
+ export const MAX_PIECE_BYTES = 65536;
9
+ export const MAX_NAME_LEN = 64;
10
+ export const MAX_PEER_ID_LEN = 64;
11
+ export const MAX_HAVE_PEERS = 32;
12
+ export const MAX_SEED_BYTES = MAX_PIECES * MAX_PIECE_BYTES;
13
+ const HEX64 = /^[0-9a-f]{64}$/;
14
+ const HEX = /^(?:[0-9a-f]{2})+$/;
15
+ function asRecord(message) {
16
+ if (message === null || typeof message !== 'object' || Array.isArray(message)) {
17
+ return undefined;
18
+ }
19
+ return message;
20
+ }
21
+ function isInt(value) {
22
+ return typeof value === 'number' && Number.isSafeInteger(value);
23
+ }
24
+ export function pieceHash(data) {
25
+ return bytesToHex(sha256(data));
26
+ }
27
+ export function infoHash(name, pieces) {
28
+ return merkleDigest({ name, pieces: [...pieces] });
29
+ }
30
+ export function splitPayload(name, text, pieceSize) {
31
+ if (!name || !text || pieceSize < 1) {
32
+ throw new RangeError('name and data must be non-empty; piece_size >= 1');
33
+ }
34
+ if (name.length > MAX_NAME_LEN || pieceSize > MAX_PIECE_BYTES) {
35
+ throw new RangeError('name or piece_size exceeds the prototype limit');
36
+ }
37
+ const raw = new TextEncoder().encode(text);
38
+ if (raw.length > MAX_SEED_BYTES) {
39
+ throw new RangeError('payload exceeds the prototype limit');
40
+ }
41
+ if (Math.ceil(raw.length / pieceSize) > MAX_PIECES) {
42
+ throw new RangeError('too many pieces');
43
+ }
44
+ const chunks = [];
45
+ for (let i = 0; i < raw.length; i += pieceSize)
46
+ chunks.push(raw.subarray(i, i + pieceSize));
47
+ const pieces = chunks.map((chunk) => pieceHash(chunk));
48
+ const payloads = chunks.map((chunk) => bytesToHex(chunk));
49
+ return { infoHash: infoHash(name, pieces), length: raw.length, payloads, pieces };
50
+ }
51
+ export class Swarm extends BaseSharedObject {
52
+ torrents = new Map();
53
+ isValid(message) {
54
+ return this.parse(message) !== undefined;
55
+ }
56
+ receive(message) {
57
+ const parsed = this.parse(message);
58
+ if (parsed === undefined)
59
+ return;
60
+ if (parsed.kind === 'metainfo') {
61
+ if (!this.torrents.has(parsed.digest)) {
62
+ this.torrents.set(parsed.digest, {
63
+ name: parsed.name,
64
+ pieces: parsed.pieces,
65
+ data: new Map(),
66
+ have: new Map(),
67
+ });
68
+ }
69
+ }
70
+ else if (parsed.kind === 'have') {
71
+ this.mark(parsed.digest, parsed.peer, parsed.index);
72
+ }
73
+ else if (parsed.kind === 'piece') {
74
+ const torrent = this.torrents.get(parsed.digest);
75
+ if (torrent !== undefined) {
76
+ torrent.data.set(parsed.index, parsed.data);
77
+ this.mark(parsed.digest, parsed.peer, parsed.index);
78
+ }
79
+ }
80
+ }
81
+ state() {
82
+ return { torrents: this.snapshot(), v: 1 };
83
+ }
84
+ assembled(digest) {
85
+ const torrent = this.torrents.get(digest);
86
+ if (torrent === undefined)
87
+ return null;
88
+ const parts = [];
89
+ for (let index = 0; index < torrent.pieces.length; index += 1) {
90
+ const hex = torrent.data.get(index);
91
+ if (hex === undefined)
92
+ return null;
93
+ parts.push(hexToBytes(hex));
94
+ }
95
+ const joined = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0));
96
+ let offset = 0;
97
+ for (const part of parts) {
98
+ joined.set(part, offset);
99
+ offset += part.length;
100
+ }
101
+ return bytesToHex(joined);
102
+ }
103
+ missing(digest) {
104
+ const torrent = this.torrents.get(digest);
105
+ if (torrent === undefined)
106
+ return [];
107
+ const out = [];
108
+ for (let index = 0; index < torrent.pieces.length; index += 1) {
109
+ if (!torrent.data.has(index))
110
+ out.push(index);
111
+ }
112
+ return out;
113
+ }
114
+ pieceHex(digest, index) {
115
+ return this.torrents.get(digest)?.data.get(index);
116
+ }
117
+ known() {
118
+ return [...this.torrents.keys()].sort(compareCodePoints);
119
+ }
120
+ mark(digest, peer, index) {
121
+ const torrent = this.torrents.get(digest);
122
+ if (torrent === undefined)
123
+ return;
124
+ let set = torrent.have.get(peer);
125
+ if (set === undefined) {
126
+ set = new Set();
127
+ torrent.have.set(peer, set);
128
+ }
129
+ set.add(index);
130
+ }
131
+ snapshot() {
132
+ const out = {};
133
+ for (const digest of [...this.torrents.keys()].sort(compareCodePoints)) {
134
+ const torrent = this.torrents.get(digest);
135
+ const count = torrent.pieces.length;
136
+ const peers = [...torrent.have.keys()].sort(compareCodePoints);
137
+ const have = {};
138
+ for (const peer of peers)
139
+ have[peer] = [...torrent.have.get(peer)].sort((a, b) => a - b);
140
+ const complete = peers.filter((peer) => have[peer].length === count && have[peer].every((v, i) => v === i));
141
+ const data = {};
142
+ for (const index of [...torrent.data.keys()].sort((a, b) => a - b)) {
143
+ data[String(index)] = torrent.data.get(index);
144
+ }
145
+ out[digest] = {
146
+ complete,
147
+ data,
148
+ have,
149
+ name: torrent.name,
150
+ pieces: [...torrent.pieces],
151
+ };
152
+ }
153
+ return out;
154
+ }
155
+ parse(message) {
156
+ const record = asRecord(message);
157
+ if (record === undefined)
158
+ return undefined;
159
+ const kind = record['bt'];
160
+ if (kind === 'metainfo') {
161
+ const name = record['name'];
162
+ const pieces = record['pieces'];
163
+ if (typeof name !== 'string' || !name || name.length > MAX_NAME_LEN)
164
+ return undefined;
165
+ if (!Array.isArray(pieces) || pieces.length === 0 || pieces.length > MAX_PIECES) {
166
+ return undefined;
167
+ }
168
+ if (!pieces.every((item) => typeof item === 'string' && HEX64.test(item)))
169
+ return undefined;
170
+ const list = pieces;
171
+ const digest = infoHash(name, list);
172
+ const existing = this.torrents.get(digest);
173
+ if (existing !== undefined && (existing.name !== name || !sameList(existing.pieces, list))) {
174
+ return undefined;
175
+ }
176
+ if (existing === undefined && this.torrents.size >= MAX_TORRENTS)
177
+ return undefined;
178
+ return { kind: 'metainfo', name, pieces: list, digest };
179
+ }
180
+ if (kind === 'have' || kind === 'piece' || kind === 'request') {
181
+ const digest = record['info_hash'];
182
+ const peer = record['peer'];
183
+ const index = record['index'];
184
+ if (typeof digest !== 'string' || !HEX64.test(digest) || typeof peer !== 'string' || !peer) {
185
+ return undefined;
186
+ }
187
+ if (peer.length > MAX_PEER_ID_LEN)
188
+ return undefined;
189
+ const torrent = this.torrents.get(digest);
190
+ if (torrent === undefined || !isInt(index) || index < 0 || index >= torrent.pieces.length) {
191
+ return undefined;
192
+ }
193
+ if (kind !== 'request' && !torrent.have.has(peer) && torrent.have.size >= MAX_HAVE_PEERS) {
194
+ return undefined;
195
+ }
196
+ if (kind !== 'piece')
197
+ return { kind, digest, peer, index };
198
+ const data = record['data'];
199
+ if (typeof data !== 'string' || data.length > MAX_PIECE_BYTES * 2 || !HEX.test(data)) {
200
+ return undefined;
201
+ }
202
+ if (pieceHash(hexToBytes(data)) !== torrent.pieces[index])
203
+ return undefined;
204
+ return { kind: 'piece', digest, peer, index, data };
205
+ }
206
+ return undefined;
207
+ }
208
+ }
209
+ function sameList(left, right) {
210
+ return left.length === right.length && left.every((item, index) => item === right[index]);
211
+ }
212
+ export class BitTorrentClient {
213
+ swarm = new Swarm();
214
+ localPeer = '';
215
+ broadcast;
216
+ constructor(broadcast) {
217
+ this.broadcast = broadcast;
218
+ }
219
+ onApp(typeName, data) {
220
+ if (typeName !== WIRE_TYPE)
221
+ return;
222
+ if (this.swarm.isValid(data))
223
+ this.swarm.addMessage(data);
224
+ this.serveRequest(data);
225
+ }
226
+ handleCommand(cmd) {
227
+ if (cmd['cmd'] === 'bt.seed') {
228
+ return this.seed(String(cmd['peer']), String(cmd['name']), cmd['data'], cmd['piece_size']);
229
+ }
230
+ if (cmd['cmd'] === 'bt.leech') {
231
+ return this.leech(String(cmd['peer']), cmd['info_hash']);
232
+ }
233
+ if (cmd['cmd'] === 'bt.status')
234
+ return this.status();
235
+ return undefined;
236
+ }
237
+ seed(peer, name, data, pieceSize) {
238
+ if (peer.length > MAX_PEER_ID_LEN || name.length > MAX_NAME_LEN) {
239
+ throw new RangeError('peer or name exceeds the prototype limit');
240
+ }
241
+ if (typeof data !== 'string' || typeof pieceSize !== 'number' || !Number.isSafeInteger(pieceSize)) {
242
+ throw new RangeError('invalid seed');
243
+ }
244
+ this.localPeer = peer;
245
+ const split = splitPayload(name, data, pieceSize);
246
+ this.broadcast(WIRE_TYPE, { bt: 'metainfo', name, pieces: split.pieces });
247
+ split.payloads.forEach((payload, index) => {
248
+ this.broadcast(WIRE_TYPE, {
249
+ bt: 'piece',
250
+ data: payload,
251
+ index,
252
+ info_hash: split.infoHash,
253
+ peer,
254
+ });
255
+ });
256
+ return {
257
+ event: 'bt.seeded',
258
+ info_hash: split.infoHash,
259
+ length: split.length,
260
+ pieces: split.pieces.length,
261
+ };
262
+ }
263
+ leech(peer, infoHashValue) {
264
+ if (peer.length > MAX_PEER_ID_LEN)
265
+ throw new RangeError('peer exceeds the prototype limit');
266
+ this.localPeer = peer;
267
+ const known = this.swarm.known();
268
+ const digest = typeof infoHashValue === 'string' ? infoHashValue : known[0] ?? '';
269
+ const requested = [];
270
+ if (digest) {
271
+ for (const index of this.swarm.missing(digest)) {
272
+ this.broadcast(WIRE_TYPE, { bt: 'request', index, info_hash: digest, peer });
273
+ requested.push(index);
274
+ }
275
+ }
276
+ return { event: 'bt.leech', info_hash: digest, requested };
277
+ }
278
+ status() {
279
+ const snap = this.swarm.state().torrents;
280
+ const torrents = this.swarm.known().map((digest) => {
281
+ const entry = snap[digest];
282
+ return {
283
+ assembled: this.swarm.assembled(digest),
284
+ complete: entry['complete'],
285
+ have: entry['have'],
286
+ info_hash: digest,
287
+ name: entry['name'],
288
+ };
289
+ });
290
+ return { event: 'bt.status', torrents };
291
+ }
292
+ serveRequest(data) {
293
+ if (data === null || typeof data !== 'object' || Array.isArray(data) || !this.localPeer)
294
+ return;
295
+ const record = data;
296
+ if (record['bt'] !== 'request')
297
+ return;
298
+ const digest = record['info_hash'];
299
+ const index = record['index'];
300
+ if (typeof digest !== 'string' || typeof index !== 'number')
301
+ return;
302
+ const payload = this.swarm.pieceHex(digest, index);
303
+ if (payload === undefined)
304
+ return;
305
+ this.broadcast(WIRE_TYPE, {
306
+ bt: 'piece',
307
+ data: payload,
308
+ index,
309
+ info_hash: digest,
310
+ peer: this.localPeer,
311
+ });
312
+ }
313
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * BitTorrent mesh client — Swarm on top of the Level 0 mesh.
3
+ *
4
+ * Driven by conformance/runner/run_bittorrent.py.
5
+ */
6
+ export {};
package/dist/btNode.js ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * BitTorrent mesh client — Swarm on top of the Level 0 mesh.
3
+ *
4
+ * Driven by conformance/runner/run_bittorrent.py.
5
+ */
6
+ import * as readline from 'node:readline';
7
+ import { BitTorrentClient, IMPL, ProtocolError } from "./index.js";
8
+ import { Mesh } from "./mesh.js";
9
+ const MAX_STDIN_LINE = 1_048_576;
10
+ function emit(event) {
11
+ process.stdout.write(`${JSON.stringify(event)}\n`);
12
+ }
13
+ const mesh = new Mesh(IMPL, emit);
14
+ const client = new BitTorrentClient((typeName, data) => mesh.broadcast(typeName, data));
15
+ mesh.onApp = (typeName, data) => client.onApp(typeName, data);
16
+ await mesh.start();
17
+ emit({ event: 'ready', addr: mesh.listenAddr, impl: IMPL });
18
+ const rl = readline.createInterface({ input: process.stdin });
19
+ for await (const line of rl) {
20
+ if (line.length > MAX_STDIN_LINE) {
21
+ emit({ event: 'error', message: 'line too long' });
22
+ continue;
23
+ }
24
+ if (!line.trim())
25
+ continue;
26
+ const cmd = JSON.parse(line);
27
+ try {
28
+ const btEvent = client.handleCommand(cmd);
29
+ if (btEvent !== undefined) {
30
+ emit(btEvent);
31
+ }
32
+ else if (cmd['cmd'] === 'connect') {
33
+ await mesh.connect(cmd['addr']);
34
+ emit({ event: 'connected', addr: cmd['addr'] });
35
+ }
36
+ else if (cmd['cmd'] === 'send') {
37
+ const id = mesh.broadcast(cmd['type'], cmd['data']);
38
+ emit({ event: 'sent', id });
39
+ }
40
+ else if (cmd['cmd'] === 'ids') {
41
+ emit({ event: 'ids', ids: mesh.ids() });
42
+ }
43
+ else if (cmd['cmd'] === 'quit') {
44
+ break;
45
+ }
46
+ else {
47
+ emit({ event: 'error', message: `unknown cmd ${cmd['cmd']}` });
48
+ }
49
+ }
50
+ catch (error) {
51
+ const message = error instanceof ProtocolError ? error.message : String(error);
52
+ emit({ event: 'error', message });
53
+ }
54
+ }
55
+ mesh.close();