@steve02081504/fount-p2p 0.0.12 → 0.0.13
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 +41 -10
- package/core/composite_key.mjs +5 -5
- package/crypto/crypto.mjs +3 -3
- package/crypto/key.mjs +12 -12
- package/dag/storage.mjs +36 -36
- package/discovery/advert_peer_hints.mjs +1 -1
- package/discovery/adverts.mjs +109 -0
- package/discovery/bt/index.mjs +153 -112
- package/discovery/bt/probe_child.mjs +2 -1
- package/discovery/bt/runtime.mjs +2 -9
- package/discovery/index.mjs +267 -62
- package/discovery/internal/signal_crypto.mjs +109 -0
- package/discovery/lan.mjs +228 -0
- package/discovery/nostr.mjs +394 -59
- package/federation/chunk_fetch_pending.mjs +10 -13
- package/federation/manifest_fetch_pending.mjs +1 -3
- package/files/assemble.mjs +14 -14
- package/files/assemble_stream.mjs +6 -6
- package/files/chunk_responder.mjs +29 -20
- package/files/evfs.mjs +29 -28
- package/files/manifest_fetch.mjs +16 -3
- package/files/public_manifest.mjs +11 -11
- package/files/transfer_key_registry.mjs +2 -2
- package/index.mjs +86 -11
- package/infra/cli.mjs +62 -0
- package/infra/debug_log.mjs +56 -0
- package/infra/default_node_dir.mjs +22 -0
- package/infra/priority.mjs +56 -0
- package/infra/service.mjs +140 -0
- package/infra/tunables.json +5 -0
- package/link/frame.mjs +9 -16
- package/link/handshake.mjs +14 -15
- package/link/pipe.mjs +8 -8
- package/link/providers/ble_gatt.mjs +6 -6
- package/link/rtc.mjs +3 -3
- package/mailbox/consumer_registry.mjs +2 -2
- package/mailbox/deliver_or_store.mjs +5 -5
- package/mailbox/wire.mjs +28 -24
- package/node/entity_store.mjs +6 -6
- package/node/instance.mjs +46 -27
- package/node/local_data_revision.mjs +26 -0
- package/node/log.mjs +56 -0
- package/node/network.mjs +37 -5
- package/node/reputation_store.mjs +4 -4
- package/node/reputation_sync.mjs +318 -0
- package/node/routing_profile.mjs +21 -0
- package/node/signaling_config.mjs +30 -11
- package/overlay/index.mjs +22 -1
- package/package.json +13 -2
- package/rooms/scoped_link.mjs +17 -166
- package/transport/advert_ingest.mjs +11 -14
- package/transport/group_link_set.mjs +149 -99
- package/transport/link_registry.mjs +211 -60
- package/transport/mesh_keepalive.mjs +217 -0
- package/transport/node_scope.mjs +289 -0
- package/transport/offer_answer.mjs +45 -48
- package/transport/peer_pool.mjs +116 -14
- package/transport/remote_user_room.mjs +6 -9
- package/transport/{rtc_mdns_filter.mjs → rtc_ice_local_hostname.mjs} +13 -13
- package/transport/runtime_bootstrap.mjs +170 -108
- package/transport/tunables.json +11 -0
- package/transport/tunables.mjs +18 -0
- package/transport/user_room.mjs +83 -158
- package/trust_graph/build.mjs +0 -2
- package/trust_graph/cache.mjs +12 -3
- package/trust_graph/registry.mjs +6 -6
- package/trust_graph/send.mjs +0 -3
- package/utils/async_mutex.mjs +4 -4
- package/utils/emit_safe.mjs +3 -3
- package/utils/json_io.mjs +12 -12
- package/utils/map_pool.mjs +5 -5
- package/wire/part_ingress.mjs +32 -28
- package/wire/part_query.mjs +26 -20
- package/discovery/mdns.mjs +0 -197
- package/transport/signal_crypto.mjs +0 -104
package/node/instance.mjs
CHANGED
|
@@ -3,7 +3,7 @@ import path from 'node:path'
|
|
|
3
3
|
import { createFsEntityStore } from './entity_store.mjs'
|
|
4
4
|
import { defaultSignalingRuntimeConfig, resolveSignalingRuntimeConfig } from './signaling_config.mjs'
|
|
5
5
|
|
|
6
|
-
/** @typedef {{ warn?: (...args: unknown[]) => void, error?: (...args: unknown[]) => void }} NodeLogger */
|
|
6
|
+
/** @typedef {{ warn?: (...args: unknown[]) => void, error?: (...args: unknown[]) => void, info?: (...args: unknown[]) => void, log?: (...args: unknown[]) => void }} NodeLogger */
|
|
7
7
|
|
|
8
8
|
/** @typedef {import('./signaling_config.mjs').SignalingRuntimeConfig} SignalingRuntimeConfig */
|
|
9
9
|
|
|
@@ -11,7 +11,7 @@ import { defaultSignalingRuntimeConfig, resolveSignalingRuntimeConfig } from './
|
|
|
11
11
|
* @typedef {{
|
|
12
12
|
* nodeDir: string
|
|
13
13
|
* entityStore: import('./entity_store.mjs').EntityStore
|
|
14
|
-
* logger: NodeLogger
|
|
14
|
+
* logger: NodeLogger | null
|
|
15
15
|
* signaling: SignalingRuntimeConfig
|
|
16
16
|
* }} NodeRuntime
|
|
17
17
|
*/
|
|
@@ -22,37 +22,28 @@ let runtime = null
|
|
|
22
22
|
/** @type {Set<(event: string, payload?: unknown) => void>} */
|
|
23
23
|
const changeListeners = new Set()
|
|
24
24
|
|
|
25
|
-
/** @type {NodeLogger} */
|
|
26
|
-
const noopLogger = {
|
|
27
|
-
/**
|
|
28
|
-
*
|
|
29
|
-
*/
|
|
30
|
-
warn() { },
|
|
31
|
-
/**
|
|
32
|
-
*
|
|
33
|
-
*/
|
|
34
|
-
error() { },
|
|
35
|
-
}
|
|
36
|
-
|
|
37
25
|
/**
|
|
38
|
-
* @param {{ nodeDir: string, entityStore?: import('./entity_store.mjs').EntityStore
|
|
39
|
-
* @returns {NodeRuntime}
|
|
26
|
+
* @param {{ nodeDir: string, entityStore?: import('./entity_store.mjs').EntityStore }} options - 节点目录与可选 entity store
|
|
27
|
+
* @returns {NodeRuntime} 初始化后的运行时
|
|
40
28
|
*/
|
|
41
29
|
export function initNode(options) {
|
|
30
|
+
if (runtime) throw new Error('p2p: initNode already called — use setNodeLogger / setSignalingRuntimeConfig or resetNodeForTests')
|
|
31
|
+
if (options?.logger !== undefined || options?.signaling !== undefined)
|
|
32
|
+
throw new Error('p2p: initNode only accepts nodeDir/entityStore — use setNodeLogger / setSignalingRuntimeConfig')
|
|
42
33
|
const nodeDir = path.resolve(String(options.nodeDir || '').trim())
|
|
43
34
|
if (!nodeDir) throw new Error('p2p: initNode requires nodeDir')
|
|
44
35
|
const entityStore = options.entityStore ?? createFsEntityStore(path.join(nodeDir, 'entities'))
|
|
45
36
|
runtime = {
|
|
46
37
|
nodeDir,
|
|
47
38
|
entityStore,
|
|
48
|
-
logger:
|
|
49
|
-
signaling:
|
|
39
|
+
logger: console,
|
|
40
|
+
signaling: resolveSignalingRuntimeConfig(),
|
|
50
41
|
}
|
|
51
42
|
return runtime
|
|
52
43
|
}
|
|
53
44
|
|
|
54
45
|
/**
|
|
55
|
-
* @returns {NodeRuntime}
|
|
46
|
+
* @returns {NodeRuntime} 当前节点运行时
|
|
56
47
|
*/
|
|
57
48
|
export function getNode() {
|
|
58
49
|
if (!runtime) throw new Error('p2p: node not initialized — call initNode() first')
|
|
@@ -67,7 +58,26 @@ export function isNodeInitialized() {
|
|
|
67
58
|
}
|
|
68
59
|
|
|
69
60
|
/**
|
|
70
|
-
* @
|
|
61
|
+
* @param {NodeLogger | null} logger - 节点日志器,null 表示静默
|
|
62
|
+
* @returns {void}
|
|
63
|
+
*/
|
|
64
|
+
export function setNodeLogger(logger) {
|
|
65
|
+
if (!runtime) throw new Error('p2p: setNodeLogger requires initNode')
|
|
66
|
+
runtime.logger = logger ?? null
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* @param {Partial<SignalingRuntimeConfig>} config - signaling 运行时补丁
|
|
71
|
+
* @returns {void}
|
|
72
|
+
*/
|
|
73
|
+
export function setSignalingRuntimeConfig(config) {
|
|
74
|
+
if (!runtime) throw new Error('p2p: setSignalingRuntimeConfig requires initNode')
|
|
75
|
+
runtime.signaling = resolveSignalingRuntimeConfig({ ...runtime.signaling, ...config })
|
|
76
|
+
emitNodeChange('signaling-changed', runtime.signaling)
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* @returns {SignalingRuntimeConfig} 当前 signaling 配置
|
|
71
81
|
*/
|
|
72
82
|
export function getSignalingRuntimeConfig() {
|
|
73
83
|
return runtime?.signaling ?? defaultSignalingRuntimeConfig()
|
|
@@ -81,22 +91,22 @@ export function getNodeDir() {
|
|
|
81
91
|
}
|
|
82
92
|
|
|
83
93
|
/**
|
|
84
|
-
* @returns {import('./entity_store.mjs').EntityStore}
|
|
94
|
+
* @returns {import('./entity_store.mjs').EntityStore} 当前 entity store
|
|
85
95
|
*/
|
|
86
96
|
export function getEntityStore() {
|
|
87
97
|
return getNode().entityStore
|
|
88
98
|
}
|
|
89
99
|
|
|
90
100
|
/**
|
|
91
|
-
* @returns {NodeLogger
|
|
101
|
+
* @returns {NodeLogger | null} 当前节点日志器
|
|
92
102
|
*/
|
|
93
103
|
export function getNodeLogger() {
|
|
94
|
-
return runtime?.logger ??
|
|
104
|
+
return runtime?.logger ?? null
|
|
95
105
|
}
|
|
96
106
|
|
|
97
107
|
/**
|
|
98
|
-
* @param {string} event
|
|
99
|
-
* @param {unknown} [payload]
|
|
108
|
+
* @param {string} event - 变更事件名
|
|
109
|
+
* @param {unknown} [payload] - 事件载荷
|
|
100
110
|
* @returns {void}
|
|
101
111
|
*/
|
|
102
112
|
export function emitNodeChange(event, payload) {
|
|
@@ -106,10 +116,19 @@ export function emitNodeChange(event, payload) {
|
|
|
106
116
|
}
|
|
107
117
|
|
|
108
118
|
/**
|
|
109
|
-
* @param {(event: string, payload?: unknown) => void} listener
|
|
110
|
-
* @returns {() => void}
|
|
119
|
+
* @param {(event: string, payload?: unknown) => void} listener - 变更回调
|
|
120
|
+
* @returns {() => void} 取消监听的 dispose
|
|
111
121
|
*/
|
|
112
122
|
export function onNodeChange(listener) {
|
|
113
123
|
changeListeners.add(listener)
|
|
114
124
|
return () => changeListeners.delete(listener)
|
|
115
125
|
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* 测试专用:重置节点运行时。
|
|
129
|
+
* @returns {void}
|
|
130
|
+
*/
|
|
131
|
+
export function resetNodeForTests() {
|
|
132
|
+
runtime = null
|
|
133
|
+
changeListeners.clear()
|
|
134
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** 本机落盘数据 revision:信任图等订阅方只读,store 不反向依赖 trust_graph。 */
|
|
2
|
+
|
|
3
|
+
let revision = 0
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 本机数据 revision +1(信任图等订阅方)。
|
|
7
|
+
* @returns {void}
|
|
8
|
+
*/
|
|
9
|
+
export function bumpLocalDataRevision() {
|
|
10
|
+
revision++
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @returns {number} 当前本机数据 revision
|
|
15
|
+
*/
|
|
16
|
+
export function getLocalDataRevision() {
|
|
17
|
+
return revision
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 测试用:清零 revision。
|
|
22
|
+
* @returns {void}
|
|
23
|
+
*/
|
|
24
|
+
export function resetLocalDataRevisionForTests() {
|
|
25
|
+
revision = 0
|
|
26
|
+
}
|
package/node/log.mjs
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { getNodeLogger } from './instance.mjs'
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* 连接/发现诊断日志开关。
|
|
5
|
+
* CLI(非 --quiet)默认打开;非 CLI 用 `setConnectivityDebug(true)`。
|
|
6
|
+
* @type {boolean}
|
|
7
|
+
*/
|
|
8
|
+
let connectivityDebug = false
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* @param {boolean} enabled 是否输出连接诊断
|
|
12
|
+
* @returns {void}
|
|
13
|
+
*/
|
|
14
|
+
export function setConnectivityDebug(enabled) {
|
|
15
|
+
connectivityDebug = !!enabled
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @returns {boolean} 当前是否输出连接诊断
|
|
20
|
+
*/
|
|
21
|
+
export function isConnectivityDebug() {
|
|
22
|
+
return connectivityDebug
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 缩短 nodeHash 便于对照两边日志。
|
|
27
|
+
* @param {string | null | undefined} hash 完整 hash
|
|
28
|
+
* @param {number} [n=8] 前缀长度
|
|
29
|
+
* @returns {string} 短 hash
|
|
30
|
+
*/
|
|
31
|
+
export function shortHash(hash, n = 8) {
|
|
32
|
+
const value = String(hash || '')
|
|
33
|
+
return value.length <= n ? value : value.slice(0, n)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 连接诊断 info(未开启或无 logger 时静默)。
|
|
38
|
+
* @param {string} message 消息
|
|
39
|
+
* @param {object} [extra] 附加字段
|
|
40
|
+
* @returns {void}
|
|
41
|
+
*/
|
|
42
|
+
export function nodeDebug(message, extra) {
|
|
43
|
+
if (!connectivityDebug) return
|
|
44
|
+
const logger = getNodeLogger()
|
|
45
|
+
if (!logger?.info) return
|
|
46
|
+
if (extra === undefined) logger.info(message)
|
|
47
|
+
else logger.info(message, extra)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* 测试专用:关掉连接诊断。
|
|
52
|
+
* @returns {void}
|
|
53
|
+
*/
|
|
54
|
+
export function resetConnectivityDebugForTests() {
|
|
55
|
+
connectivityDebug = false
|
|
56
|
+
}
|
package/node/network.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { isEntityHash128 } from '../core/entity_id.mjs'
|
|
2
2
|
import { isHex64, normalizeHex64 } from '../core/hexIds.mjs'
|
|
3
|
-
import { invalidateTrustGraphCache } from '../trust_graph/cache.mjs'
|
|
4
3
|
|
|
5
4
|
import { loadDenylist } from './denylist.mjs'
|
|
6
5
|
import { getNodeDir, isNodeInitialized } from './instance.mjs'
|
|
6
|
+
import { bumpLocalDataRevision } from './local_data_revision.mjs'
|
|
7
7
|
import { readNodeJsonSync, writeNodeJsonSync } from './storage.mjs'
|
|
8
8
|
|
|
9
9
|
|
|
@@ -28,6 +28,7 @@ import { readNodeJsonSync, writeNodeJsonSync } from './storage.mjs'
|
|
|
28
28
|
|
|
29
29
|
const DATA_NAME = 'network'
|
|
30
30
|
const MAX_EXPLORE = 500
|
|
31
|
+
const MAX_TRUSTED = 64
|
|
31
32
|
const MAX_HINTS = 256
|
|
32
33
|
const MAX_HINTS_PER_SOURCE = 12
|
|
33
34
|
const DEFAULT_EXPLORE_TTL_MS = 7 * 24 * 60 * 60 * 1000
|
|
@@ -97,10 +98,10 @@ export function capHintsBySource(hints, maxPerSource = MAX_HINTS_PER_SOURCE) {
|
|
|
97
98
|
const counts = new Map()
|
|
98
99
|
const out = []
|
|
99
100
|
for (const hint of [...hints].reverse()) {
|
|
100
|
-
const
|
|
101
|
-
const n = counts.get(
|
|
101
|
+
const source = String(hint.source || 'unknown')
|
|
102
|
+
const n = counts.get(source) ?? 0
|
|
102
103
|
if (n >= maxPerSource) continue
|
|
103
|
-
counts.set(
|
|
104
|
+
counts.set(source, n + 1)
|
|
104
105
|
out.unshift(hint)
|
|
105
106
|
}
|
|
106
107
|
return out
|
|
@@ -115,10 +116,11 @@ export function saveNetwork(data) {
|
|
|
115
116
|
const now = Date.now()
|
|
116
117
|
clean.hints = capHintsBySource(clean.hints.filter(h => !h.expiresAt || h.expiresAt > now)).slice(-MAX_HINTS)
|
|
117
118
|
clean.explorePeers = clean.explorePeers.slice(-MAX_EXPLORE)
|
|
119
|
+
clean.trustedPeers = clean.trustedPeers.slice(-MAX_TRUSTED)
|
|
118
120
|
writeNodeJsonSync(DATA_NAME, clean)
|
|
119
121
|
networkCache = clean
|
|
120
122
|
networkCacheNodeDir = isNodeInitialized() ? getNodeDir() : ''
|
|
121
|
-
|
|
123
|
+
bumpLocalDataRevision()
|
|
122
124
|
}
|
|
123
125
|
|
|
124
126
|
/**
|
|
@@ -196,6 +198,36 @@ export function mergeNetworkPeerPools(patch = {}) {
|
|
|
196
198
|
saveNetwork(net)
|
|
197
199
|
}
|
|
198
200
|
|
|
201
|
+
/**
|
|
202
|
+
* 稳定探索对端升入熟人池(从 explore 移除并追加 trusted)。
|
|
203
|
+
* @param {string} nodeHash 对端 nodeHash
|
|
204
|
+
* @returns {void}
|
|
205
|
+
*/
|
|
206
|
+
export function promoteExplorePeer(nodeHash) {
|
|
207
|
+
const net = loadNetwork()
|
|
208
|
+
const id = normalizeHex64(nodeHash)
|
|
209
|
+
if (!isHex64(id)) return
|
|
210
|
+
net.explorePeers = net.explorePeers.filter(peer => peer !== id)
|
|
211
|
+
if (!net.trustedPeers.includes(id)) net.trustedPeers.push(id)
|
|
212
|
+
net.lastRosterAt = Date.now()
|
|
213
|
+
saveNetwork(net)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* 整表替换 trusted/explore 池(可缩池)。
|
|
218
|
+
* @param {{ trustedPeers?: string[], explorePeers?: string[] }} pools - 要替换的 peer 池
|
|
219
|
+
* @returns {void}
|
|
220
|
+
*/
|
|
221
|
+
export function replaceNetworkPeerPools(pools = {}) {
|
|
222
|
+
const net = loadNetwork()
|
|
223
|
+
if (Array.isArray(pools.trustedPeers))
|
|
224
|
+
net.trustedPeers = pools.trustedPeers.map(id => normalizeHex64(id)).filter(id => isHex64(id))
|
|
225
|
+
if (Array.isArray(pools.explorePeers))
|
|
226
|
+
net.explorePeers = pools.explorePeers.map(id => normalizeHex64(id)).filter(id => isHex64(id))
|
|
227
|
+
net.lastRosterAt = Date.now()
|
|
228
|
+
saveNetwork(net)
|
|
229
|
+
}
|
|
230
|
+
|
|
199
231
|
/**
|
|
200
232
|
* @param {string} groupId 群 scope
|
|
201
233
|
* @param {'node' | 'subject' | 'entity'} scope denylist 作用域
|
|
@@ -18,10 +18,10 @@ import {
|
|
|
18
18
|
} from '../reputation/engine.mjs'
|
|
19
19
|
import { pickNodeScoreFromReputation } from '../reputation/pick_score.mjs'
|
|
20
20
|
import reputationTunables from '../reputation/tunables.json' with { type: 'json' }
|
|
21
|
-
import { invalidateTrustGraphCache } from '../trust_graph/cache.mjs'
|
|
22
21
|
import { withAsyncMutex } from '../utils/async_mutex.mjs'
|
|
23
22
|
|
|
24
23
|
import { getNodeDir, getNodeLogger, isNodeInitialized } from './instance.mjs'
|
|
24
|
+
import { bumpLocalDataRevision } from './local_data_revision.mjs'
|
|
25
25
|
import { readNodeJsonSync, writeNodeJsonSync } from './storage.mjs'
|
|
26
26
|
|
|
27
27
|
const DATA_NAME = 'reputation'
|
|
@@ -88,7 +88,7 @@ export function saveReputation(data) {
|
|
|
88
88
|
pruneReputationFile(data)
|
|
89
89
|
writeNodeJsonSync(DATA_NAME, data)
|
|
90
90
|
reputationCache = data
|
|
91
|
-
|
|
91
|
+
bumpLocalDataRevision()
|
|
92
92
|
}
|
|
93
93
|
|
|
94
94
|
/**
|
|
@@ -211,7 +211,7 @@ export async function applyVolatileSlashAlert(alert) {
|
|
|
211
211
|
* @param {object} [groupSettings] 群设置
|
|
212
212
|
* @returns {object} VOLATILE 载荷
|
|
213
213
|
*/
|
|
214
|
-
export function
|
|
214
|
+
export function buildUnverifiedSlashAlert(senderPubKeyHash, content, groupSettings = {}) {
|
|
215
215
|
const targetPubKeyHash = assertHex64(content.targetPubKeyHash, 'slash target')
|
|
216
216
|
const claim = Number.isFinite(Number(content.claim)) ? Number(content.claim) : reputationTunables.slashDefaultClaim
|
|
217
217
|
const sender = assertHex64(senderPubKeyHash, 'slash sender')
|
|
@@ -268,7 +268,7 @@ export function applyDecayCollusionAfterSlash(targetPubKeyHash, inviteEdges) {
|
|
|
268
268
|
void mutateReputation(data => {
|
|
269
269
|
const applied = applyDecayCollusionAfterSlashPure(data, targetPubKeyHash, inviteEdges)
|
|
270
270
|
if (applied.length)
|
|
271
|
-
getNodeLogger()
|
|
271
|
+
getNodeLogger()?.warn?.('reputation: collusion decay after slash', {
|
|
272
272
|
target: targetPubKeyHash.trim().toLowerCase(),
|
|
273
273
|
upstreamCount: applied.length,
|
|
274
274
|
hops: applied.map(row => row.hop),
|
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
|
|
3
|
+
import { isHex64, normalizeHex64 } from '../core/hexIds.mjs'
|
|
4
|
+
import { sendToNodeLink } from '../transport/link_registry.mjs'
|
|
5
|
+
import { attachNodeScopeFeature, ensureNodeScope, getNodeScopeWire } from '../transport/node_scope.mjs'
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
loadReputation,
|
|
9
|
+
mutateReputation,
|
|
10
|
+
} from './reputation_store.mjs'
|
|
11
|
+
import { readNodeJsonSync, writeNodeJsonSync } from './storage.mjs'
|
|
12
|
+
|
|
13
|
+
const SYNC_DATA_NAME = 'reputation_sync'
|
|
14
|
+
const MAX_LOCKED_SCORE = 1
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @typedef {{
|
|
18
|
+
* trustSyncDonors: string[]
|
|
19
|
+
* reputationExportAllowlist: string[]
|
|
20
|
+
* lockedMaxNodeHashes: string[]
|
|
21
|
+
* lockedMaxPrevByNodeHash: Record<string, number>
|
|
22
|
+
* }} ReputationSyncConfig
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/** @type {ReputationSyncConfig | null} */
|
|
26
|
+
let syncConfig = null
|
|
27
|
+
|
|
28
|
+
/** @type {Map<string, { resolve: (v: object) => void, reject: (e: Error) => void, timer: ReturnType<typeof setTimeout>, donor: string }>} */
|
|
29
|
+
const pendingPulls = new Map()
|
|
30
|
+
|
|
31
|
+
/** @type {Set<() => void>} */
|
|
32
|
+
const syncWireDisposers = new Set()
|
|
33
|
+
|
|
34
|
+
let pullTimeoutMs = 8000
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* @param {number} ms 超时毫秒;测试用
|
|
38
|
+
* @returns {void}
|
|
39
|
+
*/
|
|
40
|
+
export function setReputationPullTimeoutMsForTests(ms) {
|
|
41
|
+
pullTimeoutMs = Math.max(1, Number(ms) || 8000)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @returns {ReputationSyncConfig} 内存中的 sync 配置(首次从盘加载)
|
|
46
|
+
*/
|
|
47
|
+
function loadSyncConfig() {
|
|
48
|
+
if (syncConfig) return syncConfig
|
|
49
|
+
const raw = readNodeJsonSync(SYNC_DATA_NAME) || {}
|
|
50
|
+
/** @type {Record<string, number>} */
|
|
51
|
+
const lockedMaxPrevByNodeHash = {}
|
|
52
|
+
const prevRaw = raw.lockedMaxPrevByNodeHash && typeof raw.lockedMaxPrevByNodeHash === 'object'
|
|
53
|
+
? raw.lockedMaxPrevByNodeHash
|
|
54
|
+
: {}
|
|
55
|
+
for (const [nodeHash, score] of Object.entries(prevRaw)) {
|
|
56
|
+
const id = normalizeHex64(nodeHash)
|
|
57
|
+
const n = Number(score)
|
|
58
|
+
if (id && isHex64(id) && Number.isFinite(n)) lockedMaxPrevByNodeHash[id] = n
|
|
59
|
+
}
|
|
60
|
+
syncConfig = {
|
|
61
|
+
trustSyncDonors: normalizeHashList(raw.trustSyncDonors),
|
|
62
|
+
reputationExportAllowlist: normalizeHashList(raw.reputationExportAllowlist),
|
|
63
|
+
lockedMaxNodeHashes: normalizeHashList(raw.lockedMaxNodeHashes),
|
|
64
|
+
lockedMaxPrevByNodeHash,
|
|
65
|
+
}
|
|
66
|
+
return syncConfig
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* @param {unknown} list - 原始 hash 列表
|
|
71
|
+
* @returns {string[]} 规范化去重后的 64-hex 列表
|
|
72
|
+
*/
|
|
73
|
+
function normalizeHashList(list) {
|
|
74
|
+
return [...new Set((Array.isArray(list) ? list : [])
|
|
75
|
+
.map(id => normalizeHex64(id))
|
|
76
|
+
.filter(id => isHex64(id)))]
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* @returns {void}
|
|
81
|
+
*/
|
|
82
|
+
function persistSyncConfig() {
|
|
83
|
+
writeNodeJsonSync(SYNC_DATA_NAME, loadSyncConfig())
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* @returns {object} 当前 reputation 表(byNodeHash)
|
|
88
|
+
*/
|
|
89
|
+
export function getReputationTable() {
|
|
90
|
+
return loadReputation()
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* @param {object} table - 含 byNodeHash 的信誉表或裸 byNodeHash 对象
|
|
95
|
+
* @returns {void}
|
|
96
|
+
*/
|
|
97
|
+
export async function setReputationTable(table) {
|
|
98
|
+
const incoming = table?.byNodeHash && typeof table.byNodeHash === 'object' ? table.byNodeHash : table
|
|
99
|
+
if (!incoming || typeof incoming !== 'object') throw new Error('p2p: setReputationTable requires byNodeHash object')
|
|
100
|
+
await mutateReputation(data => {
|
|
101
|
+
data.byNodeHash = data.byNodeHash || {}
|
|
102
|
+
for (const [nodeHash, row] of Object.entries(incoming)) {
|
|
103
|
+
const id = normalizeHex64(nodeHash)
|
|
104
|
+
if (!id || !isHex64(id)) continue
|
|
105
|
+
const score = Number(row?.score ?? row)
|
|
106
|
+
if (!Number.isFinite(score)) continue
|
|
107
|
+
data.byNodeHash[id] = { ...data.byNodeHash[id] || {}, score }
|
|
108
|
+
}
|
|
109
|
+
applyLocksToReputation(data)
|
|
110
|
+
})
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* @param {object} data - reputation 存储对象
|
|
115
|
+
* @returns {void}
|
|
116
|
+
*/
|
|
117
|
+
function applyLocksToReputation(data) {
|
|
118
|
+
for (const nodeHash of loadSyncConfig().lockedMaxNodeHashes)
|
|
119
|
+
if (!data.byNodeHash[nodeHash]) data.byNodeHash[nodeHash] = { score: MAX_LOCKED_SCORE }
|
|
120
|
+
else data.byNodeHash[nodeHash].score = MAX_LOCKED_SCORE
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* 将节点分数钳到上限;首次 lock 时记下原分,unlock 时还原。
|
|
125
|
+
* @param {string[]} nodeHashes - 要 lock 的节点 hash 列表
|
|
126
|
+
* @returns {Promise<void>}
|
|
127
|
+
*/
|
|
128
|
+
export function lockReputationMax(nodeHashes) {
|
|
129
|
+
const config = loadSyncConfig()
|
|
130
|
+
const hashes = normalizeHashList(nodeHashes)
|
|
131
|
+
return mutateReputation(data => {
|
|
132
|
+
data.byNodeHash = data.byNodeHash || {}
|
|
133
|
+
for (const hash of hashes) {
|
|
134
|
+
if (config.lockedMaxNodeHashes.includes(hash)) continue
|
|
135
|
+
const prev = Number(data.byNodeHash[hash]?.score)
|
|
136
|
+
config.lockedMaxPrevByNodeHash[hash] = Number.isFinite(prev) ? prev : 0
|
|
137
|
+
config.lockedMaxNodeHashes.push(hash)
|
|
138
|
+
}
|
|
139
|
+
persistSyncConfig()
|
|
140
|
+
applyLocksToReputation(data)
|
|
141
|
+
})
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* 解除上限钳;还原 lock 前记下的分数。
|
|
146
|
+
* @param {string[]} nodeHashes - 要 unlock 的节点 hash 列表
|
|
147
|
+
* @returns {Promise<void>}
|
|
148
|
+
*/
|
|
149
|
+
export function unlockReputationMax(nodeHashes) {
|
|
150
|
+
const config = loadSyncConfig()
|
|
151
|
+
const remove = new Set(normalizeHashList(nodeHashes))
|
|
152
|
+
if (!remove.size) return Promise.resolve()
|
|
153
|
+
config.lockedMaxNodeHashes = config.lockedMaxNodeHashes.filter(id => !remove.has(id))
|
|
154
|
+
/** @type {Record<string, number>} */
|
|
155
|
+
const restore = {}
|
|
156
|
+
for (const hash of remove)
|
|
157
|
+
if (Object.hasOwn(config.lockedMaxPrevByNodeHash, hash)) {
|
|
158
|
+
restore[hash] = config.lockedMaxPrevByNodeHash[hash]
|
|
159
|
+
delete config.lockedMaxPrevByNodeHash[hash]
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
persistSyncConfig()
|
|
163
|
+
return mutateReputation(data => {
|
|
164
|
+
data.byNodeHash = data.byNodeHash || {}
|
|
165
|
+
for (const [hash, score] of Object.entries(restore))
|
|
166
|
+
if (!data.byNodeHash[hash]) data.byNodeHash[hash] = { score }
|
|
167
|
+
else data.byNodeHash[hash].score = score
|
|
168
|
+
})
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/**
|
|
172
|
+
* @returns {string[]} 当前锁定为满分的节点 hash 列表
|
|
173
|
+
*/
|
|
174
|
+
export function getReputationLocks() {
|
|
175
|
+
return [...loadSyncConfig().lockedMaxNodeHashes]
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* @param {string[]} donors - 允许拉取信誉的 donor 节点
|
|
180
|
+
* @returns {void}
|
|
181
|
+
*/
|
|
182
|
+
export function setTrustSyncDonors(donors) {
|
|
183
|
+
loadSyncConfig().trustSyncDonors = normalizeHashList(donors)
|
|
184
|
+
persistSyncConfig()
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* @returns {string[]} 当前 trustSyncDonors 副本
|
|
189
|
+
*/
|
|
190
|
+
export function getTrustSyncDonors() {
|
|
191
|
+
return [...loadSyncConfig().trustSyncDonors]
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* @param {string[]} allowlist - 允许导出本机信誉表的节点
|
|
196
|
+
* @returns {void}
|
|
197
|
+
*/
|
|
198
|
+
export function setReputationExportAllowlist(allowlist) {
|
|
199
|
+
loadSyncConfig().reputationExportAllowlist = normalizeHashList(allowlist)
|
|
200
|
+
persistSyncConfig()
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* @returns {string[]} 当前 reputationExportAllowlist 副本
|
|
205
|
+
*/
|
|
206
|
+
export function getReputationExportAllowlist() {
|
|
207
|
+
return [...loadSyncConfig().reputationExportAllowlist]
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* @returns {object} 仅含 score 的导出表
|
|
212
|
+
*/
|
|
213
|
+
function exportScoreTable() {
|
|
214
|
+
const rep = loadReputation()
|
|
215
|
+
/** @type {Record<string, { score: number }>} */
|
|
216
|
+
const byNodeHash = {}
|
|
217
|
+
for (const [nodeHash, row] of Object.entries(rep.byNodeHash || {}))
|
|
218
|
+
byNodeHash[nodeHash] = { score: Number(row?.score ?? 0) }
|
|
219
|
+
return { byNodeHash }
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* 挂载信誉同步 wire(refcount;处理 rep_sync_req / rep_sync_res)。
|
|
224
|
+
* @returns {() => void} 取消 wire 挂载的 dispose
|
|
225
|
+
*/
|
|
226
|
+
export function attachReputationSyncWire() {
|
|
227
|
+
ensureNodeScope()
|
|
228
|
+
if (!getNodeScopeWire()) throw new Error('p2p: attachReputationSyncWire requires node scope wire')
|
|
229
|
+
const dispose = attachNodeScopeFeature('rep_sync', wire => {
|
|
230
|
+
const offs = [
|
|
231
|
+
wire.on('rep_sync_req', (payload, peerId) => {
|
|
232
|
+
const requester = normalizeHex64(peerId)
|
|
233
|
+
if (!requester || !getReputationExportAllowlist().includes(requester)) return
|
|
234
|
+
try {
|
|
235
|
+
wire.send('rep_sync_res', {
|
|
236
|
+
requestId: payload?.requestId,
|
|
237
|
+
...exportScoreTable(),
|
|
238
|
+
}, peerId)
|
|
239
|
+
}
|
|
240
|
+
catch { /* disconnected */ }
|
|
241
|
+
}),
|
|
242
|
+
wire.on('rep_sync_res', (payload, peerId) => {
|
|
243
|
+
const requestId = String(payload?.requestId || '')
|
|
244
|
+
const pending = pendingPulls.get(requestId)
|
|
245
|
+
if (!pending) return
|
|
246
|
+
if (normalizeHex64(peerId) !== pending.donor) return
|
|
247
|
+
clearTimeout(pending.timer)
|
|
248
|
+
pendingPulls.delete(requestId)
|
|
249
|
+
pending.resolve(payload)
|
|
250
|
+
}),
|
|
251
|
+
]
|
|
252
|
+
return () => {
|
|
253
|
+
for (const off of offs)
|
|
254
|
+
try { off?.() } catch { /* ignore */ }
|
|
255
|
+
}
|
|
256
|
+
})
|
|
257
|
+
syncWireDisposers.add(dispose)
|
|
258
|
+
return () => {
|
|
259
|
+
if (!syncWireDisposers.delete(dispose)) return
|
|
260
|
+
dispose()
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* 卸掉信誉同步 wire(强制清掉全部 ref)。
|
|
266
|
+
* @returns {void}
|
|
267
|
+
*/
|
|
268
|
+
export function detachReputationSyncWire() {
|
|
269
|
+
for (const dispose of [...syncWireDisposers]) {
|
|
270
|
+
syncWireDisposers.delete(dispose)
|
|
271
|
+
try { dispose() } catch { /* ignore */ }
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/**
|
|
276
|
+
* 从 donor 拉取信誉表 JSON;不落盘。应用需自行 `setReputationTable`。
|
|
277
|
+
* @param {string} nodeHash - donor 节点 64-hex hash
|
|
278
|
+
* @returns {Promise<object>} donor 返回的信誉表
|
|
279
|
+
*/
|
|
280
|
+
export async function pullReputationFromNode(nodeHash) {
|
|
281
|
+
const donor = normalizeHex64(nodeHash)
|
|
282
|
+
if (!donor || !isHex64(donor)) throw new Error('p2p: pullReputationFromNode requires valid nodeHash')
|
|
283
|
+
if (!getTrustSyncDonors().includes(donor))
|
|
284
|
+
throw new Error('p2p: node not in trustSyncDonors')
|
|
285
|
+
attachReputationSyncWire()
|
|
286
|
+
const requestId = randomUUID()
|
|
287
|
+
const resultPromise = new Promise((resolve, reject) => {
|
|
288
|
+
const timer = setTimeout(() => {
|
|
289
|
+
pendingPulls.delete(requestId)
|
|
290
|
+
reject(new Error('p2p: rep_sync timeout'))
|
|
291
|
+
}, pullTimeoutMs)
|
|
292
|
+
pendingPulls.set(requestId, { resolve, reject, timer, donor })
|
|
293
|
+
})
|
|
294
|
+
const ok = await sendToNodeLink(donor, {
|
|
295
|
+
scope: 'node',
|
|
296
|
+
action: 'rep_sync_req',
|
|
297
|
+
payload: { requestId },
|
|
298
|
+
})
|
|
299
|
+
if (!ok) {
|
|
300
|
+
const pending = pendingPulls.get(requestId)
|
|
301
|
+
if (pending) {
|
|
302
|
+
clearTimeout(pending.timer)
|
|
303
|
+
pendingPulls.delete(requestId)
|
|
304
|
+
}
|
|
305
|
+
throw new Error('p2p: rep_sync_req send failed')
|
|
306
|
+
}
|
|
307
|
+
return await resultPromise
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* @returns {void}
|
|
312
|
+
*/
|
|
313
|
+
export function resetReputationSyncForTests() {
|
|
314
|
+
syncConfig = null
|
|
315
|
+
detachReputationSyncWire()
|
|
316
|
+
pendingPulls.clear()
|
|
317
|
+
pullTimeoutMs = 8000
|
|
318
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { getNodeTransportSettings, saveNodeTransportSettings } from './identity.mjs'
|
|
2
|
+
|
|
3
|
+
/** @typedef {'default' | 'low'} RoutingProfile */
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* @param {RoutingProfile} profile - `default` 或 `low`(省电)
|
|
7
|
+
* @returns {RoutingProfile} 写入后的当前 profile
|
|
8
|
+
*/
|
|
9
|
+
export function setRoutingProfile(profile) {
|
|
10
|
+
if (profile !== 'default' && profile !== 'low')
|
|
11
|
+
throw new Error('p2p: setRoutingProfile expects default|low')
|
|
12
|
+
saveNodeTransportSettings({ batterySaver: profile === 'low' })
|
|
13
|
+
return getRoutingProfile()
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @returns {RoutingProfile} 当前路由 profile
|
|
18
|
+
*/
|
|
19
|
+
export function getRoutingProfile() {
|
|
20
|
+
return getNodeTransportSettings().batterySaver ? 'low' : 'default'
|
|
21
|
+
}
|