@chaincraft/core 1.3.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
@@ -3,7 +3,9 @@
3
3
  TypeScript implementation of the Chaincraft wire protocol, object semantics, and
4
4
  Level 2 stack (consensus, ledgers, BitTorrent, channels). Same observable
5
5
  behaviour as the Python `chaincraft` package and the Rust `chaincraft` crate.
6
- Release **[1.3.0](https://www.npmjs.com/package/@chaincraft/core)** on npm.
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.
7
9
 
8
10
  Open-source toolkit for peer-to-peer protocols like blockchains, chat rooms,
9
11
  BitTorrent swarms, and content-addressed stores.
@@ -150,7 +152,7 @@ loopback Hello World still uses `127.0.0.1:9735`.
150
152
 
151
153
  `connect` allows loopback, RFC1918, public unicast IPv4, `localhost`, `.local`,
152
154
  and ordinary DNS names. Unspecified (`0.0.0.0`), link-local, multicast, and
153
- reserved addresses are refused. Each mesh keeps at most 256 peers.
155
+ reserved addresses are refused. One mesh process keeps at most 256 live peers.
154
156
 
155
157
  ## Library
156
158
 
@@ -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.3.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.3.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.3.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',
@@ -58,6 +59,7 @@ export const FEATURES = [
58
59
  'channel.pipe',
59
60
  'app.pubsub',
60
61
  'app.stream',
62
+ 'protocol.crdt-kv',
61
63
  ];
62
64
  export function manifest() {
63
65
  return {
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';
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";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@chaincraft/core",
3
- "version": "1.3.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",