ckb-vm-js 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +140 -2
- package/THIRD_PARTY_NOTICES.md +2317 -0
- package/crates/verifier/SCHEMA.md +114 -0
- package/docs/javascript.md +187 -0
- package/docs/local-first-publish.md +168 -0
- package/docs/playground.md +90 -0
- package/docs/publishing.md +98 -0
- package/docs/verification.md +92 -0
- package/js/index.d.ts +106 -0
- package/js/index.js +84 -0
- package/js/worker.js +23 -0
- package/package.json +44 -4
- package/pkg/ckb_wasm_verifier.d.ts +44 -0
- package/pkg/ckb_wasm_verifier.js +222 -0
- package/pkg/ckb_wasm_verifier_bg.wasm +0 -0
- package/pkg/ckb_wasm_verifier_bg.wasm.d.ts +13 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# 发布与 npm Trusted Publishing
|
|
2
|
+
|
|
3
|
+
截至 2026-11-12,本次只添加发布流程,**尚未配置 npm 信任关系,也没有替你注册包、创建 GitHub environment、tag、Release 或执行 npm 发布**。`npm pack` 生成本地 tarball,不等于发布。
|
|
4
|
+
|
|
5
|
+
## 工作流做什么
|
|
6
|
+
|
|
7
|
+
入口固定为 [`.github/workflows/publish.yml`](../.github/workflows/publish.yml):
|
|
8
|
+
|
|
9
|
+
- **Actions → Publish npm package → Run workflow**:选择 `main`,填写已存在的版本 tag,只构建、验证和上传 tarball。不会进入发布 job,也不申请 npm OIDC 身份。
|
|
10
|
+
- **发布 GitHub Release**:`release.published` 事件先执行相同构建,再进入 `npm-publish` environment,批准后用 OIDC 发布经过测试的同一个 tarball。
|
|
11
|
+
- 普通 push、PR、评论和单独推送 tag 都不会触发 npm 发布。工作流不创建 GitHub Release,不修改账户设置。
|
|
12
|
+
- 构建/发布分别运行;发布 job 不安装项目依赖、不重新构建、不执行包生命周期脚本。没有 `NPM_TOKEN`、`NODE_AUTH_TOKEN` secret 或长期 token fallback。
|
|
13
|
+
|
|
14
|
+
使用 GitHub-hosted Ubuntu、Node 24、固定 npm 11.21.0。Actions 固定到审阅时的完整 commit SHA;发布构建不恢复依赖或编译缓存。npm OIDC 要求至少 npm 11.5.1、Node 22.14.0;当前不支持 self-hosted runner。配置字段和权限规则以 [npm 官方文档](https://docs.npmjs.com/trusted-publishers/)为准。
|
|
15
|
+
|
|
16
|
+
参考了 [CCC 发布流程](https://github.com/ckb-devrel/ccc/blob/b7babe4c25bdf0cf9f0e2d5a89b8dc6b12a08414/.github/workflows/_publish-packages.yaml)的独立发布环境和构建后发布结构。该版本 CCC 使用 Changesets 和 `NPM_TOKEN`;本项目是单包,因此没有照搬 monorepo、canary/评论触发或长期 token 方案。
|
|
17
|
+
|
|
18
|
+
希望自己 clone、构建并首发,请按[本地首次发布完整步骤](local-first-publish.md)执行;不要只 npm pack 未构建的 checkout。
|
|
19
|
+
|
|
20
|
+
## 1. 首次创建 npm 包
|
|
21
|
+
|
|
22
|
+
Trusted Publisher 是**包级设置**。还不存在的 `ckb-vm-js` 不能凭空配置 OIDC 并直接完成首发。由准备拥有该 npm 包的维护者,在确认名称仍可用并审阅内容后,选择一种方式:
|
|
23
|
+
|
|
24
|
+
1. **交互式首次发布**:下载已经验证的 `ckb-vm-js-0.2.0.tgz`,在自己的终端登录 npm,完成需要的 2FA,再发布该文件。
|
|
25
|
+
2. **先暂存创建包**:新版 npm 支持用交互式会话执行 `npm stage publish` 来创建新包。第一版进入待审批队列,维护者批准后才可安装。创建包之后就能管理设置和配置 Trusted Publisher。这不是匿名/OIDC 自动首次注册。[官方新包暂存说明](https://github.blog/changelog/2026-10-02-npm-staged-publishing-now-supports-creating-new-packages/)
|
|
26
|
+
|
|
27
|
+
只有在你准备实际发布时,才自行运行以下示例,二选一:
|
|
28
|
+
|
|
29
|
+
```sh
|
|
30
|
+
# 使用当前受支持的 Node/npm,先在自己的终端完成登录。
|
|
31
|
+
npm login --registry=https://registry.npmjs.org
|
|
32
|
+
|
|
33
|
+
# A:直接首次发布;这会产生真实的公开 npm 版本。
|
|
34
|
+
npm publish ./ckb-vm-js-0.2.0.tgz --access public --ignore-scripts
|
|
35
|
+
|
|
36
|
+
# 或 B:创建并暂存第一版;之后到 npm 审阅并批准。
|
|
37
|
+
# 需要支持 stage 的新版 npm,详见官方 staged publishing 文档。
|
|
38
|
+
npm stage publish ./ckb-vm-js-0.2.0.tgz --access public
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
本工作流要求已有一个**公开可读的 bootstrap 版本**。如果使用暂存方式,请先批准第一版,再用下一个版本验证自动发布。live Release 在安装构建依赖前检查公开 registry,并在发布前再次检查版本和 dist-tag;手动 dry-run 保持可离线准备首包。工作流遇到 registry 404 会明确停止,不会降级到 token 或自动注册。读取 registry 的错误也不会被当作“版本不存在”。
|
|
42
|
+
|
|
43
|
+
已发布的包名/版本组合不能再次使用。若先发布了 `0.2.0`,第一个 OIDC Release 应使用新版本,例如 `0.2.1`,不能再发布 `v0.2.0`。[npm publish 规则](https://docs.npmjs.com/cli/v11/commands/npm-publish/)
|
|
44
|
+
|
|
45
|
+
live 检查同时拒绝 notices 中仍标记的未解决缺口,发布前再检查 tarball 内的 notices。该检查不是法律审查。
|
|
46
|
+
|
|
47
|
+
发布前仍应审阅实验性验证范围及 [第三方许可证声明与来源](../THIRD_PARTY_NOTICES.md)。自动化和 provenance 不会代替代码或许可证审查。
|
|
48
|
+
|
|
49
|
+
## 2. GitHub 配置(仓库管理员完成)
|
|
50
|
+
|
|
51
|
+
在 `Hanssen0-Alter-Ego/ckb-vm-js` 的 **Settings → Environments**:
|
|
52
|
+
|
|
53
|
+
1. 创建名称恰好为 **`npm-publish`** 的 environment。
|
|
54
|
+
2. 配置 required reviewers,建议禁止发布发起者自行批准;如使用 tag 限制,允许版本 tag `v*`,不要仅允许 `main` 分支,因为 live job 的 ref 是 release tag。
|
|
55
|
+
3. 保护 `main` 和版本 tag,限制谁可以创建、移动或删除发布 tag。
|
|
56
|
+
|
|
57
|
+
不需要创建 npm token secret,也不需要将仓库默认 `GITHUB_TOKEN` 改成写权限。YAML 仅给发布 job `id-token: write`,其他 job 只有 `contents: read`。Environment 的审批/分支规则需由管理员实际设置,写入 YAML 的 environment 名本身不会建立审批保护。[GitHub environment 文档](https://docs.github.com/en/actions/reference/workflows-and-actions/deployments-and-environments)
|
|
58
|
+
|
|
59
|
+
## 3. npm 配置(npm 包维护者完成)
|
|
60
|
+
|
|
61
|
+
在 npm 的 `ckb-vm-js` 包页面进入 **Settings → Trusted publishing**,添加 GitHub Actions:
|
|
62
|
+
|
|
63
|
+
| 字段 | 值 |
|
|
64
|
+
| --- | --- |
|
|
65
|
+
| Organization or user | `Hanssen0-Alter-Ego` |
|
|
66
|
+
| Repository | `ckb-vm-js` |
|
|
67
|
+
| Workflow filename | **`publish.yml`**,不要填写 `.github/workflows/` 前缀 |
|
|
68
|
+
| Environment name | **`npm-publish`** |
|
|
69
|
+
| Allowed actions | **勾选 Allow npm publish** |
|
|
70
|
+
|
|
71
|
+
当前新配置默认允许 staging;本 workflow 执行直接 `npm publish`,只保留 stage-only 会失败。不需要另外允许 `npm dist-tag`,这里没有调用该命令。仓库、文件名、environment 大小写必须一致。`package.json.repository.url` 已与此仓库一致。[Trusted Publisher 设置](https://docs.npmjs.com/trusted-publishers/)
|
|
72
|
+
|
|
73
|
+
**在准备好下一版时再创建信任关系**:新配置需在 48 小时内完成第一次成功发布,否则会过期,需要删除后重新创建。第一次成功后,信任绑定到仓库的不可变身份。保存表单不代表已经验证成功。[官方过期规则](https://github.blog/changelog/2026-10-02-unvalidated-npm-trusted-publishing-configurations-now-expire/)
|
|
74
|
+
|
|
75
|
+
公共仓库的公共包通过 OIDC 发布可以生成 provenance。工作流显式启用了 `--provenance`;它证明来源和构建关联,不证明软件安全或共识正确。[Provenance 文档](https://docs.npmjs.com/generating-provenance-statements/)
|
|
76
|
+
|
|
77
|
+
验证 OIDC 真正工作以后,可以再考虑 npm 的 “Require two-factor authentication and disallow tokens” 设置;本次没有修改这些设置或创建/撤销任何 token。
|
|
78
|
+
|
|
79
|
+
## 4. 日常发版
|
|
80
|
+
|
|
81
|
+
以 `0.2.1` 为例,由维护者完成:
|
|
82
|
+
|
|
83
|
+
1. 更新 `package.json` 和 `package-lock.json` 的版本,例如 `npm version patch --no-git-tag-version`。提交并合入 `main`,等待普通 CI 通过。
|
|
84
|
+
2. 给该 commit 创建 `v0.2.1` tag 并推送。tag 必须精确等于 `v` + npm 版本,指向 `main` 历史中的 commit,且包含此发布工作流和脚本。不要移动已用过的 tag。
|
|
85
|
+
3. 可先手动运行 `Publish npm package`,选择 `main`、输入 `v0.2.1`,下载并检查 dry-run artifact。
|
|
86
|
+
4. 发布该 tag 对应的 GitHub Release,或将草稿 Release 发布。稳定版本不要勾 prerelease;例如 `0.3.0-rc.1` 必须勾 prerelease。
|
|
87
|
+
5. 等待完整 native/WASM/browser 验证和 tarball 安装测试;审批 `npm-publish` environment。
|
|
88
|
+
6. 检查 Actions 与 npm 上的版本/provenance。npm 的发布扫描可能延迟可安装时间,成功提交不一定立即可安装。[发布扫描说明](https://github.blog/changelog/2026-07-28-npm-publish-time-malware-scanning-and-dual-use-metadata/)
|
|
89
|
+
|
|
90
|
+
稳定版本使用 `latest`,预发布使用 `next`。检查器拒绝版本重发、错误包名/仓库、lockfile 不一致、Release 类型不一致、tag 移动、非 main commit、tarball 摘要变化和 dist-tag 倒退。使用同一个并发组串行处理发布,避免两个版本同时争抢 `latest`。
|
|
91
|
+
|
|
92
|
+
## 故障与验证边界
|
|
93
|
+
|
|
94
|
+
- `ENEEDAUTH`:检查 npm CLI/runner、`id-token: write`、四项 trust 字段、Allow npm publish、48 小时窗口;不要临时塞入一个长期发布 token。
|
|
95
|
+
- 第一次手动 dry-run 成功**不证明 OIDC 已配置**:该模式刻意不申请发布身份,也不写 registry。
|
|
96
|
+
- 发布调用超时或结果不明确:先查 npm 和 Actions 输出,确认是否已经接受该版本,不要盲目重发。已公开的版本不可覆盖,registry 检查会停止重复发布。
|
|
97
|
+
- 如构建成功、发布 job 失败,先排查配置/状态,再选择 GitHub 的“重跑失败 jobs”;不要假设重新打包的文件与此前测试文件相同。
|
|
98
|
+
- 维护检查包括 release guard 单元测试、Actionlint 和离线包安装;普通 CI 会从源码重新构建并验证 native/WASM/browser,结果以对应 commit 的检查为准。没有执行真实 `npm publish`、创建远端 tag/Release、配置 environment 或 npm trust,因此首次 OIDC 发布仍须由维护者配置后验证。
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
# Verification record and limits
|
|
2
|
+
|
|
3
|
+
This is an experimental integration of pinned upstream CKB. Passing a finite fixture suite is not proof of consensus equivalence, and no independent production security audit is claimed.
|
|
4
|
+
|
|
5
|
+
## Reproduce
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
./scripts/prepare.sh
|
|
9
|
+
cargo fmt --all -- --check
|
|
10
|
+
cargo clippy --locked -p ckb-wasm-verifier --all-targets --no-deps -- -D warnings
|
|
11
|
+
cargo test --locked -p ckb-wasm-verifier
|
|
12
|
+
cargo build --locked -p ckb-wasm-verifier --bin verify
|
|
13
|
+
npm ci
|
|
14
|
+
npm test
|
|
15
|
+
npm run typecheck
|
|
16
|
+
./scripts/build-wasm.sh
|
|
17
|
+
npm run test:wasm
|
|
18
|
+
npm run test:differential
|
|
19
|
+
npx playwright install chromium
|
|
20
|
+
npm run test:browser
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`fixtures/*.json` contain `{request, expected}`. They are generated by the native wrapper using the same pinned CKB verifier, not hand-written success stubs. The differential suite separately invokes the compiled native CLI for each request and compares actual results against the actual WASM engine, including cycles, fee, errors and group membership. Group array order is normalized because upstream hash-map iteration order is not meaningful. This comparison checks host/platform consistency; it does not independently prove that our context wrapper includes every required rule.
|
|
24
|
+
|
|
25
|
+
Regenerate only when intentionally reviewing a behavior change:
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
cargo run -p ckb-wasm-verifier --example generate-fixtures -- fixtures
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
The baseline fixtures exercise full lock execution, lock plus type execution, selected lock/type groups, dep-group expansion, cycle exhaustion, nonzero script exit, malformed ELF, version/shape/capacity rejection, duplicate inputs/dependencies, maturity/since, incomplete context and inconsistent metadata. Adversarial host-width cases are described beside the compatibility patches.
|
|
32
|
+
|
|
33
|
+
## Foundation-interface coverage and audit scope
|
|
34
|
+
|
|
35
|
+
The caller supplies all context and transaction-relevant consensus parameters. The core does not select mainnet/testnet, fetch headers/cells, maintain a chain database, or infer that a supplied cell is live. Submitted mode uses the actual current tip; committed mode uses a separate candidate header and target transaction index. These modes deliberately follow different upstream environment semantics, including median-time starting point and DAO lock-size gating.
|
|
36
|
+
|
|
37
|
+
The consensus-field audit follows noncontextual/contextual transaction verification, script VM selection, and DAO transaction-fee calculation. It does not turn this wrapper into a full block verifier, and it is not a proof that the pinned upstream can replay all historical rules with arbitrary hardfork parameters. Network wrappers can be added separately without changing this trust boundary.
|
|
38
|
+
|
|
39
|
+
Audit references at the pinned CKB commit:
|
|
40
|
+
|
|
41
|
+
- [Transaction checks](https://github.com/nervosnetwork/ckb/blob/6abb474c1678e67dae0337abeb8bfd77cfb576e3/verification/src/transaction_verifier.rs) and [verification environments](https://github.com/nervosnetwork/ckb/blob/6abb474c1678e67dae0337abeb8bfd77cfb576e3/script/src/verify_env.rs).
|
|
42
|
+
- [DAO transaction-fee/withdrawal paths](https://github.com/nervosnetwork/ckb/blob/6abb474c1678e67dae0337abeb8bfd77cfb576e3/util/dao/src/lib.rs), distinct from block reward calculation.
|
|
43
|
+
- [Pool DAO size checks](https://github.com/nervosnetwork/ckb/blob/6abb474c1678e67dae0337abeb8bfd77cfb576e3/tx-pool/src/util.rs) versus [committed-block activation](https://github.com/nervosnetwork/ckb/blob/6abb474c1678e67dae0337abeb8bfd77cfb576e3/verification/contextual/src/contextual_block_verifier.rs).
|
|
44
|
+
- [Same-block cell metadata and ordering](https://github.com/nervosnetwork/ckb/blob/6abb474c1678e67dae0337abeb8bfd77cfb576e3/util/types/src/core/cell.rs).
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
The v0.2 corpus contains **62 fixtures**. New coverage includes default and explicit submitted mode; submitted versus committed earliest-height `since`; same-block ordering and zero/positive relative since; explicit unconfirmed inputs and header/extension syscall results; omitted origins; custom transaction version, byte limit, maturity and VM activation; tip/candidate mismatch; height overflow; and invalid median configuration. A large configured median window reaching genesis checks that allocation follows actual ancestry, rather than eagerly reserving the whole caller-supplied count.
|
|
48
|
+
|
|
49
|
+
Four custom-chain fixtures isolate the DAO size gate: submitted mode before block activation, committed mode before/at activation, and the origin-height threshold. These use a tiny success program as a stand-in for the DAO type script and **are not full Nervos DAO withdrawal tests**.
|
|
50
|
+
|
|
51
|
+
## v0.2 local execution record (2026-11-12)
|
|
52
|
+
|
|
53
|
+
- Rust 1.95.0 formatting, Clippy with warnings denied, and 4 tests passed; one test executes all 62 fixture mutations.
|
|
54
|
+
- 63 real-WASM tests passed (62 fixtures plus initialization/error boundary).
|
|
55
|
+
- Both 62-case native/WASM differential runs passed: patched native and separately built unmodified upstream submodules. The wrapper is shared, so this is platform parity, not an independent full-node consensus proof.
|
|
56
|
+
- 11 JavaScript unit/protocol tests and TypeScript checks passed.
|
|
57
|
+
- The built 0.2.0 tarball was installed offline into a fresh consumer directory and verified a real transaction.
|
|
58
|
+
- Real browser execution remains a CI check: this local environment cannot launch Chromium because a required socket operation is unavailable. No local real-browser pass is claimed. The Worker test now covers submitted, unconfirmed and same-block inputs, in addition to the original valid/selected/failure cases. Inspect the workflow associated with the exact source commit.
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
## Limits
|
|
62
|
+
|
|
63
|
+
- The corpus is synthetic and small. It is not a replay of historical mainnet blocks or a comprehensive upstream conformance suite.
|
|
64
|
+
- Complex DAO withdrawal transitions, every syscall family, TYPE_ID lifecycle, spawn/exec process trees and all historical hardfork boundaries need broader fixtures.
|
|
65
|
+
- Native comparison includes a binary built from unmodified upstream submodules, but uses the same integration wrapper. A separate full-node oracle and known historical transactions would provide stronger evidence.
|
|
66
|
+
- JSON/snapshot size and memory consumption need application-level limits. Cycle limits bound VM execution, not parsing, context allocation or every setup cost.
|
|
67
|
+
- The API trusts the developer's external context. It cannot authenticate headers, cell data, extensions, spent status, ancestry or proposal inclusion.
|
|
68
|
+
- Browser execution should use the Worker interface. Workers may be terminated by the caller; the direct synchronous WASM call has no cooperative cancellation API.
|
|
69
|
+
|
|
70
|
+
## Historical v0.1 local execution record (2026-11-12)
|
|
71
|
+
|
|
72
|
+
- Rust 1.95.0 native check, formatting, tests and Clippy were run.
|
|
73
|
+
- 33 transaction fixtures run through the real WASM engine, plus an initialization/invalid-request check.
|
|
74
|
+
- Live differential comparison against native, including an unmodified-upstream native binary.
|
|
75
|
+
- 11 JavaScript boundary/Worker-protocol tests and TypeScript declarations checked.
|
|
76
|
+
- WASM release generated with wasm-bindgen 0.2.105 and WASI SDK 34 clang (only as C compiler, still targeting bare wasm32-unknown-unknown).
|
|
77
|
+
- The local environment could not launch Chromium because a required local socket operation was unavailable. Managed-browser access also could not reach the isolated local server. No local real-browser pass is claimed; the committed CI workflow runs the real offline Worker test in Chromium. Check the exact commit's workflow result.
|
|
78
|
+
|
|
79
|
+
## Historical v0.1 CI browser evidence
|
|
80
|
+
|
|
81
|
+
The complete workflow passed at engine commit `184af5d80ce8a2798d432c821b475ef03b3f6bc6`:
|
|
82
|
+
https://github.com/Hanssen0-Alter-Ego/ckb-vm-js/actions/runs/43139332773
|
|
83
|
+
|
|
84
|
+
This includes Chromium running a real dedicated Worker with `crossOriginIsolated === false` and no SharedArrayBuffer. After module initialization from localhost, browser networking is disabled before full transaction, selected group and failure fixtures are verified. It also includes native/WASM parity against the separately built **unmodified upstream** native engine. This evidence belongs to that exact earlier commit. In particular, it does not establish that the later foundation-interface refactor passed; inspect the current commit’s checks separately.
|
|
85
|
+
|
|
86
|
+
## Distribution notices
|
|
87
|
+
|
|
88
|
+
`THIRD_PARTY_NOTICES.md` records the dependency notices and their provenance. Two
|
|
89
|
+
upstream MIT notice texts were not found for blake2b-ref 0.3.1 and
|
|
90
|
+
ckb-system-scripts 0.5.4; those gaps and current-upstream fallbacks are explicit.
|
|
91
|
+
This attribution inventory is not a claim that licensing review is complete.
|
|
92
|
+
Resolve the listed gaps before production redistribution.
|
package/js/index.d.ts
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
export type Hex = `0x${string}`;
|
|
2
|
+
export interface OutPoint { tx_hash: Hex; index: Hex }
|
|
3
|
+
export interface Script { code_hash: Hex; hash_type: 'data' | 'type' | 'data1' | 'data2'; args: Hex }
|
|
4
|
+
export interface CellOutput { capacity: Hex; lock: Script; type?: Script | null }
|
|
5
|
+
export interface Transaction {
|
|
6
|
+
version: Hex;
|
|
7
|
+
cell_deps: Array<{ out_point: OutPoint; dep_type: 'code' | 'dep_group' }>;
|
|
8
|
+
header_deps: Hex[];
|
|
9
|
+
inputs: Array<{ previous_output: OutPoint; since: Hex }>;
|
|
10
|
+
outputs: CellOutput[];
|
|
11
|
+
outputs_data: Hex[];
|
|
12
|
+
witnesses: Hex[];
|
|
13
|
+
/** Optional RPC view hash; must match the hash computed from the transaction. */
|
|
14
|
+
hash?: Hex;
|
|
15
|
+
}
|
|
16
|
+
export interface Header {
|
|
17
|
+
compact_target: Hex; dao: Hex; epoch: Hex; extra_hash: Hex;
|
|
18
|
+
/** Optional RPC view hash; must match the hash computed from the header. */
|
|
19
|
+
hash?: Hex;
|
|
20
|
+
nonce: Hex; number: Hex; parent_hash: Hex; proposals_hash: Hex;
|
|
21
|
+
timestamp: Hex; transactions_root: Hex; version: Hex;
|
|
22
|
+
}
|
|
23
|
+
export interface ResolvedCell {
|
|
24
|
+
out_point: OutPoint; output: CellOutput; data: Hex;
|
|
25
|
+
/** Required: null claims a non-cellbase cell with unknown/unconfirmed origin, in either phase. */
|
|
26
|
+
transaction_info: { block_hash: Hex; block_number: Hex; block_epoch: Hex; index: Hex } | null;
|
|
27
|
+
}
|
|
28
|
+
/** Caller-supplied consensus configuration; no network presets are selected. */
|
|
29
|
+
export interface Consensus {
|
|
30
|
+
tx_version: Hex;
|
|
31
|
+
max_block_bytes: Hex;
|
|
32
|
+
max_block_cycles: Hex;
|
|
33
|
+
cellbase_maturity: Hex;
|
|
34
|
+
median_time_block_count: Hex;
|
|
35
|
+
tx_proposal_window: { closest: Hex; farthest: Hex };
|
|
36
|
+
dao_type_hash: Hex;
|
|
37
|
+
hardforks: {
|
|
38
|
+
rfc0028_epoch: Hex;
|
|
39
|
+
rfc0032_epoch: Hex;
|
|
40
|
+
rfc0049_epoch: Hex;
|
|
41
|
+
rfc0044_epoch: Hex;
|
|
42
|
+
};
|
|
43
|
+
starting_block_limiting_dao_withdrawing_lock: Hex;
|
|
44
|
+
}
|
|
45
|
+
export type Verification =
|
|
46
|
+
| { phase: 'submitted' }
|
|
47
|
+
| {
|
|
48
|
+
phase: 'committed';
|
|
49
|
+
/** Candidate must be a direct child of context.tip_header. */
|
|
50
|
+
candidate_header: Header;
|
|
51
|
+
/** Positive transaction index within the candidate block. */
|
|
52
|
+
transaction_index: Hex;
|
|
53
|
+
};
|
|
54
|
+
export interface Context {
|
|
55
|
+
consensus: Consensus;
|
|
56
|
+
/** Actual current chain tip, not the candidate committed block. */
|
|
57
|
+
tip_header: Header;
|
|
58
|
+
/** Defaults to submitted when omitted. */
|
|
59
|
+
verification?: Verification;
|
|
60
|
+
cells: ResolvedCell[];
|
|
61
|
+
headers: Header[];
|
|
62
|
+
extensions: Array<{ block_hash: Hex; data: Hex | null }>;
|
|
63
|
+
}
|
|
64
|
+
export interface ScriptGroup { group_type: 'lock' | 'type'; script_hash: Hex }
|
|
65
|
+
export interface VerifyRequest {
|
|
66
|
+
transaction: Transaction;
|
|
67
|
+
context: Context;
|
|
68
|
+
max_cycles: Hex;
|
|
69
|
+
script_group?: ScriptGroup;
|
|
70
|
+
}
|
|
71
|
+
export interface VerifyResult {
|
|
72
|
+
ok: boolean;
|
|
73
|
+
scope?: 'transaction' | 'script_group';
|
|
74
|
+
cycles?: Hex;
|
|
75
|
+
fee?: Hex;
|
|
76
|
+
groups?: Array<ScriptGroup & { input_indices: number[]; output_indices: number[] }>;
|
|
77
|
+
chain_state_verified?: false;
|
|
78
|
+
error?: { code: string; message: string };
|
|
79
|
+
[key: string]: unknown;
|
|
80
|
+
}
|
|
81
|
+
export interface WasmBindings {
|
|
82
|
+
default?: (options?: { module_or_path: WasmInput }) => Promise<unknown>;
|
|
83
|
+
verify: (requestJson: string) => string;
|
|
84
|
+
}
|
|
85
|
+
export type WasmInput = BufferSource | WebAssembly.Module | URL | Request | Response | string;
|
|
86
|
+
export interface VerifierOptions {
|
|
87
|
+
/** Omit to load the packaged WASM. Supply bytes/module for offline initialization. */
|
|
88
|
+
wasm?: WasmInput;
|
|
89
|
+
/** Override generated bindings loading, e.g. when integrating with a bundler. */
|
|
90
|
+
loadBindings?: () => Promise<WasmBindings> | WasmBindings;
|
|
91
|
+
}
|
|
92
|
+
export interface Verifier {
|
|
93
|
+
/** Runs synchronously inside WASM, returning its result through a Promise. */
|
|
94
|
+
verify(request: VerifyRequest): Promise<VerifyResult>;
|
|
95
|
+
verifyScriptGroup(request: VerifyRequest, group: ScriptGroup): Promise<VerifyResult>;
|
|
96
|
+
}
|
|
97
|
+
export interface WorkerVerifier extends Verifier { dispose(): void }
|
|
98
|
+
export interface WorkerVerifierOptions {
|
|
99
|
+
/** Bytes/module are cloned to the worker, not transferred or detached. */
|
|
100
|
+
wasm?: BufferSource | WebAssembly.Module | string;
|
|
101
|
+
worker?: Worker;
|
|
102
|
+
workerURL?: string | URL;
|
|
103
|
+
}
|
|
104
|
+
export function createVerifier(options?: VerifierOptions): Promise<Verifier>;
|
|
105
|
+
/** Owns and terminates the worker, including a caller-supplied worker. */
|
|
106
|
+
export function createWorkerVerifier(options?: WorkerVerifierOptions): Promise<WorkerVerifier>;
|
package/js/index.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/** Initialize once, then verify entirely from caller-supplied data. */
|
|
2
|
+
export async function createVerifier(options = {}) {
|
|
3
|
+
const bindings = await (options.loadBindings
|
|
4
|
+
? options.loadBindings()
|
|
5
|
+
: import('../pkg/ckb_wasm_verifier.js'));
|
|
6
|
+
if (typeof bindings.default === 'function') {
|
|
7
|
+
// wasm-bindgen's object form avoids its deprecated positional init API.
|
|
8
|
+
await bindings.default(options.wasm === undefined ? undefined : { module_or_path: options.wasm });
|
|
9
|
+
}
|
|
10
|
+
if (typeof bindings.verify !== 'function') throw new TypeError('WASM bindings must export verify(requestJson)');
|
|
11
|
+
const verify = async (request) => {
|
|
12
|
+
if (!request || typeof request !== 'object' || Array.isArray(request)) {
|
|
13
|
+
throw new TypeError('A verification request object is required');
|
|
14
|
+
}
|
|
15
|
+
const result = JSON.parse(bindings.verify(JSON.stringify(request)));
|
|
16
|
+
if (!result || typeof result !== 'object' || typeof result.ok !== 'boolean') {
|
|
17
|
+
throw new TypeError('Invalid verification response from WASM');
|
|
18
|
+
}
|
|
19
|
+
return result;
|
|
20
|
+
};
|
|
21
|
+
return Object.freeze({
|
|
22
|
+
verify,
|
|
23
|
+
verifyScriptGroup: async (request, group) => verify({ ...request, script_group: validateGroup(group) }),
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function validateGroup(group) {
|
|
28
|
+
if (!group || !['lock', 'type'].includes(group.group_type) ||
|
|
29
|
+
!/^0x[0-9a-fA-F]{64}$/.test(group.script_hash)) {
|
|
30
|
+
throw new TypeError('A script group requires group_type (lock or type) and a 32-byte script_hash');
|
|
31
|
+
}
|
|
32
|
+
return group;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Dedicated Worker client: no SharedArrayBuffer or cross-origin isolation required. */
|
|
36
|
+
export async function createWorkerVerifier(options = {}) {
|
|
37
|
+
const worker = options.worker ?? new Worker(options.workerURL ?? new URL('./worker.js', import.meta.url), { type: 'module' });
|
|
38
|
+
const pending = new Map();
|
|
39
|
+
let sequence = 0;
|
|
40
|
+
let closed = false;
|
|
41
|
+
const failAll = (error) => {
|
|
42
|
+
for (const { reject } of pending.values()) reject(error);
|
|
43
|
+
pending.clear();
|
|
44
|
+
};
|
|
45
|
+
const onMessage = ({ data }) => {
|
|
46
|
+
const entry = pending.get(data?.id);
|
|
47
|
+
if (!entry) return;
|
|
48
|
+
pending.delete(data.id);
|
|
49
|
+
if (data.error) {
|
|
50
|
+
const error = new Error(data.error.message || 'Verifier worker failed');
|
|
51
|
+
error.name = data.error.name || 'Error';
|
|
52
|
+
entry.reject(error);
|
|
53
|
+
} else entry.resolve(data.result);
|
|
54
|
+
};
|
|
55
|
+
const onError = (event) => {
|
|
56
|
+
failAll(new Error(event.message || 'Verifier worker failed'));
|
|
57
|
+
dispose();
|
|
58
|
+
};
|
|
59
|
+
worker.addEventListener('message', onMessage);
|
|
60
|
+
worker.addEventListener('error', onError);
|
|
61
|
+
worker.addEventListener('messageerror', onError);
|
|
62
|
+
const call = (method, payload) => new Promise((resolve, reject) => {
|
|
63
|
+
if (closed) return reject(new Error('Verifier worker is closed'));
|
|
64
|
+
const id = ++sequence;
|
|
65
|
+
pending.set(id, { resolve, reject });
|
|
66
|
+
try { worker.postMessage({ id, method, ...payload }); }
|
|
67
|
+
catch (error) { pending.delete(id); reject(error); }
|
|
68
|
+
});
|
|
69
|
+
const dispose = () => {
|
|
70
|
+
closed = true;
|
|
71
|
+
worker.removeEventListener('message', onMessage);
|
|
72
|
+
worker.removeEventListener('error', onError);
|
|
73
|
+
worker.removeEventListener('messageerror', onError);
|
|
74
|
+
worker.terminate();
|
|
75
|
+
failAll(new Error('Verifier worker is closed'));
|
|
76
|
+
};
|
|
77
|
+
try { await call('init', { options: { wasm: options.wasm } }); }
|
|
78
|
+
catch (error) { dispose(); throw error; }
|
|
79
|
+
return Object.freeze({
|
|
80
|
+
verify: (request) => call('verify', { request }),
|
|
81
|
+
verifyScriptGroup: async (request, group) => call('verify', { request: { ...request, script_group: validateGroup(group) } }),
|
|
82
|
+
dispose,
|
|
83
|
+
});
|
|
84
|
+
}
|
package/js/worker.js
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { createVerifier } from './index.js';
|
|
2
|
+
|
|
3
|
+
// The event queue naturally serializes synchronous WASM verification. Send errors
|
|
4
|
+
// as plain objects because browser Error structured-cloning differs by runtime.
|
|
5
|
+
let verifier;
|
|
6
|
+
self.addEventListener('message', async ({ data }) => {
|
|
7
|
+
const { id, method } = data ?? {};
|
|
8
|
+
try {
|
|
9
|
+
let result;
|
|
10
|
+
if (method === 'init') {
|
|
11
|
+
if (verifier) throw new Error('Verifier already initialized');
|
|
12
|
+
verifier = createVerifier(data.options);
|
|
13
|
+
await verifier;
|
|
14
|
+
result = null;
|
|
15
|
+
} else if (method === 'verify') {
|
|
16
|
+
if (!verifier) throw new Error('Initialize the verifier first');
|
|
17
|
+
result = await (await verifier).verify(data.request);
|
|
18
|
+
} else throw new Error(`Unknown worker method: ${method}`);
|
|
19
|
+
self.postMessage({ id, result });
|
|
20
|
+
} catch (error) {
|
|
21
|
+
self.postMessage({ id, error: { name: error.name, message: error.message } });
|
|
22
|
+
}
|
|
23
|
+
});
|
package/package.json
CHANGED
|
@@ -1,6 +1,46 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ckb-vm-js",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Offline CKB transaction and script-group verification in WebAssembly",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"files": [
|
|
8
|
+
"js",
|
|
9
|
+
"pkg/*.js",
|
|
10
|
+
"pkg/*.wasm",
|
|
11
|
+
"pkg/*.d.ts",
|
|
12
|
+
"docs/*.md",
|
|
13
|
+
"crates/verifier/SCHEMA.md",
|
|
14
|
+
"THIRD_PARTY_NOTICES.md"
|
|
15
|
+
],
|
|
16
|
+
"exports": {
|
|
17
|
+
".": {
|
|
18
|
+
"types": "./js/index.d.ts",
|
|
19
|
+
"import": "./js/index.js"
|
|
20
|
+
},
|
|
21
|
+
"./worker": "./js/worker.js",
|
|
22
|
+
"./wasm": "./pkg/ckb_wasm_verifier_bg.wasm"
|
|
23
|
+
},
|
|
24
|
+
"scripts": {
|
|
25
|
+
"test": "node --test tests/js/*.test.js",
|
|
26
|
+
"test:wasm": "node --test tests/js/wasm.integration.js",
|
|
27
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
28
|
+
"test:browser": "playwright test",
|
|
29
|
+
"test:differential": "node --test tests/js/differential.integration.js"
|
|
30
|
+
},
|
|
31
|
+
"engines": {
|
|
32
|
+
"node": ">=20"
|
|
33
|
+
},
|
|
34
|
+
"sideEffects": false,
|
|
35
|
+
"publishConfig": {
|
|
36
|
+
"access": "public"
|
|
37
|
+
},
|
|
38
|
+
"devDependencies": {
|
|
39
|
+
"@playwright/test": "1.56.1",
|
|
40
|
+
"typescript": "5.9.3"
|
|
41
|
+
},
|
|
42
|
+
"repository": {
|
|
43
|
+
"type": "git",
|
|
44
|
+
"url": "git+https://github.com/Hanssen0-Alter-Ego/ckb-vm-js.git"
|
|
45
|
+
}
|
|
46
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/* tslint:disable */
|
|
2
|
+
/* eslint-disable */
|
|
3
|
+
/**
|
|
4
|
+
* Returns structured JSON on both success and failure. Numbers are lossless hex strings.
|
|
5
|
+
* `scope=transaction` means validity relative to supplied context, not network acceptance.
|
|
6
|
+
*/
|
|
7
|
+
export function verify(request_json: string): string;
|
|
8
|
+
|
|
9
|
+
export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;
|
|
10
|
+
|
|
11
|
+
export interface InitOutput {
|
|
12
|
+
readonly memory: WebAssembly.Memory;
|
|
13
|
+
readonly verify: (a: number, b: number) => [number, number];
|
|
14
|
+
readonly rustsecp256k1_v0_10_0_context_create: (a: number) => number;
|
|
15
|
+
readonly rustsecp256k1_v0_10_0_context_destroy: (a: number) => void;
|
|
16
|
+
readonly rustsecp256k1_v0_10_0_default_error_callback_fn: (a: number, b: number) => void;
|
|
17
|
+
readonly rustsecp256k1_v0_10_0_default_illegal_callback_fn: (a: number, b: number) => void;
|
|
18
|
+
readonly __wbindgen_externrefs: WebAssembly.Table;
|
|
19
|
+
readonly __wbindgen_malloc: (a: number, b: number) => number;
|
|
20
|
+
readonly __wbindgen_realloc: (a: number, b: number, c: number, d: number) => number;
|
|
21
|
+
readonly __wbindgen_free: (a: number, b: number, c: number) => void;
|
|
22
|
+
readonly __wbindgen_start: () => void;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export type SyncInitInput = BufferSource | WebAssembly.Module;
|
|
26
|
+
/**
|
|
27
|
+
* Instantiates the given `module`, which can either be bytes or
|
|
28
|
+
* a precompiled `WebAssembly.Module`.
|
|
29
|
+
*
|
|
30
|
+
* @param {{ module: SyncInitInput }} module - Passing `SyncInitInput` directly is deprecated.
|
|
31
|
+
*
|
|
32
|
+
* @returns {InitOutput}
|
|
33
|
+
*/
|
|
34
|
+
export function initSync(module: { module: SyncInitInput } | SyncInitInput): InitOutput;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* If `module_or_path` is {RequestInfo} or {URL}, makes a request and
|
|
38
|
+
* for everything else, calls `WebAssembly.instantiate` directly.
|
|
39
|
+
*
|
|
40
|
+
* @param {{ module_or_path: InitInput | Promise<InitInput> }} module_or_path - Passing `InitInput` directly is deprecated.
|
|
41
|
+
*
|
|
42
|
+
* @returns {Promise<InitOutput>}
|
|
43
|
+
*/
|
|
44
|
+
export default function __wbg_init (module_or_path?: { module_or_path: InitInput | Promise<InitInput> } | InitInput | Promise<InitInput>): Promise<InitOutput>;
|