@arcblock/did-noise 0.0.0-stage → 1.30.25
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/LICENSE +13 -0
- package/esm/chacha20poly1305.d.mts +18 -0
- package/esm/chacha20poly1305.mjs +152 -0
- package/esm/chain-node-mesh.d.mts +79 -0
- package/esm/chain-node-mesh.mjs +187 -0
- package/esm/http-transport.d.mts +72 -0
- package/esm/http-transport.mjs +216 -0
- package/esm/index.d.mts +6 -0
- package/esm/index.mjs +7 -0
- package/esm/mesh-tunnel.d.mts +165 -0
- package/esm/mesh-tunnel.mjs +350 -0
- package/esm/noise-session.d.mts +157 -0
- package/esm/noise-session.mjs +491 -0
- package/lib/_vendor/@noble/curves/LICENSE +21 -0
- package/lib/_vendor/@noble/curves/abstract/curve.cjs +338 -0
- package/lib/_vendor/@noble/curves/abstract/edwards.cjs +542 -0
- package/lib/_vendor/@noble/curves/abstract/hash-to-curve.cjs +72 -0
- package/lib/_vendor/@noble/curves/abstract/modular.cjs +557 -0
- package/lib/_vendor/@noble/curves/abstract/montgomery.cjs +149 -0
- package/lib/_vendor/@noble/curves/ed25519.cjs +302 -0
- package/lib/_vendor/@noble/curves/utils.cjs +436 -0
- package/lib/_vendor/@noble/hashes/LICENSE +21 -0
- package/lib/_vendor/@noble/hashes/_blake.cjs +300 -0
- package/lib/_vendor/@noble/hashes/_md.cjs +194 -0
- package/lib/_vendor/@noble/hashes/_u64.cjs +60 -0
- package/lib/_vendor/@noble/hashes/blake2.cjs +291 -0
- package/lib/_vendor/@noble/hashes/hkdf.cjs +104 -0
- package/lib/_vendor/@noble/hashes/hmac.cjs +86 -0
- package/lib/_vendor/@noble/hashes/sha2.cjs +417 -0
- package/lib/_vendor/@noble/hashes/utils.cjs +422 -0
- package/lib/chacha20poly1305.cjs +153 -0
- package/lib/chacha20poly1305.d.cts +18 -0
- package/lib/chain-node-mesh.cjs +189 -0
- package/lib/chain-node-mesh.d.cts +79 -0
- package/lib/http-transport.cjs +219 -0
- package/lib/http-transport.d.cts +72 -0
- package/lib/index.cjs +31 -0
- package/lib/index.d.cts +6 -0
- package/lib/mesh-tunnel.cjs +354 -0
- package/lib/mesh-tunnel.d.cts +165 -0
- package/lib/noise-session.cjs +503 -0
- package/lib/noise-session.d.cts +157 -0
- package/package.json +80 -4
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Copyright 2018-2025 ArcBlock
|
|
2
|
+
|
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
you may not use this file except in compliance with the License.
|
|
5
|
+
You may obtain a copy of the License at
|
|
6
|
+
|
|
7
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
See the License for the specific language governing permissions and
|
|
13
|
+
limitations under the License.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
//#region src/chacha20poly1305.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* RFC 8439 ChaCha20-Poly1305 AEAD implementation.
|
|
4
|
+
*
|
|
5
|
+
* Self-contained, zero external cipher dependency, constant-time tag verification,
|
|
6
|
+
* byte-for-byte compatible with `@noble/ciphers/chacha.js` (`chacha20poly1305`).
|
|
7
|
+
*/
|
|
8
|
+
interface ChaCha20Poly1305Cipher {
|
|
9
|
+
encrypt(plaintext: Uint8Array): Uint8Array;
|
|
10
|
+
decrypt(ciphertextWithTag: Uint8Array): Uint8Array;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Create an RFC 8439 ChaCha20-Poly1305 AEAD cipher instance.
|
|
14
|
+
* Drop-in compatible with `@noble/ciphers/chacha.js` `chacha20poly1305(key, nonce, aad)`.
|
|
15
|
+
*/
|
|
16
|
+
declare function chacha20poly1305(key: Uint8Array, nonce: Uint8Array, aad?: Uint8Array): ChaCha20Poly1305Cipher;
|
|
17
|
+
//#endregion
|
|
18
|
+
export { ChaCha20Poly1305Cipher, chacha20poly1305 };
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
//#region src/chacha20poly1305.ts
|
|
2
|
+
/**
|
|
3
|
+
* RFC 8439 ChaCha20-Poly1305 AEAD implementation.
|
|
4
|
+
*
|
|
5
|
+
* Self-contained, zero external cipher dependency, constant-time tag verification,
|
|
6
|
+
* byte-for-byte compatible with `@noble/ciphers/chacha.js` (`chacha20poly1305`).
|
|
7
|
+
*/
|
|
8
|
+
function rotl32(v, n) {
|
|
9
|
+
return (v << n | v >>> 32 - n) >>> 0;
|
|
10
|
+
}
|
|
11
|
+
function readU32LE(buf, offset) {
|
|
12
|
+
return (buf[offset] | buf[offset + 1] << 8 | buf[offset + 2] << 16 | buf[offset + 3] << 24) >>> 0;
|
|
13
|
+
}
|
|
14
|
+
function writeU32LE(buf, offset, val) {
|
|
15
|
+
buf[offset] = val & 255;
|
|
16
|
+
buf[offset + 1] = val >>> 8 & 255;
|
|
17
|
+
buf[offset + 2] = val >>> 16 & 255;
|
|
18
|
+
buf[offset + 3] = val >>> 24 & 255;
|
|
19
|
+
}
|
|
20
|
+
function writeU64LE(buf, offset, len) {
|
|
21
|
+
const lo = len >>> 0;
|
|
22
|
+
const hi = Math.floor(len / 4294967296) >>> 0;
|
|
23
|
+
writeU32LE(buf, offset, lo);
|
|
24
|
+
writeU32LE(buf, offset + 4, hi);
|
|
25
|
+
}
|
|
26
|
+
function quarterRound(s, a, b, c, d) {
|
|
27
|
+
s[a] = s[a] + s[b] >>> 0;
|
|
28
|
+
s[d] = rotl32(s[d] ^ s[a], 16);
|
|
29
|
+
s[c] = s[c] + s[d] >>> 0;
|
|
30
|
+
s[b] = rotl32(s[b] ^ s[c], 12);
|
|
31
|
+
s[a] = s[a] + s[b] >>> 0;
|
|
32
|
+
s[d] = rotl32(s[d] ^ s[a], 8);
|
|
33
|
+
s[c] = s[c] + s[d] >>> 0;
|
|
34
|
+
s[b] = rotl32(s[b] ^ s[c], 7);
|
|
35
|
+
}
|
|
36
|
+
function chacha20Block(key, counter, nonce) {
|
|
37
|
+
const state = new Uint32Array(16);
|
|
38
|
+
state[0] = 1634760805;
|
|
39
|
+
state[1] = 857760878;
|
|
40
|
+
state[2] = 2036477234;
|
|
41
|
+
state[3] = 1797285236;
|
|
42
|
+
for (let i = 0; i < 8; i++) state[4 + i] = readU32LE(key, i * 4);
|
|
43
|
+
state[12] = counter >>> 0;
|
|
44
|
+
state[13] = readU32LE(nonce, 0);
|
|
45
|
+
state[14] = readU32LE(nonce, 4);
|
|
46
|
+
state[15] = readU32LE(nonce, 8);
|
|
47
|
+
const working = new Uint32Array(state);
|
|
48
|
+
for (let i = 0; i < 10; i++) {
|
|
49
|
+
quarterRound(working, 0, 4, 8, 12);
|
|
50
|
+
quarterRound(working, 1, 5, 9, 13);
|
|
51
|
+
quarterRound(working, 2, 6, 10, 14);
|
|
52
|
+
quarterRound(working, 3, 7, 11, 15);
|
|
53
|
+
quarterRound(working, 0, 5, 10, 15);
|
|
54
|
+
quarterRound(working, 1, 6, 11, 12);
|
|
55
|
+
quarterRound(working, 2, 7, 8, 13);
|
|
56
|
+
quarterRound(working, 3, 4, 9, 14);
|
|
57
|
+
}
|
|
58
|
+
const out = new Uint8Array(64);
|
|
59
|
+
for (let i = 0; i < 16; i++) writeU32LE(out, i * 4, working[i] + state[i] >>> 0);
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
function chacha20Xor(key, initialCounter, nonce, input) {
|
|
63
|
+
const out = new Uint8Array(input.length);
|
|
64
|
+
let counter = initialCounter;
|
|
65
|
+
for (let offset = 0; offset < input.length; offset += 64) {
|
|
66
|
+
const block = chacha20Block(key, counter++, nonce);
|
|
67
|
+
const chunkLen = Math.min(64, input.length - offset);
|
|
68
|
+
for (let i = 0; i < chunkLen; i++) out[offset + i] = input[offset + i] ^ block[i];
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
const POLY1305_P = (1n << 130n) - 5n;
|
|
73
|
+
function bytesToBigIntLE(bytes) {
|
|
74
|
+
let result = 0n;
|
|
75
|
+
for (let i = bytes.length - 1; i >= 0; i--) result = result << 8n | BigInt(bytes[i]);
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
function poly1305Mac(msg, otk) {
|
|
79
|
+
const rBytes = new Uint8Array(otk.subarray(0, 16));
|
|
80
|
+
rBytes[3] &= 15;
|
|
81
|
+
rBytes[7] &= 15;
|
|
82
|
+
rBytes[11] &= 15;
|
|
83
|
+
rBytes[15] &= 15;
|
|
84
|
+
rBytes[4] &= 252;
|
|
85
|
+
rBytes[8] &= 252;
|
|
86
|
+
rBytes[12] &= 252;
|
|
87
|
+
const r = bytesToBigIntLE(rBytes);
|
|
88
|
+
const s = bytesToBigIntLE(otk.subarray(16, 32));
|
|
89
|
+
let acc = 0n;
|
|
90
|
+
for (let offset = 0; offset < msg.length; offset += 16) {
|
|
91
|
+
const slice = msg.subarray(offset, Math.min(offset + 16, msg.length));
|
|
92
|
+
const n = bytesToBigIntLE(slice) | 1n << BigInt(slice.length * 8);
|
|
93
|
+
acc = (acc + n) * r % POLY1305_P;
|
|
94
|
+
}
|
|
95
|
+
acc = acc + s & (1n << 128n) - 1n;
|
|
96
|
+
const tag = new Uint8Array(16);
|
|
97
|
+
for (let i = 0; i < 16; i++) {
|
|
98
|
+
tag[i] = Number(acc & 255n);
|
|
99
|
+
acc >>= 8n;
|
|
100
|
+
}
|
|
101
|
+
return tag;
|
|
102
|
+
}
|
|
103
|
+
function buildPoly1305Input(aad, ciphertext) {
|
|
104
|
+
const aadPad = (16 - aad.length % 16) % 16;
|
|
105
|
+
const ctPad = (16 - ciphertext.length % 16) % 16;
|
|
106
|
+
const totalLen = aad.length + aadPad + ciphertext.length + ctPad + 16;
|
|
107
|
+
const buf = new Uint8Array(totalLen);
|
|
108
|
+
let pos = 0;
|
|
109
|
+
buf.set(aad, pos);
|
|
110
|
+
pos += aad.length + aadPad;
|
|
111
|
+
buf.set(ciphertext, pos);
|
|
112
|
+
pos += ciphertext.length + ctPad;
|
|
113
|
+
writeU64LE(buf, pos, aad.length);
|
|
114
|
+
writeU64LE(buf, pos + 8, ciphertext.length);
|
|
115
|
+
return buf;
|
|
116
|
+
}
|
|
117
|
+
function constantTimeEqual(a, b) {
|
|
118
|
+
if (a.length !== b.length) return false;
|
|
119
|
+
let diff = 0;
|
|
120
|
+
for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
|
|
121
|
+
return diff === 0;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Create an RFC 8439 ChaCha20-Poly1305 AEAD cipher instance.
|
|
125
|
+
* Drop-in compatible with `@noble/ciphers/chacha.js` `chacha20poly1305(key, nonce, aad)`.
|
|
126
|
+
*/
|
|
127
|
+
function chacha20poly1305(key, nonce, aad = new Uint8Array(0)) {
|
|
128
|
+
if (key.length !== 32) throw new Error(`Invalid ChaCha20-Poly1305 key length: expected 32, got ${key.length}`);
|
|
129
|
+
if (nonce.length !== 12) throw new Error(`Invalid ChaCha20-Poly1305 nonce length: expected 12, got ${nonce.length}`);
|
|
130
|
+
return {
|
|
131
|
+
encrypt(plaintext) {
|
|
132
|
+
const otk = chacha20Block(key, 0, nonce).subarray(0, 32);
|
|
133
|
+
const ciphertext = chacha20Xor(key, 1, nonce, plaintext);
|
|
134
|
+
const tag = poly1305Mac(buildPoly1305Input(aad, ciphertext), otk);
|
|
135
|
+
const out = new Uint8Array(ciphertext.length + 16);
|
|
136
|
+
out.set(ciphertext, 0);
|
|
137
|
+
out.set(tag, ciphertext.length);
|
|
138
|
+
return out;
|
|
139
|
+
},
|
|
140
|
+
decrypt(ciphertextWithTag) {
|
|
141
|
+
if (ciphertextWithTag.length < 16) throw new Error("ChaCha20-Poly1305 decryption failed: ciphertext too short");
|
|
142
|
+
const ciphertext = ciphertextWithTag.subarray(0, ciphertextWithTag.length - 16);
|
|
143
|
+
const receivedTag = ciphertextWithTag.subarray(ciphertextWithTag.length - 16);
|
|
144
|
+
const otk = chacha20Block(key, 0, nonce).subarray(0, 32);
|
|
145
|
+
if (!constantTimeEqual(receivedTag, poly1305Mac(buildPoly1305Input(aad, ciphertext), otk))) throw new Error("ChaCha20-Poly1305 authentication tag mismatch");
|
|
146
|
+
return chacha20Xor(key, 1, nonce, ciphertext);
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
//#endregion
|
|
152
|
+
export { chacha20poly1305 };
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { NoiseIdentity } from "./noise-session.mjs";
|
|
2
|
+
import { EncryptedChannel, MultiMeshRouter } from "./mesh-tunnel.mjs";
|
|
3
|
+
import { NoisePeerContext } from "./http-transport.mjs";
|
|
4
|
+
|
|
5
|
+
//#region src/chain-node-mesh.d.ts
|
|
6
|
+
|
|
7
|
+
type ChainNodeRole = 'sequencer' | 'witness' | 'replica' | 'gateway';
|
|
8
|
+
interface ChainCommitmentPayload {
|
|
9
|
+
chainId: string;
|
|
10
|
+
height: number;
|
|
11
|
+
stateRoot: string;
|
|
12
|
+
txRoot: string;
|
|
13
|
+
timestamp: number;
|
|
14
|
+
sequencerDid: string;
|
|
15
|
+
}
|
|
16
|
+
interface ChainWitnessAttestation {
|
|
17
|
+
chainId: string;
|
|
18
|
+
height: number;
|
|
19
|
+
stateRoot: string;
|
|
20
|
+
txRoot: string;
|
|
21
|
+
witnessDid: string;
|
|
22
|
+
witnessPubkeyHex: string;
|
|
23
|
+
signatureHex: string;
|
|
24
|
+
}
|
|
25
|
+
interface ChainReplicaSyncAck {
|
|
26
|
+
ok: boolean;
|
|
27
|
+
replicaDid: string;
|
|
28
|
+
ackedHeight: number;
|
|
29
|
+
stateRoot: string;
|
|
30
|
+
}
|
|
31
|
+
interface ChainNodeDarknetOptions {
|
|
32
|
+
chainId: string;
|
|
33
|
+
role: ChainNodeRole;
|
|
34
|
+
identity: NoiseIdentity;
|
|
35
|
+
/** Authorized Sequencer DIDs allowed to push commitments / request witness signatures */
|
|
36
|
+
authorizedSequencerDids?: Iterable<string>;
|
|
37
|
+
/** All authorized peer DIDs or pubkeyHexes allowed into this chain's internal darknet */
|
|
38
|
+
authorizedPeers: Iterable<string>;
|
|
39
|
+
/** Optional hook invoked on Replica/Gateway when a verified commitment arrives */
|
|
40
|
+
onCommitmentSynced?: (commitment: ChainCommitmentPayload, peer: NoisePeerContext) => void | Promise<void>;
|
|
41
|
+
/** Optional policy hook invoked on Witness before signing a commitment */
|
|
42
|
+
validateCommitmentForWitness?: (commitment: ChainCommitmentPayload, peer: NoisePeerContext) => boolean | Promise<boolean>;
|
|
43
|
+
}
|
|
44
|
+
declare function canonicalizeCommitment(c: ChainCommitmentPayload): Uint8Array;
|
|
45
|
+
declare function verifyWitnessAttestation(commitment: ChainCommitmentPayload, attestation: ChainWitnessAttestation): boolean;
|
|
46
|
+
declare class ChainNodeDarknet {
|
|
47
|
+
readonly chainId: string;
|
|
48
|
+
readonly role: ChainNodeRole;
|
|
49
|
+
readonly identity: NoiseIdentity;
|
|
50
|
+
readonly meshId: string;
|
|
51
|
+
readonly router: MultiMeshRouter;
|
|
52
|
+
private readonly authorizedSequencers;
|
|
53
|
+
private readonly bridges;
|
|
54
|
+
private readonly onCommitmentSynced?;
|
|
55
|
+
private readonly validateCommitmentForWitness?;
|
|
56
|
+
private readonly syncedCommitments;
|
|
57
|
+
constructor(options: ChainNodeDarknetOptions);
|
|
58
|
+
getSyncedCommitments(): ChainCommitmentPayload[];
|
|
59
|
+
/**
|
|
60
|
+
* Establish a bidirectional encrypted Noise_IK channel + HTTP bridge with a remote `ChainNodeDarknet`
|
|
61
|
+
* (or custom packet transport).
|
|
62
|
+
*/
|
|
63
|
+
connectToNode(targetNode: ChainNodeDarknet): {
|
|
64
|
+
localChannel: EncryptedChannel;
|
|
65
|
+
remoteChannel: EncryptedChannel;
|
|
66
|
+
};
|
|
67
|
+
/**
|
|
68
|
+
* Sequencer calls a Witness node over the darknet tunnel to obtain an Ed25519 attestation.
|
|
69
|
+
*/
|
|
70
|
+
requestWitnessSignature(witnessDidOrPubkey: string, commitment: ChainCommitmentPayload): Promise<ChainWitnessAttestation>;
|
|
71
|
+
/**
|
|
72
|
+
* Sequencer replicates a commitment to a Replica or Gateway node over the darknet tunnel.
|
|
73
|
+
*/
|
|
74
|
+
replicateToNode(replicaDidOrPubkey: string, commitment: ChainCommitmentPayload): Promise<ChainReplicaSyncAck>;
|
|
75
|
+
private handleInternalRequest;
|
|
76
|
+
close(): void;
|
|
77
|
+
}
|
|
78
|
+
//#endregion
|
|
79
|
+
export { ChainCommitmentPayload, ChainNodeDarknet, ChainNodeDarknetOptions, ChainNodeRole, ChainReplicaSyncAck, ChainWitnessAttestation, canonicalizeCommitment, verifyWitnessAttestation };
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { NoiseHttpBridge } from "./http-transport.mjs";
|
|
2
|
+
import { fromHex, toHex } from "./noise-session.mjs";
|
|
3
|
+
import { MultiMeshRouter } from "./mesh-tunnel.mjs";
|
|
4
|
+
import { ed25519 } from "@noble/curves/ed25519.js";
|
|
5
|
+
|
|
6
|
+
//#region src/chain-node-mesh.ts
|
|
7
|
+
/**
|
|
8
|
+
* ChainNodeDarknet — Zero-Exposure Internal Mesh for Blockchain Nodes
|
|
9
|
+
* (Sequencer <-> Witness / Replica / Gateway)
|
|
10
|
+
*
|
|
11
|
+
* Implements Milestone M3 of Issue #1018 (planning/36 & planning/47):
|
|
12
|
+
* - Sequencer, Witness, Replica, and Gateway nodes communicate exclusively over
|
|
13
|
+
* `Noise_IK` (`@arcblock/did-noise`) encrypted channels inside an isolated `chain-darknet:<chainId>` mesh.
|
|
14
|
+
* - Unauthorized connection attempts are silently dropped in 1-RTT (`NoiseStealthDropError`).
|
|
15
|
+
* - Sequencer collects Ed25519 co-signatures from Witness nodes and replicates commitments
|
|
16
|
+
* to Replicas/Gateways over standard `NoiseHttpBridge` routes (`/internal/witness/sign`, `/internal/replica/sync`).
|
|
17
|
+
*/
|
|
18
|
+
const encoder = new TextEncoder();
|
|
19
|
+
function canonicalizeCommitment(c) {
|
|
20
|
+
return encoder.encode(`${c.chainId}:${c.height}:${c.stateRoot}:${c.txRoot}:${c.timestamp}:${c.sequencerDid}`);
|
|
21
|
+
}
|
|
22
|
+
function verifyWitnessAttestation(commitment, attestation) {
|
|
23
|
+
if (attestation.chainId !== commitment.chainId || attestation.height !== commitment.height || attestation.stateRoot !== commitment.stateRoot || attestation.txRoot !== commitment.txRoot) return false;
|
|
24
|
+
const msg = canonicalizeCommitment(commitment);
|
|
25
|
+
const sig = fromHex(attestation.signatureHex);
|
|
26
|
+
const pub = fromHex(attestation.witnessPubkeyHex);
|
|
27
|
+
return ed25519.verify(sig, msg, pub);
|
|
28
|
+
}
|
|
29
|
+
var ChainNodeDarknet = class {
|
|
30
|
+
constructor(options) {
|
|
31
|
+
this.bridges = /* @__PURE__ */ new Map();
|
|
32
|
+
this.syncedCommitments = [];
|
|
33
|
+
this.chainId = options.chainId;
|
|
34
|
+
this.role = options.role;
|
|
35
|
+
this.identity = options.identity;
|
|
36
|
+
this.meshId = `chain-darknet:${options.chainId}`;
|
|
37
|
+
this.authorizedSequencers = new Set(options.authorizedSequencerDids ?? []);
|
|
38
|
+
this.onCommitmentSynced = options.onCommitmentSynced;
|
|
39
|
+
this.validateCommitmentForWitness = options.validateCommitmentForWitness;
|
|
40
|
+
this.router = new MultiMeshRouter(options.identity);
|
|
41
|
+
this.router.joinMesh({
|
|
42
|
+
meshId: this.meshId,
|
|
43
|
+
allowedPeers: options.authorizedPeers,
|
|
44
|
+
label: `Chain Darknet (${options.chainId})`
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
getSyncedCommitments() {
|
|
48
|
+
return [...this.syncedCommitments];
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Establish a bidirectional encrypted Noise_IK channel + HTTP bridge with a remote `ChainNodeDarknet`
|
|
52
|
+
* (or custom packet transport).
|
|
53
|
+
*/
|
|
54
|
+
connectToNode(targetNode) {
|
|
55
|
+
const { handshakeMsg, channel: localChannel } = this.router.initiateHandshake(this.meshId, targetNode.identity.pubkeyHex);
|
|
56
|
+
const { responseMsg, channel: remoteChannel } = targetNode.router.respondHandshake(handshakeMsg);
|
|
57
|
+
localChannel.completeHandshake(responseMsg);
|
|
58
|
+
const refs = {};
|
|
59
|
+
const remoteBridge = new NoiseHttpBridge(remoteChannel, {
|
|
60
|
+
sendEncrypted: (ct) => refs.localBridge?.receiveEncrypted(ct),
|
|
61
|
+
handler: targetNode.handleInternalRequest.bind(targetNode)
|
|
62
|
+
});
|
|
63
|
+
const localBridge = new NoiseHttpBridge(localChannel, {
|
|
64
|
+
sendEncrypted: (ct) => remoteBridge.receiveEncrypted(ct),
|
|
65
|
+
handler: this.handleInternalRequest.bind(this)
|
|
66
|
+
});
|
|
67
|
+
refs.localBridge = localBridge;
|
|
68
|
+
refs.remoteBridge = remoteBridge;
|
|
69
|
+
const remoteDid = targetNode.identity.did ?? targetNode.identity.pubkeyHex;
|
|
70
|
+
const localDid = this.identity.did ?? this.identity.pubkeyHex;
|
|
71
|
+
this.bridges.set(remoteDid, localBridge);
|
|
72
|
+
this.bridges.set(targetNode.identity.pubkeyHex, localBridge);
|
|
73
|
+
targetNode.bridges.set(localDid, remoteBridge);
|
|
74
|
+
targetNode.bridges.set(this.identity.pubkeyHex, remoteBridge);
|
|
75
|
+
return {
|
|
76
|
+
localChannel,
|
|
77
|
+
remoteChannel
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Sequencer calls a Witness node over the darknet tunnel to obtain an Ed25519 attestation.
|
|
82
|
+
*/
|
|
83
|
+
async requestWitnessSignature(witnessDidOrPubkey, commitment) {
|
|
84
|
+
const bridge = this.bridges.get(witnessDidOrPubkey);
|
|
85
|
+
if (!bridge) throw new Error(`No active darknet bridge to witness "${witnessDidOrPubkey}"`);
|
|
86
|
+
const res = await bridge.fetch("http://witness.internal/internal/witness/sign", {
|
|
87
|
+
method: "POST",
|
|
88
|
+
headers: { "content-type": "application/json" },
|
|
89
|
+
body: JSON.stringify(commitment)
|
|
90
|
+
});
|
|
91
|
+
if (!res.ok) {
|
|
92
|
+
const errText = await res.text();
|
|
93
|
+
throw new Error(`Witness rejected commitment (${res.status}): ${errText}`);
|
|
94
|
+
}
|
|
95
|
+
const attestation = await res.json();
|
|
96
|
+
if (!verifyWitnessAttestation(commitment, attestation)) throw new Error(`Invalid Ed25519 signature returned by witness ${attestation.witnessDid}`);
|
|
97
|
+
return attestation;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Sequencer replicates a commitment to a Replica or Gateway node over the darknet tunnel.
|
|
101
|
+
*/
|
|
102
|
+
async replicateToNode(replicaDidOrPubkey, commitment) {
|
|
103
|
+
const bridge = this.bridges.get(replicaDidOrPubkey);
|
|
104
|
+
if (!bridge) throw new Error(`No active darknet bridge to replica "${replicaDidOrPubkey}"`);
|
|
105
|
+
const res = await bridge.fetch("http://replica.internal/internal/replica/sync", {
|
|
106
|
+
method: "POST",
|
|
107
|
+
headers: { "content-type": "application/json" },
|
|
108
|
+
body: JSON.stringify(commitment)
|
|
109
|
+
});
|
|
110
|
+
if (!res.ok) {
|
|
111
|
+
const errText = await res.text();
|
|
112
|
+
throw new Error(`Replica sync failed (${res.status}): ${errText}`);
|
|
113
|
+
}
|
|
114
|
+
return await res.json();
|
|
115
|
+
}
|
|
116
|
+
async handleInternalRequest(req, ctx) {
|
|
117
|
+
const url = new URL(req.url);
|
|
118
|
+
if (this.authorizedSequencers.size > 0 && !this.authorizedSequencers.has(ctx.remoteDid) && !this.authorizedSequencers.has(ctx.remotePubkeyHex)) return new Response(JSON.stringify({ error: `Sender ${ctx.remoteDid} is not an authorized sequencer` }), {
|
|
119
|
+
status: 403,
|
|
120
|
+
headers: { "content-type": "application/json" }
|
|
121
|
+
});
|
|
122
|
+
if (req.method === "POST" && url.pathname === "/internal/witness/sign") {
|
|
123
|
+
if (this.role !== "witness") return new Response(JSON.stringify({ error: "Node is not a witness" }), {
|
|
124
|
+
status: 400,
|
|
125
|
+
headers: { "content-type": "application/json" }
|
|
126
|
+
});
|
|
127
|
+
const commitment = await req.json();
|
|
128
|
+
if (commitment.chainId !== this.chainId) return new Response(JSON.stringify({ error: "Chain ID mismatch" }), {
|
|
129
|
+
status: 400,
|
|
130
|
+
headers: { "content-type": "application/json" }
|
|
131
|
+
});
|
|
132
|
+
if (this.validateCommitmentForWitness) {
|
|
133
|
+
if (!await this.validateCommitmentForWitness(commitment, ctx)) return new Response(JSON.stringify({ error: "Commitment rejected by witness policy" }), {
|
|
134
|
+
status: 422,
|
|
135
|
+
headers: { "content-type": "application/json" }
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
const msg = canonicalizeCommitment(commitment);
|
|
139
|
+
const seed = this.identity.secretKey.subarray(0, 32);
|
|
140
|
+
const sig = ed25519.sign(msg, seed);
|
|
141
|
+
const attestation = {
|
|
142
|
+
chainId: this.chainId,
|
|
143
|
+
height: commitment.height,
|
|
144
|
+
stateRoot: commitment.stateRoot,
|
|
145
|
+
txRoot: commitment.txRoot,
|
|
146
|
+
witnessDid: this.identity.did ?? "",
|
|
147
|
+
witnessPubkeyHex: this.identity.pubkeyHex,
|
|
148
|
+
signatureHex: toHex(sig)
|
|
149
|
+
};
|
|
150
|
+
return new Response(JSON.stringify(attestation), {
|
|
151
|
+
status: 200,
|
|
152
|
+
headers: { "content-type": "application/json" }
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
if (req.method === "POST" && url.pathname === "/internal/replica/sync") {
|
|
156
|
+
const commitment = await req.json();
|
|
157
|
+
if (commitment.chainId !== this.chainId) return new Response(JSON.stringify({ error: "Chain ID mismatch" }), {
|
|
158
|
+
status: 400,
|
|
159
|
+
headers: { "content-type": "application/json" }
|
|
160
|
+
});
|
|
161
|
+
this.syncedCommitments.push(commitment);
|
|
162
|
+
if (this.onCommitmentSynced) await this.onCommitmentSynced(commitment, ctx);
|
|
163
|
+
const ack = {
|
|
164
|
+
ok: true,
|
|
165
|
+
replicaDid: this.identity.did ?? "",
|
|
166
|
+
ackedHeight: commitment.height,
|
|
167
|
+
stateRoot: commitment.stateRoot
|
|
168
|
+
};
|
|
169
|
+
return new Response(JSON.stringify(ack), {
|
|
170
|
+
status: 200,
|
|
171
|
+
headers: { "content-type": "application/json" }
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
return new Response(JSON.stringify({ error: "Not Found" }), {
|
|
175
|
+
status: 404,
|
|
176
|
+
headers: { "content-type": "application/json" }
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
close() {
|
|
180
|
+
for (const bridge of this.bridges.values()) bridge.close();
|
|
181
|
+
this.bridges.clear();
|
|
182
|
+
this.router.leaveMesh(this.meshId);
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
//#endregion
|
|
187
|
+
export { ChainNodeDarknet, canonicalizeCommitment, verifyWitnessAttestation };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { NoiseHandshakeClaims } from "./noise-session.mjs";
|
|
2
|
+
import { EncryptedChannel, MultiMeshRouter } from "./mesh-tunnel.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/http-transport.d.ts
|
|
5
|
+
|
|
6
|
+
interface NoiseHttpRequestEnvelope {
|
|
7
|
+
kind: 'noise-http-req';
|
|
8
|
+
id: string;
|
|
9
|
+
method: string;
|
|
10
|
+
url: string;
|
|
11
|
+
headers: Record<string, string>;
|
|
12
|
+
bodyBase64?: string;
|
|
13
|
+
}
|
|
14
|
+
interface NoiseHttpResponseEnvelope {
|
|
15
|
+
kind: 'noise-http-res';
|
|
16
|
+
id: string;
|
|
17
|
+
status: number;
|
|
18
|
+
statusText: string;
|
|
19
|
+
headers: Record<string, string>;
|
|
20
|
+
bodyBase64?: string;
|
|
21
|
+
error?: string;
|
|
22
|
+
}
|
|
23
|
+
interface NoisePeerContext {
|
|
24
|
+
remoteDid: string;
|
|
25
|
+
remotePubkeyHex: string;
|
|
26
|
+
meshId?: string;
|
|
27
|
+
claims: NoiseHandshakeClaims | null;
|
|
28
|
+
}
|
|
29
|
+
type NoiseHttpHandler = (request: Request, context: NoisePeerContext) => Promise<Response> | Response;
|
|
30
|
+
interface NoiseHttpBridgeOptions {
|
|
31
|
+
/** Default request timeout in milliseconds (default: 15_000) */
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
/** Optional server-side HTTP handler for incoming requests on this channel */
|
|
34
|
+
handler?: NoiseHttpHandler;
|
|
35
|
+
/** Callback to transmit encrypted bytes to the remote peer */
|
|
36
|
+
sendEncrypted: (ciphertext: Uint8Array) => void | Promise<void>;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Multiplexes standard Web `Request` / `Response` pairs over a single `EncryptedChannel`.
|
|
40
|
+
*/
|
|
41
|
+
declare class NoiseHttpBridge {
|
|
42
|
+
private readonly channel;
|
|
43
|
+
private readonly sendEncrypted;
|
|
44
|
+
private readonly timeoutMs;
|
|
45
|
+
private handler?;
|
|
46
|
+
private readonly pending;
|
|
47
|
+
private readonly unsubMessage;
|
|
48
|
+
constructor(channel: EncryptedChannel, options: NoiseHttpBridgeOptions);
|
|
49
|
+
setHandler(handler: NoiseHttpHandler): void;
|
|
50
|
+
/**
|
|
51
|
+
* Feed an incoming encrypted frame from the network into the bridge.
|
|
52
|
+
*/
|
|
53
|
+
receiveEncrypted(ciphertext: Uint8Array): void;
|
|
54
|
+
/**
|
|
55
|
+
* Standard Web `fetch` implementation bound to this encrypted channel.
|
|
56
|
+
*/
|
|
57
|
+
fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
|
|
58
|
+
private onDecryptedMessage;
|
|
59
|
+
close(): void;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* Convenience helper to create a standard `(input, init) => Promise<Response>` fetch function
|
|
63
|
+
* bound to a `NoiseHttpBridge`.
|
|
64
|
+
*/
|
|
65
|
+
declare function createNoiseFetch(bridge: NoiseHttpBridge): (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
66
|
+
/**
|
|
67
|
+
* Create a Multi-VLAN aware `fetch` function that routes requests by virtual IP (`http://10.x.y.z/...`)
|
|
68
|
+
* or explicit mesh URL (`http://<peerDid>.<meshId>.arc/...`) across a `MultiMeshRouter`.
|
|
69
|
+
*/
|
|
70
|
+
declare function createMultiMeshFetch(router: MultiMeshRouter, getBridgeForChannel: (channel: EncryptedChannel, meshId: string) => NoiseHttpBridge): (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
|
|
71
|
+
//#endregion
|
|
72
|
+
export { NoiseHttpBridge, NoiseHttpBridgeOptions, NoiseHttpHandler, NoiseHttpRequestEnvelope, NoiseHttpResponseEnvelope, NoisePeerContext, createMultiMeshFetch, createNoiseFetch };
|