@optimystic/db-p2p 0.13.5 → 0.14.1

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 (342) hide show
  1. package/README.md +6 -6
  2. package/dist/src/cluster/block-transfer-service.d.ts +67 -8
  3. package/dist/src/cluster/block-transfer-service.d.ts.map +1 -1
  4. package/dist/src/cluster/block-transfer-service.js +101 -62
  5. package/dist/src/cluster/block-transfer-service.js.map +1 -1
  6. package/dist/src/cluster/client.d.ts +18 -1
  7. package/dist/src/cluster/client.d.ts.map +1 -1
  8. package/dist/src/cluster/client.js +55 -39
  9. package/dist/src/cluster/client.js.map +1 -1
  10. package/dist/src/cluster/cluster-error.d.ts +38 -0
  11. package/dist/src/cluster/cluster-error.d.ts.map +1 -0
  12. package/dist/src/cluster/cluster-error.js +51 -0
  13. package/dist/src/cluster/cluster-error.js.map +1 -0
  14. package/dist/src/cluster/cluster-repo.d.ts +135 -3
  15. package/dist/src/cluster/cluster-repo.d.ts.map +1 -1
  16. package/dist/src/cluster/cluster-repo.js +333 -58
  17. package/dist/src/cluster/cluster-repo.js.map +1 -1
  18. package/dist/src/cluster/commit-cert.d.ts +63 -0
  19. package/dist/src/cluster/commit-cert.d.ts.map +1 -0
  20. package/dist/src/cluster/commit-cert.js +108 -0
  21. package/dist/src/cluster/commit-cert.js.map +1 -0
  22. package/dist/src/cluster/service.d.ts +46 -11
  23. package/dist/src/cluster/service.d.ts.map +1 -1
  24. package/dist/src/cluster/service.js +97 -33
  25. package/dist/src/cluster/service.js.map +1 -1
  26. package/dist/src/cluster/spread-on-churn.d.ts +13 -0
  27. package/dist/src/cluster/spread-on-churn.d.ts.map +1 -1
  28. package/dist/src/cluster/spread-on-churn.js +34 -4
  29. package/dist/src/cluster/spread-on-churn.js.map +1 -1
  30. package/dist/src/cohort-topic/bootstrap-evidence-builder.d.ts +59 -0
  31. package/dist/src/cohort-topic/bootstrap-evidence-builder.d.ts.map +1 -0
  32. package/dist/src/cohort-topic/bootstrap-evidence-builder.js +79 -0
  33. package/dist/src/cohort-topic/bootstrap-evidence-builder.js.map +1 -0
  34. package/dist/src/cohort-topic/bootstrap-evidence-verifiers.d.ts +81 -0
  35. package/dist/src/cohort-topic/bootstrap-evidence-verifiers.d.ts.map +1 -0
  36. package/dist/src/cohort-topic/bootstrap-evidence-verifiers.js +93 -0
  37. package/dist/src/cohort-topic/bootstrap-evidence-verifiers.js.map +1 -0
  38. package/dist/src/cohort-topic/bootstrap-parent-reference.d.ts +108 -0
  39. package/dist/src/cohort-topic/bootstrap-parent-reference.d.ts.map +1 -0
  40. package/dist/src/cohort-topic/bootstrap-parent-reference.js +108 -0
  41. package/dist/src/cohort-topic/bootstrap-parent-reference.js.map +1 -0
  42. package/dist/src/cohort-topic/change-bridge.d.ts +65 -0
  43. package/dist/src/cohort-topic/change-bridge.d.ts.map +1 -0
  44. package/dist/src/cohort-topic/change-bridge.js +76 -0
  45. package/dist/src/cohort-topic/change-bridge.js.map +1 -0
  46. package/dist/src/cohort-topic/cohort-gossip-driver.d.ts +74 -0
  47. package/dist/src/cohort-topic/cohort-gossip-driver.d.ts.map +1 -0
  48. package/dist/src/cohort-topic/cohort-gossip-driver.js +87 -0
  49. package/dist/src/cohort-topic/cohort-gossip-driver.js.map +1 -0
  50. package/dist/src/cohort-topic/cohort-gossip-transport.d.ts +42 -0
  51. package/dist/src/cohort-topic/cohort-gossip-transport.d.ts.map +1 -0
  52. package/dist/src/cohort-topic/cohort-gossip-transport.js +57 -0
  53. package/dist/src/cohort-topic/cohort-gossip-transport.js.map +1 -0
  54. package/dist/src/cohort-topic/fret-trust-anchor.d.ts +100 -0
  55. package/dist/src/cohort-topic/fret-trust-anchor.d.ts.map +1 -0
  56. package/dist/src/cohort-topic/fret-trust-anchor.js +115 -0
  57. package/dist/src/cohort-topic/fret-trust-anchor.js.map +1 -0
  58. package/dist/src/cohort-topic/host.d.ts +573 -0
  59. package/dist/src/cohort-topic/host.d.ts.map +1 -0
  60. package/dist/src/cohort-topic/host.js +1460 -0
  61. package/dist/src/cohort-topic/host.js.map +1 -0
  62. package/dist/src/cohort-topic/index.d.ts +14 -0
  63. package/dist/src/cohort-topic/index.d.ts.map +1 -0
  64. package/dist/src/cohort-topic/index.js +14 -0
  65. package/dist/src/cohort-topic/index.js.map +1 -0
  66. package/dist/src/cohort-topic/membership-publish-sink.d.ts +14 -0
  67. package/dist/src/cohort-topic/membership-publish-sink.d.ts.map +1 -0
  68. package/dist/src/cohort-topic/membership-publish-sink.js +17 -0
  69. package/dist/src/cohort-topic/membership-publish-sink.js.map +1 -0
  70. package/dist/src/cohort-topic/membership-source.d.ts +36 -0
  71. package/dist/src/cohort-topic/membership-source.d.ts.map +1 -0
  72. package/dist/src/cohort-topic/membership-source.js +58 -0
  73. package/dist/src/cohort-topic/membership-source.js.map +1 -0
  74. package/dist/src/cohort-topic/peer-codec.d.ts +18 -0
  75. package/dist/src/cohort-topic/peer-codec.d.ts.map +1 -0
  76. package/dist/src/cohort-topic/peer-codec.js +26 -0
  77. package/dist/src/cohort-topic/peer-codec.js.map +1 -0
  78. package/dist/src/cohort-topic/peer-sig.d.ts +52 -0
  79. package/dist/src/cohort-topic/peer-sig.d.ts.map +1 -0
  80. package/dist/src/cohort-topic/peer-sig.js +83 -0
  81. package/dist/src/cohort-topic/peer-sig.js.map +1 -0
  82. package/dist/src/cohort-topic/protocols.d.ts +49 -0
  83. package/dist/src/cohort-topic/protocols.d.ts.map +1 -0
  84. package/dist/src/cohort-topic/protocols.js +58 -0
  85. package/dist/src/cohort-topic/protocols.js.map +1 -0
  86. package/dist/src/cohort-topic/reactivity-membership-gate.d.ts +49 -0
  87. package/dist/src/cohort-topic/reactivity-membership-gate.d.ts.map +1 -0
  88. package/dist/src/cohort-topic/reactivity-membership-gate.js +42 -0
  89. package/dist/src/cohort-topic/reactivity-membership-gate.js.map +1 -0
  90. package/dist/src/cohort-topic/size-estimator.d.ts +16 -0
  91. package/dist/src/cohort-topic/size-estimator.d.ts.map +1 -0
  92. package/dist/src/cohort-topic/size-estimator.js +16 -0
  93. package/dist/src/cohort-topic/size-estimator.js.map +1 -0
  94. package/dist/src/cohort-topic/stream-util.d.ts +19 -0
  95. package/dist/src/cohort-topic/stream-util.d.ts.map +1 -0
  96. package/dist/src/cohort-topic/stream-util.js +76 -0
  97. package/dist/src/cohort-topic/stream-util.js.map +1 -0
  98. package/dist/src/cohort-topic/threshold-crypto.d.ts +94 -0
  99. package/dist/src/cohort-topic/threshold-crypto.d.ts.map +1 -0
  100. package/dist/src/cohort-topic/threshold-crypto.js +178 -0
  101. package/dist/src/cohort-topic/threshold-crypto.js.map +1 -0
  102. package/dist/src/cohort-topic/topic-router.d.ts +41 -0
  103. package/dist/src/cohort-topic/topic-router.d.ts.map +1 -0
  104. package/dist/src/cohort-topic/topic-router.js +63 -0
  105. package/dist/src/cohort-topic/topic-router.js.map +1 -0
  106. package/dist/src/dispute/cascade.d.ts +179 -0
  107. package/dist/src/dispute/cascade.d.ts.map +1 -0
  108. package/dist/src/dispute/cascade.js +315 -0
  109. package/dist/src/dispute/cascade.js.map +1 -0
  110. package/dist/src/dispute/client.d.ts +2 -1
  111. package/dist/src/dispute/client.d.ts.map +1 -1
  112. package/dist/src/dispute/client.js +12 -3
  113. package/dist/src/dispute/client.js.map +1 -1
  114. package/dist/src/dispute/dispute-service.d.ts +41 -1
  115. package/dist/src/dispute/dispute-service.d.ts.map +1 -1
  116. package/dist/src/dispute/dispute-service.js +147 -21
  117. package/dist/src/dispute/dispute-service.js.map +1 -1
  118. package/dist/src/dispute/index.d.ts +2 -0
  119. package/dist/src/dispute/index.d.ts.map +1 -1
  120. package/dist/src/dispute/index.js +2 -0
  121. package/dist/src/dispute/index.js.map +1 -1
  122. package/dist/src/dispute/invalidation.d.ts +266 -0
  123. package/dist/src/dispute/invalidation.d.ts.map +1 -0
  124. package/dist/src/dispute/invalidation.js +405 -0
  125. package/dist/src/dispute/invalidation.js.map +1 -0
  126. package/dist/src/dispute/types.d.ts +14 -0
  127. package/dist/src/dispute/types.d.ts.map +1 -1
  128. package/dist/src/dispute/types.js.map +1 -1
  129. package/dist/src/index.d.ts +4 -0
  130. package/dist/src/index.d.ts.map +1 -1
  131. package/dist/src/index.js +4 -0
  132. package/dist/src/index.js.map +1 -1
  133. package/dist/src/libp2p-key-network.d.ts +7 -0
  134. package/dist/src/libp2p-key-network.d.ts.map +1 -1
  135. package/dist/src/libp2p-key-network.js +49 -5
  136. package/dist/src/libp2p-key-network.js.map +1 -1
  137. package/dist/src/libp2p-node-base.d.ts +45 -3
  138. package/dist/src/libp2p-node-base.d.ts.map +1 -1
  139. package/dist/src/libp2p-node-base.js +522 -5
  140. package/dist/src/libp2p-node-base.js.map +1 -1
  141. package/dist/src/matchmaking/aggregate-counts.d.ts +67 -0
  142. package/dist/src/matchmaking/aggregate-counts.d.ts.map +1 -0
  143. package/dist/src/matchmaking/aggregate-counts.js +60 -0
  144. package/dist/src/matchmaking/aggregate-counts.js.map +1 -0
  145. package/dist/src/matchmaking/index.d.ts +20 -0
  146. package/dist/src/matchmaking/index.d.ts.map +1 -0
  147. package/dist/src/matchmaking/index.js +20 -0
  148. package/dist/src/matchmaking/index.js.map +1 -0
  149. package/dist/src/matchmaking/module.d.ts +181 -0
  150. package/dist/src/matchmaking/module.d.ts.map +1 -0
  151. package/dist/src/matchmaking/module.js +221 -0
  152. package/dist/src/matchmaking/module.js.map +1 -0
  153. package/dist/src/matchmaking/protocols.d.ts +37 -0
  154. package/dist/src/matchmaking/protocols.d.ts.map +1 -0
  155. package/dist/src/matchmaking/protocols.js +42 -0
  156. package/dist/src/matchmaking/protocols.js.map +1 -0
  157. package/dist/src/matchmaking/provider-manager.d.ts +52 -0
  158. package/dist/src/matchmaking/provider-manager.d.ts.map +1 -0
  159. package/dist/src/matchmaking/provider-manager.js +74 -0
  160. package/dist/src/matchmaking/provider-manager.js.map +1 -0
  161. package/dist/src/matchmaking/query-handler.d.ts +34 -0
  162. package/dist/src/matchmaking/query-handler.d.ts.map +1 -0
  163. package/dist/src/matchmaking/query-handler.js +62 -0
  164. package/dist/src/matchmaking/query-handler.js.map +1 -0
  165. package/dist/src/matchmaking/query-transport.d.ts +180 -0
  166. package/dist/src/matchmaking/query-transport.d.ts.map +1 -0
  167. package/dist/src/matchmaking/query-transport.js +315 -0
  168. package/dist/src/matchmaking/query-transport.js.map +1 -0
  169. package/dist/src/matchmaking/seeker-manager.d.ts +39 -0
  170. package/dist/src/matchmaking/seeker-manager.d.ts.map +1 -0
  171. package/dist/src/matchmaking/seeker-manager.js +49 -0
  172. package/dist/src/matchmaking/seeker-manager.js.map +1 -0
  173. package/dist/src/matchmaking/seeker-walk-client.d.ts +127 -0
  174. package/dist/src/matchmaking/seeker-walk-client.d.ts.map +1 -0
  175. package/dist/src/matchmaking/seeker-walk-client.js +189 -0
  176. package/dist/src/matchmaking/seeker-walk-client.js.map +1 -0
  177. package/dist/src/matchmaking/traffic-validation.d.ts +128 -0
  178. package/dist/src/matchmaking/traffic-validation.d.ts.map +1 -0
  179. package/dist/src/matchmaking/traffic-validation.js +105 -0
  180. package/dist/src/matchmaking/traffic-validation.js.map +1 -0
  181. package/dist/src/network/network-manager-service.d.ts +4 -2
  182. package/dist/src/network/network-manager-service.d.ts.map +1 -1
  183. package/dist/src/network/network-manager-service.js +9 -3
  184. package/dist/src/network/network-manager-service.js.map +1 -1
  185. package/dist/src/protocol-client.d.ts +13 -0
  186. package/dist/src/protocol-client.d.ts.map +1 -1
  187. package/dist/src/protocol-client.js +74 -2
  188. package/dist/src/protocol-client.js.map +1 -1
  189. package/dist/src/reactivity/forwarder-host.d.ts +198 -0
  190. package/dist/src/reactivity/forwarder-host.d.ts.map +1 -0
  191. package/dist/src/reactivity/forwarder-host.js +355 -0
  192. package/dist/src/reactivity/forwarder-host.js.map +1 -0
  193. package/dist/src/reactivity/index.d.ts +19 -0
  194. package/dist/src/reactivity/index.d.ts.map +1 -0
  195. package/dist/src/reactivity/index.js +19 -0
  196. package/dist/src/reactivity/index.js.map +1 -0
  197. package/dist/src/reactivity/notify-transport.d.ts +70 -0
  198. package/dist/src/reactivity/notify-transport.d.ts.map +1 -0
  199. package/dist/src/reactivity/notify-transport.js +111 -0
  200. package/dist/src/reactivity/notify-transport.js.map +1 -0
  201. package/dist/src/reactivity/origination-manager.d.ts +110 -0
  202. package/dist/src/reactivity/origination-manager.d.ts.map +1 -0
  203. package/dist/src/reactivity/origination-manager.js +129 -0
  204. package/dist/src/reactivity/origination-manager.js.map +1 -0
  205. package/dist/src/reactivity/protocols.d.ts +43 -0
  206. package/dist/src/reactivity/protocols.d.ts.map +1 -0
  207. package/dist/src/reactivity/protocols.js +50 -0
  208. package/dist/src/reactivity/protocols.js.map +1 -0
  209. package/dist/src/reactivity/push-state-gossip.d.ts +132 -0
  210. package/dist/src/reactivity/push-state-gossip.d.ts.map +1 -0
  211. package/dist/src/reactivity/push-state-gossip.js +231 -0
  212. package/dist/src/reactivity/push-state-gossip.js.map +1 -0
  213. package/dist/src/reactivity/recover-transport.d.ts +167 -0
  214. package/dist/src/reactivity/recover-transport.d.ts.map +1 -0
  215. package/dist/src/reactivity/recover-transport.js +308 -0
  216. package/dist/src/reactivity/recover-transport.js.map +1 -0
  217. package/dist/src/reactivity/rotation-rereg-scheduler.d.ts +142 -0
  218. package/dist/src/reactivity/rotation-rereg-scheduler.d.ts.map +1 -0
  219. package/dist/src/reactivity/rotation-rereg-scheduler.js +223 -0
  220. package/dist/src/reactivity/rotation-rereg-scheduler.js.map +1 -0
  221. package/dist/src/reactivity/subscriber-registry.d.ts +47 -0
  222. package/dist/src/reactivity/subscriber-registry.d.ts.map +1 -0
  223. package/dist/src/reactivity/subscriber-registry.js +87 -0
  224. package/dist/src/reactivity/subscriber-registry.js.map +1 -0
  225. package/dist/src/reactivity/subscription-manager.d.ts +221 -0
  226. package/dist/src/reactivity/subscription-manager.d.ts.map +1 -0
  227. package/dist/src/reactivity/subscription-manager.js +302 -0
  228. package/dist/src/reactivity/subscription-manager.js.map +1 -0
  229. package/dist/src/reactivity/topic-bytes.d.ts +32 -0
  230. package/dist/src/reactivity/topic-bytes.d.ts.map +1 -0
  231. package/dist/src/reactivity/topic-bytes.js +34 -0
  232. package/dist/src/reactivity/topic-bytes.js.map +1 -0
  233. package/dist/src/repo/client.d.ts.map +1 -1
  234. package/dist/src/repo/client.js +51 -23
  235. package/dist/src/repo/client.js.map +1 -1
  236. package/dist/src/repo/service.d.ts +46 -1
  237. package/dist/src/repo/service.d.ts.map +1 -1
  238. package/dist/src/repo/service.js +79 -45
  239. package/dist/src/repo/service.js.map +1 -1
  240. package/dist/src/rpc-deadline.d.ts +37 -0
  241. package/dist/src/rpc-deadline.d.ts.map +1 -0
  242. package/dist/src/rpc-deadline.js +31 -0
  243. package/dist/src/rpc-deadline.js.map +1 -0
  244. package/dist/src/storage/block-storage.d.ts +2 -0
  245. package/dist/src/storage/block-storage.d.ts.map +1 -1
  246. package/dist/src/storage/block-storage.js +95 -2
  247. package/dist/src/storage/block-storage.js.map +1 -1
  248. package/dist/src/storage/i-block-storage.d.ts +25 -0
  249. package/dist/src/storage/i-block-storage.d.ts.map +1 -1
  250. package/dist/src/storage/storage-repo.d.ts +53 -2
  251. package/dist/src/storage/storage-repo.d.ts.map +1 -1
  252. package/dist/src/storage/storage-repo.js +193 -9
  253. package/dist/src/storage/storage-repo.js.map +1 -1
  254. package/dist/src/sync/client.d.ts +4 -1
  255. package/dist/src/sync/client.d.ts.map +1 -1
  256. package/dist/src/sync/client.js +5 -2
  257. package/dist/src/sync/client.js.map +1 -1
  258. package/dist/src/testing/cohort-topic-mesh-harness.d.ts +219 -0
  259. package/dist/src/testing/cohort-topic-mesh-harness.d.ts.map +1 -0
  260. package/dist/src/testing/cohort-topic-mesh-harness.js +467 -0
  261. package/dist/src/testing/cohort-topic-mesh-harness.js.map +1 -0
  262. package/dist/src/testing/matchmaking-mesh-harness.d.ts +187 -0
  263. package/dist/src/testing/matchmaking-mesh-harness.d.ts.map +1 -0
  264. package/dist/src/testing/matchmaking-mesh-harness.js +358 -0
  265. package/dist/src/testing/matchmaking-mesh-harness.js.map +1 -0
  266. package/dist/src/testing/mesh-harness.d.ts.map +1 -1
  267. package/dist/src/testing/mesh-harness.js +23 -1
  268. package/dist/src/testing/mesh-harness.js.map +1 -1
  269. package/dist/src/testing/reactivity-mesh-harness.d.ts +298 -0
  270. package/dist/src/testing/reactivity-mesh-harness.d.ts.map +1 -0
  271. package/dist/src/testing/reactivity-mesh-harness.js +663 -0
  272. package/dist/src/testing/reactivity-mesh-harness.js.map +1 -0
  273. package/package.json +7 -4
  274. package/src/cluster/block-transfer-service.ts +133 -68
  275. package/src/cluster/client.ts +64 -45
  276. package/src/cluster/cluster-error.ts +64 -0
  277. package/src/cluster/cluster-repo.ts +405 -55
  278. package/src/cluster/commit-cert.ts +139 -0
  279. package/src/cluster/service.ts +116 -44
  280. package/src/cluster/spread-on-churn.ts +328 -285
  281. package/src/cohort-topic/bootstrap-evidence-builder.ts +122 -0
  282. package/src/cohort-topic/bootstrap-evidence-verifiers.ts +132 -0
  283. package/src/cohort-topic/bootstrap-parent-reference.ts +159 -0
  284. package/src/cohort-topic/change-bridge.ts +109 -0
  285. package/src/cohort-topic/cohort-gossip-driver.ts +144 -0
  286. package/src/cohort-topic/cohort-gossip-transport.ts +74 -0
  287. package/src/cohort-topic/fret-trust-anchor.ts +153 -0
  288. package/src/cohort-topic/host.ts +2175 -0
  289. package/src/cohort-topic/index.ts +13 -0
  290. package/src/cohort-topic/membership-publish-sink.ts +20 -0
  291. package/src/cohort-topic/membership-source.ts +68 -0
  292. package/src/cohort-topic/peer-codec.ts +31 -0
  293. package/src/cohort-topic/peer-sig.ts +86 -0
  294. package/src/cohort-topic/protocols.ts +71 -0
  295. package/src/cohort-topic/reactivity-membership-gate.ts +77 -0
  296. package/src/cohort-topic/size-estimator.ts +16 -0
  297. package/src/cohort-topic/stream-util.ts +87 -0
  298. package/src/cohort-topic/threshold-crypto.ts +239 -0
  299. package/src/cohort-topic/topic-router.ts +77 -0
  300. package/src/dispute/cascade.ts +517 -0
  301. package/src/dispute/client.ts +12 -2
  302. package/src/dispute/dispute-service.ts +171 -24
  303. package/src/dispute/index.ts +42 -0
  304. package/src/dispute/invalidation.ts +587 -0
  305. package/src/dispute/types.ts +14 -0
  306. package/src/index.ts +4 -0
  307. package/src/libp2p-key-network.ts +49 -6
  308. package/src/libp2p-node-base.ts +620 -12
  309. package/src/matchmaking/aggregate-counts.ts +104 -0
  310. package/src/matchmaking/index.ts +20 -0
  311. package/src/matchmaking/module.ts +363 -0
  312. package/src/matchmaking/protocols.ts +51 -0
  313. package/src/matchmaking/provider-manager.ts +95 -0
  314. package/src/matchmaking/query-handler.ts +88 -0
  315. package/src/matchmaking/query-transport.ts +483 -0
  316. package/src/matchmaking/seeker-manager.ts +64 -0
  317. package/src/matchmaking/seeker-walk-client.ts +293 -0
  318. package/src/matchmaking/traffic-validation.ts +195 -0
  319. package/src/network/network-manager-service.ts +9 -2
  320. package/src/protocol-client.ts +64 -3
  321. package/src/reactivity/forwarder-host.ts +438 -0
  322. package/src/reactivity/index.ts +19 -0
  323. package/src/reactivity/notify-transport.ts +144 -0
  324. package/src/reactivity/origination-manager.ts +192 -0
  325. package/src/reactivity/protocols.ts +61 -0
  326. package/src/reactivity/push-state-gossip.ts +291 -0
  327. package/src/reactivity/recover-transport.ts +408 -0
  328. package/src/reactivity/rotation-rereg-scheduler.ts +256 -0
  329. package/src/reactivity/subscriber-registry.ts +96 -0
  330. package/src/reactivity/subscription-manager.ts +450 -0
  331. package/src/reactivity/topic-bytes.ts +37 -0
  332. package/src/repo/client.ts +54 -23
  333. package/src/repo/service.ts +90 -42
  334. package/src/rpc-deadline.ts +45 -0
  335. package/src/storage/block-storage.ts +106 -3
  336. package/src/storage/i-block-storage.ts +27 -0
  337. package/src/storage/storage-repo.ts +209 -13
  338. package/src/sync/client.ts +5 -2
  339. package/src/testing/cohort-topic-mesh-harness.ts +613 -0
  340. package/src/testing/matchmaking-mesh-harness.ts +475 -0
  341. package/src/testing/mesh-harness.ts +22 -2
  342. package/src/testing/reactivity-mesh-harness.ts +922 -0
@@ -0,0 +1,587 @@
1
+ import { peerIdFromString } from '@libp2p/peer-id';
2
+ import { fromString as uint8ArrayFromString } from 'uint8arrays/from-string';
3
+ import type {
4
+ ActionId, BlockId, IBlock, Log,
5
+ DisputeResolutionProof, ArbitrationVoteProof, RevertedBlock,
6
+ } from '@optimystic/db-core';
7
+ import { applyTransform, hashString } from '@optimystic/db-core';
8
+ import type { IBlockStorage } from '../storage/i-block-storage.js';
9
+ import type { DisputeResolution, ArbitrationVote } from './types.js';
10
+ import { createLogger } from '../logger.js';
11
+
12
+ const log = createLogger('invalidation');
13
+
14
+ /**
15
+ * Accepted arbitration-vote wire-format version. The v3 signed payload binds each vote to BOTH the
16
+ * specific reversed transaction (`targetHash`, #2) and the legitimately-selected arbitrator set
17
+ * (`setHash`, #1); v1/v2 (un-set-bound) votes are rejected, never accepted-by-default.
18
+ */
19
+ export const VOTE_VERSION = 'v3' as const;
20
+
21
+ /**
22
+ * The transaction an invalidation certificate's votes are bound to — the committed action being
23
+ * reversed and the blocks it wrote. Threaded into {@link verifyInvalidationCertificate} so a genuine
24
+ * `challenger-wins` proof for transaction X cannot be replayed to revert an unrelated transaction Y:
25
+ * the arbitrators signed over X's `targetHash`, so verifying against any other target makes every
26
+ * signature fail → 0 decisive votes → reject.
27
+ */
28
+ export type CertificateTarget = {
29
+ readonly invalidatedActionId: ActionId;
30
+ readonly blockIds: ReadonlyArray<BlockId>;
31
+ };
32
+
33
+ /**
34
+ * Binds a vote to its reversal target: `hashString(`${messageHash}|${invalidatedActionId}|${sortedBlockIds}`)`.
35
+ * `blockIds` are lexically sorted so the binding is independent of the order a member happens to list
36
+ * them, and {@link hashString} is the same db-core helper the compensating-state computation uses, so
37
+ * every member recomputes an identical `targetHash`.
38
+ */
39
+ export async function computeTargetHash(messageHash: string, target: CertificateTarget): Promise<string> {
40
+ const sortedBlockIds = [...target.blockIds].sort();
41
+ return await hashString(`${messageHash}|${target.invalidatedActionId}|${sortedBlockIds.join(',')}`);
42
+ }
43
+
44
+ /**
45
+ * Digest of the legitimately-selected arbitrator set (#1) — `hashString(sortedArbitratorSet.join(','))`.
46
+ * Peer-ids are lexically sorted so the digest is independent of the order any party happens to list the
47
+ * set in, and every member (arbitrators signing votes, the challenger signing the set, the verifier)
48
+ * recomputes an identical `setHash`.
49
+ */
50
+ export async function computeArbitratorSetHash(arbitratorSet: ReadonlyArray<string>): Promise<string> {
51
+ return await hashString([...arbitratorSet].sort().join(','));
52
+ }
53
+
54
+ /**
55
+ * The exact bytes an arbitrator signs for a v3 vote — `utf8(`v3:${disputeId}:${vote}:${computedHash}:${targetHash}:${setHash}`)`.
56
+ * Shared by the origination path ({@link makeVote in dispute-service}) and {@link verifyVoteSignature}
57
+ * so the signed and verified preimages can never drift.
58
+ */
59
+ export function voteSigningPayload(disputeId: string, vote: string, computedHash: string, targetHash: string, setHash: string): Uint8Array {
60
+ return new TextEncoder().encode(`${VOTE_VERSION}:${disputeId}:${vote}:${computedHash}:${targetHash}:${setHash}`);
61
+ }
62
+
63
+ /**
64
+ * The exact bytes the **challenger** signs to bind `(disputeId, target, arbitratorSet)` —
65
+ * `utf8(`v3set:${disputeId}:${targetHash}:${setHash}`)`. Verified against the challenger's embedded key
66
+ * ({@link DisputeResolutionProof.challengerPeerId}); shared with the origination path so it can never drift.
67
+ * The version marker is derived from {@link VOTE_VERSION} (currently `v3` → `v3set`) so a future format
68
+ * bump moves the vote and set preimages together — a proof is wholly one wire version, never a mix.
69
+ */
70
+ export function arbitratorSetSigningPayload(disputeId: string, targetHash: string, setHash: string): Uint8Array {
71
+ return new TextEncoder().encode(`${VOTE_VERSION}set:${disputeId}:${targetHash}:${setHash}`);
72
+ }
73
+
74
+ /**
75
+ * Context handed to an {@link ArbitratorSetRecompute} capability: everything it needs to re-derive the
76
+ * legitimate arbitrator set from the verifying member's own topology and judge the carried set against it.
77
+ */
78
+ export type ArbitratorSetRecomputeContext = {
79
+ readonly disputeId: string;
80
+ readonly messageHash: string;
81
+ readonly invalidatedActionId: ActionId;
82
+ readonly blockIds: ReadonlyArray<BlockId>;
83
+ /** The carried set being judged (peer-id strings). */
84
+ readonly arbitratorSet: ReadonlyArray<string>;
85
+ };
86
+
87
+ /**
88
+ * Verdict from an {@link ArbitratorSetRecompute}:
89
+ * - `{ feasible: false }` — the member could not reconstruct the historical selection (late-joiner,
90
+ * churned DHT view); the verifier falls through to the degradation posture (layer-1 accept + log).
91
+ * - `{ feasible: true, legitimate }` — it recomputed the eligible set and judged whether the carried
92
+ * `arbitratorSet` matches it (within whatever churn tolerance the capability applies).
93
+ */
94
+ export type ArbitratorSetVerdict =
95
+ | { readonly feasible: false }
96
+ | { readonly feasible: true; readonly legitimate: boolean };
97
+
98
+ /**
99
+ * Injected **layer-2** capability: re-derives the legitimately-selected arbitrator set from the verifying
100
+ * member's topology view (it has `peerNetwork` / FRET routing) and judges the carried set. Supplied by
101
+ * callers that hold a network (e.g. `ClusterMember.applyConsensusInvalidation`); the pure
102
+ * {@link verifyInvalidationCertificate} stays usable without it (layer-1 + degradation). Closing the
103
+ * fully-malicious-challenger vector requires this layer (or the layer-3 trust anchor).
104
+ */
105
+ export type ArbitratorSetRecompute = (ctx: ArbitratorSetRecomputeContext) => Promise<ArbitratorSetVerdict>;
106
+
107
+ /** Reported when a certificate is accepted on layer-1 alone — see {@link VerifyCertificateOptions.onUnanchored}. */
108
+ export type UnanchoredAcceptanceInfo = {
109
+ readonly disputeId: string;
110
+ readonly arbitratorSet: ReadonlyArray<string>;
111
+ /** Why the stronger layers did not apply. */
112
+ readonly reason: 'no-recompute-capability' | 'recompute-infeasible';
113
+ };
114
+
115
+ /** Optional capabilities a caller threads into {@link verifyInvalidationCertificate} when it has a network. */
116
+ export type VerifyCertificateOptions = {
117
+ /** Layer-2 recompute capability; omitted → pure layer-1 verification with the documented degradation. */
118
+ readonly recomputeArbitratorSet?: ArbitratorSetRecompute;
119
+ /**
120
+ * Invoked when the certificate is accepted on the challenger-bound set + membership + dedup ALONE —
121
+ * the interim posture when neither recompute (layer 2) nor a trust anchor (layer 3) resolved the set.
122
+ * Lets a caller surface "applied an invalidation it could not fully anchor" alongside the internal log.
123
+ */
124
+ readonly onUnanchored?: (info: UnanchoredAcceptanceInfo) => void;
125
+ };
126
+
127
+ /**
128
+ * Marks a `reverted` block whose as-if-`T_inv`-absent state is a *deletion* (T_inv created the
129
+ * block, so there is no prior content to restore). {@link applyInvalidation} now physically removes
130
+ * such blocks (a forward tombstone via {@link IBlockStorage.saveDeletion}); this sentinel is the
131
+ * `restoredContentHash` it records for the deleted block, telling read-dependents "the observed
132
+ * content no longer exists → invalidate" (a created block can never equal "absent"). Greppable so it
133
+ * is never mistaken for a real content hash.
134
+ */
135
+ export const DELETED_BLOCK_RESTORE = 'deleted:block-creation-reverted';
136
+
137
+ // ─── DisputeResolution → DisputeResolutionProof ───
138
+
139
+ /**
140
+ * The arbitrator-set binding a proof carries (#1): the legitimately-selected set, the challenger that
141
+ * selected it, and the challenger's signature over `(disputeId, target, arbitratorSet)`. Assembled by
142
+ * the originator ({@link DisputeService.maybeInvalidate}), which holds the selected set from
143
+ * `initiateDispute` and signs it with the challenger's key.
144
+ */
145
+ export type ArbitratorSetBinding = {
146
+ readonly arbitratorSet: ReadonlyArray<string>;
147
+ readonly challengerPeerId: string;
148
+ readonly arbitratorSetSignature: string;
149
+ };
150
+
151
+ /**
152
+ * Projects a db-p2p {@link DisputeResolution} onto the db-core {@link DisputeResolutionProof} —
153
+ * the independently-verifiable subset (outcome + signed votes + arbitrator-set binding) that an
154
+ * {@link InvalidationEntry} carries. `messageHash` is the original transaction's hash (from the
155
+ * challenge), the anchor the proof pins the reversal to; `binding` carries the legitimately-selected
156
+ * arbitrator set and the challenger's signature over it (#1).
157
+ */
158
+ export function buildDisputeResolutionProof(resolution: DisputeResolution, messageHash: string, binding: ArbitratorSetBinding): DisputeResolutionProof {
159
+ return {
160
+ disputeId: resolution.disputeId,
161
+ messageHash,
162
+ outcome: resolution.outcome,
163
+ challengerPeerId: binding.challengerPeerId,
164
+ arbitratorSet: binding.arbitratorSet,
165
+ arbitratorSetSignature: binding.arbitratorSetSignature,
166
+ votes: resolution.votes.map(toVoteProof),
167
+ };
168
+ }
169
+
170
+ function toVoteProof(vote: ArbitrationVote): ArbitrationVoteProof {
171
+ return {
172
+ version: vote.version,
173
+ arbitratorPeerId: vote.arbitratorPeerId,
174
+ vote: vote.vote,
175
+ computedHash: vote.evidence.computedHash,
176
+ signature: vote.signature,
177
+ };
178
+ }
179
+
180
+ // ─── Invalidation certificate verification ───
181
+
182
+ /**
183
+ * Verifies that a {@link DisputeResolutionProof} is a valid invalidation certificate — the reversal
184
+ * analogue of the commit certificate. A member accepts an invalidation **only** if this returns true.
185
+ * Defense-in-depth, strongest-available-layer-wins:
186
+ *
187
+ * **Target binding (#2).** `target` is the transaction actually being reverted; the verifier recomputes
188
+ * `targetHash` from `proof.messageHash` + `target` and checks each vote's signature over the v3 payload
189
+ * `v3:${disputeId}:${vote}:${computedHash}:${targetHash}:${setHash}`. Because the arbitrators signed the
190
+ * *real* transaction's `targetHash`, feeding any other target (a replay against an innocent transaction)
191
+ * makes every signature fail. A vote whose version is absent/unrecognized (legacy/v1/v2) is rejected
192
+ * before counting — never accepted-by-default.
193
+ *
194
+ * **Arbitrator-set binding (#1) — layer 1 (always).** The proof carries `arbitratorSet` (the K peer-ids
195
+ * the challenger selected) and `arbitratorSetSignature` (the challenger's signature over
196
+ * `(disputeId, target, arbitratorSet)`, verified against `challengerPeerId`'s embedded key). The verifier:
197
+ * - rejects a proof missing the set / challenger fields;
198
+ * - rejects a proof whose challenger signature does not validate over the recomputed `(targetHash, setHash)`
199
+ * — so tampering with the set (adding sybils) breaks the certificate;
200
+ * - counts only votes whose `arbitratorPeerId` ∈ `arbitratorSet` (a signature-valid vote from a peer
201
+ * outside the set is dropped), and whose vote payload also commits to the same `setHash`.
202
+ * This closes the third-party-relay / originator sybil vector and binds the originator. It does NOT by
203
+ * itself stop a *fully-malicious* challenger (who legitimately holds its own key and signs a sybil set it
204
+ * minted) — that needs layer 2 or 3.
205
+ *
206
+ * **Per-arbitrator dedup (#3).** Among the in-set votes, decisive verdicts are tallied at most once per
207
+ * `arbitratorPeerId`: a repeated identical decisive vote counts once; an arbitrator with conflicting
208
+ * decisive votes (equivocation) is dropped from both sides. `inconclusive` votes are non-decisive.
209
+ *
210
+ * **Recompute — layer 2 (best effort).** When `options.recomputeArbitratorSet` is supplied (the caller
211
+ * holds a topology view), the carried set is re-derived and judged. A `{feasible:true, legitimate:false}`
212
+ * verdict rejects the certificate even though layer 1 passed — closing the malicious-challenger vector.
213
+ * `{feasible:false}` (member can't reconstruct the historical topology) falls through to degradation.
214
+ *
215
+ * **Degradation (layer 3 / none-available).** With no recompute capability (or an infeasible recompute)
216
+ * and no trust anchor yet, a layer-1-valid certificate is **accepted and logged** as not-fully-anchored
217
+ * (and `options.onUnanchored` is invoked) — never a silent accept-by-default, and never a false reject
218
+ * that would break liveness for late-joiners. This is the interim posture until the cohort-topic
219
+ * membership-cert trust-anchor chain lands (`tickets/plan/cohort-topic-membership-cert-trust-anchoring.md`),
220
+ * at which point it is upgraded to a hard gate.
221
+ */
222
+ export async function verifyInvalidationCertificate(proof: DisputeResolutionProof, target: CertificateTarget, options: VerifyCertificateOptions = {}): Promise<boolean> {
223
+ if (proof.outcome !== 'challenger-wins') {
224
+ return false;
225
+ }
226
+
227
+ // Structural: a v3 certificate must carry the arbitrator-set binding. Absent → reject (never accept a
228
+ // pre-set-binding proof by default).
229
+ if (!proof.arbitratorSet?.length || !proof.challengerPeerId || !proof.arbitratorSetSignature) {
230
+ return false;
231
+ }
232
+
233
+ const targetHash = await computeTargetHash(proof.messageHash, target);
234
+ const setHash = await computeArbitratorSetHash(proof.arbitratorSet);
235
+
236
+ // Layer 1a: challenger binds (disputeId, target, arbitratorSet). A tampered set breaks this signature.
237
+ if (!(await verifyChallengerSetSignature(proof, targetHash, setHash))) {
238
+ log('verify-reject-challenger-set-signature disputeId=%s challenger=%s', proof.disputeId, proof.challengerPeerId);
239
+ return false;
240
+ }
241
+
242
+ // Layer 1b: count only signature-valid, target+set-bound, in-set votes — deduped/equivocation-dropped.
243
+ const arbitratorSet = new Set(proof.arbitratorSet);
244
+ type Decisive = 'agree-with-challenger' | 'agree-with-majority';
245
+ const decisiveByArbitrator = new Map<string, Decisive | 'equivocated'>();
246
+ for (const vote of proof.votes) {
247
+ if (!arbitratorSet.has(vote.arbitratorPeerId)) {
248
+ continue; // not a legitimately-selected arbitrator → never counted (#1)
249
+ }
250
+ if (!(await verifyVoteSignature(proof.disputeId, vote, targetHash, setHash))) {
251
+ continue;
252
+ }
253
+ if (vote.vote !== 'agree-with-challenger' && vote.vote !== 'agree-with-majority') {
254
+ continue; // 'inconclusive' — valid but not decisive
255
+ }
256
+ const prior = decisiveByArbitrator.get(vote.arbitratorPeerId);
257
+ if (prior === undefined) {
258
+ decisiveByArbitrator.set(vote.arbitratorPeerId, vote.vote);
259
+ } else if (prior !== 'equivocated' && prior !== vote.vote) {
260
+ // Same arbitrator, conflicting decisive votes → drop entirely (do not let one peer be on both sides).
261
+ decisiveByArbitrator.set(vote.arbitratorPeerId, 'equivocated');
262
+ }
263
+ // prior === vote.vote (duplicate) or already 'equivocated': counted at most once, no change.
264
+ }
265
+
266
+ let challengerVotes = 0;
267
+ let majorityVotes = 0;
268
+ for (const decision of decisiveByArbitrator.values()) {
269
+ if (decision === 'agree-with-challenger') {
270
+ challengerVotes++;
271
+ } else if (decision === 'agree-with-majority') {
272
+ majorityVotes++;
273
+ }
274
+ }
275
+
276
+ const totalDecisive = challengerVotes + majorityVotes;
277
+ if (totalDecisive === 0) {
278
+ return false;
279
+ }
280
+ const superMajorityThreshold = Math.ceil(totalDecisive * 2 / 3);
281
+ if (challengerVotes < superMajorityThreshold) {
282
+ return false;
283
+ }
284
+
285
+ // Layer 2: re-derive the eligible set from the member's own topology when it can — closes a
286
+ // fully-malicious challenger that self-signed a sybil set that passed layer 1.
287
+ if (options.recomputeArbitratorSet) {
288
+ const verdict = await options.recomputeArbitratorSet({
289
+ disputeId: proof.disputeId,
290
+ messageHash: proof.messageHash,
291
+ invalidatedActionId: target.invalidatedActionId,
292
+ blockIds: target.blockIds,
293
+ arbitratorSet: proof.arbitratorSet,
294
+ });
295
+ if (verdict.feasible) {
296
+ if (!verdict.legitimate) {
297
+ log('verify-reject-recompute-mismatch disputeId=%s', proof.disputeId);
298
+ return false;
299
+ }
300
+ return true; // fully anchored to the recomputed topology
301
+ }
302
+ // infeasible → fall through to the documented degradation posture
303
+ return acceptUnanchored(proof, 'recompute-infeasible', options);
304
+ }
305
+
306
+ // Layer 3 / none-available: accept on layer 1 alone, but never silently — log + surface the residual.
307
+ return acceptUnanchored(proof, 'no-recompute-capability', options);
308
+ }
309
+
310
+ /**
311
+ * Accept-and-log a layer-1-valid certificate that could not be fully anchored (no recompute capability
312
+ * or an infeasible recompute, and no trust anchor yet). Documented interim posture — never a silent
313
+ * accept. Returns true.
314
+ */
315
+ function acceptUnanchored(proof: DisputeResolutionProof, reason: UnanchoredAcceptanceInfo['reason'], options: VerifyCertificateOptions): boolean {
316
+ log('verify-accept-unanchored disputeId=%s reason=%s setSize=%d', proof.disputeId, reason, proof.arbitratorSet.length);
317
+ try {
318
+ options.onUnanchored?.({ disputeId: proof.disputeId, arbitratorSet: proof.arbitratorSet, reason });
319
+ } catch (err) {
320
+ log('verify-onUnanchored-error disputeId=%s error=%o', proof.disputeId, err);
321
+ }
322
+ return true;
323
+ }
324
+
325
+ /**
326
+ * Verify the challenger's signature binding `(disputeId, target, arbitratorSet)` against the embedded
327
+ * Ed25519 key in `proof.challengerPeerId`. Closes the third-party-relay sybil vector: a relay cannot
328
+ * swap the carried set without the challenger's key.
329
+ */
330
+ async function verifyChallengerSetSignature(proof: DisputeResolutionProof, targetHash: string, setHash: string): Promise<boolean> {
331
+ try {
332
+ const publicKey = peerIdFromString(proof.challengerPeerId).publicKey;
333
+ if (!publicKey) {
334
+ return false;
335
+ }
336
+ const payload = arbitratorSetSigningPayload(proof.disputeId, targetHash, setHash);
337
+ const sigBytes = uint8ArrayFromString(proof.arbitratorSetSignature, 'base64url');
338
+ return await publicKey.verify(payload, sigBytes);
339
+ } catch (err) {
340
+ log('challenger-set-signature-verify-error challenger=%s error=%o', proof.challengerPeerId, err);
341
+ return false;
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Verify one arbitration vote's Ed25519 signature against its arbitrator peer id's embedded key, over
347
+ * the **target- and set-bound v3 payload**. Rejects any vote that is not the v3 format before trusting
348
+ * it, so a legacy/unversioned (v1/v2) vote can never slip through.
349
+ */
350
+ async function verifyVoteSignature(disputeId: string, vote: ArbitrationVoteProof, targetHash: string, setHash: string): Promise<boolean> {
351
+ // Runtime gate: `vote` arrives off the wire, so its `version` may not match the declared type.
352
+ if (vote.version !== VOTE_VERSION) {
353
+ return false;
354
+ }
355
+ try {
356
+ const publicKey = peerIdFromString(vote.arbitratorPeerId).publicKey;
357
+ if (!publicKey) {
358
+ return false;
359
+ }
360
+ const payload = voteSigningPayload(disputeId, vote.vote, vote.computedHash, targetHash, setHash);
361
+ const sigBytes = uint8ArrayFromString(vote.signature, 'base64url');
362
+ return await publicKey.verify(payload, sigBytes);
363
+ } catch (err) {
364
+ log('vote-signature-verify-error arbitrator=%s error=%o', vote.arbitratorPeerId, err);
365
+ return false;
366
+ }
367
+ }
368
+
369
+ // ─── Compensating-state computation ───
370
+
371
+ /**
372
+ * The recomputed "as-if-`T_inv`-never-committed" state for a single block.
373
+ * - `restore`: the block existed before `T_inv`; `block` is its recomputed content (the revision
374
+ * immediately before `T_inv`, with any surviving later actions replayed on top).
375
+ * - `delete`: `T_inv` created the block, so the as-if-absent state is a deletion (physically removed
376
+ * by {@link applyInvalidation} via a tombstone — see {@link DELETED_BLOCK_RESTORE}).
377
+ */
378
+ export type RevertedComputation =
379
+ | { kind: 'restore'; block: IBlock; restoredContentHash: string; fromRev: number; laterActions: number }
380
+ | { kind: 'delete'; fromRev: number };
381
+
382
+ /**
383
+ * Reconstructs the compensating content for one block from stored revisions only (never by re-running
384
+ * the engine — so it does not depend on engine availability and stays deterministic across members).
385
+ *
386
+ * Base = the block's content at the highest stored revision strictly before `T_inv` (no such revision
387
+ * ⇒ `T_inv` created the block ⇒ a deletion). In the single-collection/no-cascade core, "surviving later
388
+ * actions" = every committed action after `T_inv` on this block, replayed verbatim on the rolled-back
389
+ * base. The cascade (see `cascade.ts`) layers true read-dependent re-evaluation on top of this blind
390
+ * replay — it reverts the genuine successors this primitive leaves as-is and logs.
391
+ */
392
+ export async function computeRevertedBlock(blockStorage: IBlockStorage, invalidatedRev: number): Promise<RevertedComputation> {
393
+ const latest = await blockStorage.getLatest();
394
+ const fromRev = latest?.rev ?? invalidatedRev;
395
+
396
+ // Find the highest stored revision strictly before T_inv — the base to roll back to. A descending
397
+ // listRevisions(invalidatedRev - 1, 1) yields it first (same descending-scan pattern materializeBlock
398
+ // uses, so no new cost class). No such revision ⇒ T_inv CREATED this block ⇒ the as-if-absent state is
399
+ // a deletion — at ANY rev, without throwing (the previous `invalidatedRev <= 1` special-case folds into
400
+ // this: at rev <= 1 the probe is skipped and priorRev stays undefined). We intentionally do NOT replay
401
+ // surviving later actions onto an absent base: replaying an update on `undefined` stays `undefined`, and
402
+ // any later writer of a created-then-reverted block is itself a read-dependent the cascade (`cascade.ts`)
403
+ // re-evaluates and reverts.
404
+ let priorRev: number | undefined;
405
+ if (invalidatedRev > 1) {
406
+ for await (const ar of blockStorage.listRevisions(invalidatedRev - 1, 1)) {
407
+ priorRev = ar.rev;
408
+ break;
409
+ }
410
+ }
411
+ if (priorRev === undefined) {
412
+ return { kind: 'delete', fromRev };
413
+ }
414
+ const base = await blockStorage.getBlock(priorRev);
415
+ if (!base) {
416
+ return { kind: 'delete', fromRev };
417
+ }
418
+
419
+ // Replay surviving later actions (committed strictly after T_inv) onto the rolled-back base.
420
+ // Guard on `fromRev > invalidatedRev`: listRevisions treats start > end as a *descending*
421
+ // range, so an unguarded listRevisions(invalidatedRev + 1, fromRev) when no later action
422
+ // exists would wrongly re-include T_inv's own revision.
423
+ let block: IBlock | undefined = base.block;
424
+ let laterActions = 0;
425
+ if (fromRev > invalidatedRev) {
426
+ for await (const actionRev of blockStorage.listRevisions(invalidatedRev + 1, fromRev)) {
427
+ const transform = await blockStorage.getTransaction(actionRev.actionId);
428
+ if (!transform) {
429
+ continue;
430
+ }
431
+ block = applyTransform(block, transform);
432
+ laterActions++;
433
+ }
434
+ }
435
+ if (!block) {
436
+ return { kind: 'delete', fromRev };
437
+ }
438
+ const restoredContentHash = await hashBlockContent(block);
439
+ return { kind: 'restore', block, restoredContentHash, fromRev, laterActions };
440
+ }
441
+
442
+ /**
443
+ * Deterministic content hash for a materialized block — the single hashing convention shared by
444
+ * the compensating-state computation ({@link computeRevertedBlock}) and the cascade re-evaluator
445
+ * (`db-p2p/src/dispute/cascade.ts`). Both must agree byte-for-byte: the cascade decides whether a
446
+ * read-dependent still holds by comparing the hash of the content it *observed* against the
447
+ * `restoredContentHash` an invalidation recorded — so the two hashes have to be produced the same way.
448
+ */
449
+ export async function hashBlockContent(block: IBlock): Promise<string> {
450
+ return await hashString(stableStringify(block));
451
+ }
452
+
453
+ // ─── Deterministic apply ───
454
+
455
+ /** Everything the apply primitive needs from the host: the collection log and per-block storage. */
456
+ export type InvalidationContext = {
457
+ /** The collection log of the collection `T_inv` wrote (where the compensating entry is appended). */
458
+ readonly log: Log<unknown>;
459
+ /** Resolves a block's storage so the compensating revision can be written. */
460
+ readonly createBlockStorage: (blockId: BlockId) => IBlockStorage;
461
+ };
462
+
463
+ export type ApplyInvalidationParams = {
464
+ readonly invalidatedActionId: ActionId;
465
+ readonly invalidatedRev: number;
466
+ /** Blocks `T_inv` wrote (its commit's blockIds). */
467
+ readonly blockIds: ReadonlyArray<BlockId>;
468
+ /** The invalidation certificate. */
469
+ readonly proof: DisputeResolutionProof;
470
+ /**
471
+ * Consensus-assigned revision slot for the compensating revision (collection-global). When
472
+ * omitted, computed as one past the highest current tip across the reverted blocks — the value a
473
+ * local/single-node apply uses; the consensus path passes the agreed slot.
474
+ */
475
+ readonly rev?: number;
476
+ /**
477
+ * When this invalidation is a cascade step (a read-dependent of an already-invalidated root being
478
+ * reverted), the `actionId` of the root invalidation that triggered the cascade. Recorded on the
479
+ * resulting {@link InvalidationEntry} (`cascadeRoot`) so the reversal is auditable as part of one
480
+ * logical cascade event. Absent for a root invalidation.
481
+ */
482
+ readonly cascadeRoot?: ActionId;
483
+ /**
484
+ * The target the proof's votes are bound to — the transaction the dispute actually resolved. For a
485
+ * **root** invalidation this equals this call's own `(invalidatedActionId, blockIds)` and may be
486
+ * omitted (defaulted below). A **cascade child** reuses the *root's* proof to authorize reverting a
487
+ * read-dependent whose own target differs, so it MUST pass the root's target here: the votes were
488
+ * signed over the root's `targetHash`, not the child's. The child-specific justification is the
489
+ * deterministic cascade derivation every member replays — not the certificate, which only attests
490
+ * the root is invalid. (The network-facing apply path `applyConsensusInvalidation` never sets this:
491
+ * it verifies against the request's *own* target, which is the replay boundary this ticket closes.)
492
+ */
493
+ readonly certificateTarget?: CertificateTarget;
494
+ readonly timestamp?: number;
495
+ };
496
+
497
+ export type ApplyInvalidationResult = {
498
+ readonly applied: boolean;
499
+ readonly reason?: 'already-applied' | 'invalid-certificate';
500
+ readonly rev?: number;
501
+ readonly reverted: ReadonlyArray<RevertedBlock>;
502
+ };
503
+
504
+ /**
505
+ * Deterministically applies a single-collection invalidation: the durable reversal primitive every
506
+ * cluster member runs identically (it carries the `reverted` targets and proof, exactly as the
507
+ * consensus-apply path runs committed operations on every peer).
508
+ *
509
+ * Steps, in order:
510
+ * 1. **Dedup** — if the log already holds an invalidation for `(invalidatedActionId, disputeId)`,
511
+ * this is a re-receipt (rebroadcast / sync / retry): no-op, append nothing.
512
+ * 2. **Certificate** — reject (append nothing) unless `proof` is a valid challenger-wins certificate.
513
+ * 3. **Reverted revisions** — for each block, recompute the as-if-`T_inv`-absent content and write a
514
+ * new monotonic revision (a forward compensating transform; prior revisions are retained).
515
+ * 4. **Log entry** — append the {@link InvalidationEntry} carrying the proof and `reverted` targets,
516
+ * making `committed-invalidated` durable and recoverable on sync.
517
+ */
518
+ export async function applyInvalidation(ctx: InvalidationContext, params: ApplyInvalidationParams): Promise<ApplyInvalidationResult> {
519
+ const { invalidatedActionId, invalidatedRev, blockIds, proof } = params;
520
+
521
+ // 1. Idempotent re-receipt — keyed on (invalidatedActionId, disputeId).
522
+ const existing = await ctx.log.findInvalidation(invalidatedActionId);
523
+ if (existing && existing.resolution.disputeId === proof.disputeId) {
524
+ log('apply-skip-duplicate actionId=%s disputeId=%s', invalidatedActionId, proof.disputeId);
525
+ return { applied: false, reason: 'already-applied', reverted: [...existing.reverted] };
526
+ }
527
+
528
+ // 2. Certificate verification — never trust a single peer's say-so. The proof's votes are bound to
529
+ // a specific target; verify against the target they were signed over. For a root invalidation
530
+ // that is this call's own target; a cascade child passes the root's target via `certificateTarget`
531
+ // (the child-target justification is the deterministic cascade, not the certificate). A mismatched
532
+ // target (a genuine proof replayed against an innocent transaction) fails every signature here, so
533
+ // no compensating revision or log entry is ever written for it.
534
+ const certificateTarget = params.certificateTarget ?? { invalidatedActionId, blockIds };
535
+ if (!(await verifyInvalidationCertificate(proof, certificateTarget))) {
536
+ log('apply-reject-certificate actionId=%s disputeId=%s outcome=%s', invalidatedActionId, proof.disputeId, proof.outcome);
537
+ return { applied: false, reason: 'invalid-certificate', reverted: [] };
538
+ }
539
+
540
+ // 3. Compute compensating content + the collection-global revision slot.
541
+ const computations = await Promise.all(
542
+ blockIds.map(async (blockId) => {
543
+ const storage = ctx.createBlockStorage(blockId);
544
+ return { blockId, storage, computation: await computeRevertedBlock(storage, invalidatedRev) };
545
+ })
546
+ );
547
+ const maxFromRev = computations.reduce((max, c) => Math.max(max, c.computation.fromRev), invalidatedRev);
548
+ const rev = params.rev ?? maxFromRev + 1;
549
+
550
+ const reverted: RevertedBlock[] = [];
551
+ for (const { blockId, storage, computation } of computations) {
552
+ // Deterministic compensating-revision actionId — identical on every member, so all converge on
553
+ // the same (rev, actionId) for both the restore and the tombstone path.
554
+ const revertActionId = await hashString(`inv:${invalidatedActionId}:${proof.disputeId}:${blockId}:${rev}`);
555
+ if (computation.kind === 'delete') {
556
+ // Block-creation reversal: physically remove the created block by writing a forward tombstone
557
+ // revision. The `restoredContentHash` is the DELETED_BLOCK_RESTORE sentinel — a deleted block
558
+ // has no content hash, and the sentinel tells dependents "observed content is gone → invalidate".
559
+ await storage.saveDeletion({ rev, actionId: revertActionId });
560
+ log('apply-delete-restore blockId=%s invalidatedRev=%d rev=%d', blockId, invalidatedRev, rev);
561
+ reverted.push({ blockId, fromRev: computation.fromRev, restoredContentHash: DELETED_BLOCK_RESTORE });
562
+ continue;
563
+ }
564
+ if (computation.laterActions > 0) {
565
+ // Surviving later actions were replayed verbatim; true read-dependents are out of scope here.
566
+ log('apply-replayed-later-actions blockId=%s count=%d', blockId, computation.laterActions);
567
+ }
568
+ await storage.saveReplica(computation.block, { rev, actionId: revertActionId });
569
+ reverted.push({ blockId, fromRev: computation.fromRev, restoredContentHash: computation.restoredContentHash });
570
+ }
571
+
572
+ // 4. Durable, append-only invalidation entry (the source of truth for committed-invalidated).
573
+ // `cascadeRoot` is set when this is a cascade step (a reverted read-dependent), undefined for a root.
574
+ await ctx.log.addInvalidation(invalidatedActionId, invalidatedRev, proof, reverted, rev, params.cascadeRoot, params.timestamp);
575
+ log('apply-complete actionId=%s disputeId=%s rev=%d blocks=%d', invalidatedActionId, proof.disputeId, rev, reverted.length);
576
+
577
+ return { applied: true, rev, reverted };
578
+ }
579
+
580
+ /** Deterministic, key-sorted JSON for content hashing — stable across members regardless of key order. */
581
+ function stableStringify(value: unknown): string {
582
+ return JSON.stringify(value, (_key, v) =>
583
+ v && typeof v === 'object' && !Array.isArray(v)
584
+ ? Object.keys(v).sort().reduce((o: Record<string, unknown>, k) => { o[k] = (v as Record<string, unknown>)[k]; return o; }, {})
585
+ : v
586
+ );
587
+ }
@@ -32,10 +32,24 @@ export type DisputeChallenge = {
32
32
  timestamp: number;
33
33
  /** TTL for arbitration (default: 2 × transaction TTL) */
34
34
  expiration: number;
35
+ /**
36
+ * The legitimately-selected arbitrator set (peer-id strings) the challenger computed for this dispute
37
+ * — the next K peers beyond the original cluster. Carried on the challenge so each arbitrator folds its
38
+ * digest (`setHash`) into the v3 vote it signs, binding the votes to the set (#1). Absent only on a
39
+ * pre-v3 challenger; such votes will not verify against a v3 proof. The originator independently carries
40
+ * the same set on {@link DisputeResolutionProof.arbitratorSet}.
41
+ */
42
+ arbitratorSet?: string[];
35
43
  };
36
44
 
37
45
  /** An arbitrator's independent assessment */
38
46
  export type ArbitrationVote = {
47
+ /**
48
+ * Wire-format version of the signed vote payload (target- and arbitrator-set-bound). Mirrors
49
+ * {@link ArbitrationVoteProof.version}; kept in lock-step so origination and the proof projection
50
+ * agree. Only `'v3'` is produced/accepted today.
51
+ */
52
+ version: 'v3';
39
53
  /** Dispute being voted on */
40
54
  disputeId: string;
41
55
  /** Peer ID of the arbitrator */
package/src/index.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  export * from "./cluster/client.js";
2
2
  export * from "./cluster/cluster-repo.js";
3
+ export * from "./cluster/commit-cert.js";
3
4
  export * from "./cluster/service.js";
4
5
  export * from "./cluster/rebalance-monitor.js";
5
6
  export * from "./cluster/spread-on-churn.js";
@@ -32,6 +33,9 @@ export * from "./network/network-manager-service.js";
32
33
  export * from "./network/get-network-manager.js";
33
34
  export * from "./reputation/index.js";
34
35
  export * from "./dispute/index.js";
36
+ export * from "./cohort-topic/index.js";
37
+ export * from "./matchmaking/index.js";
38
+ export * from "./reactivity/index.js";
35
39
  export * from "./cluster/i-transaction-state-store.js";
36
40
  export * from "./cluster/memory-transaction-state-store.js";
37
41
  export * from "./cluster/persistent-transaction-state-store.js";