@remetra/sdk 0.0.0-stage → 0.1.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 +201 -0
- package/README.md +83 -2
- package/agent/ebpf-meter.js +86 -0
- package/backend/lib.js +90 -0
- package/bin/remetra-ebpf.js +3 -0
- package/index.d.ts +57 -0
- package/index.js +4 -0
- package/package.json +43 -4
- package/sdk/meter.js +87 -0
- package/zk/build/files.json +16 -0
- package/zk/build/verification_key.json +63 -0
- package/zk/index.js +96 -0
- package/zk/receipt.circom +47 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,84 @@
|
|
|
1
|
-
#
|
|
1
|
+
# remetra
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Metering SDK for [Remetra](https://remetra.xyz), an opt-in royalty network for software dependencies.
|
|
4
|
+
|
|
5
|
+
Your app counts how much it uses each registered dependency and sends signed usage receipts.
|
|
6
|
+
Creators are paid from your app's vault in USDC on Solana. **Only counts leave your process:** no
|
|
7
|
+
arguments, results, payloads or user data.
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
npm install @remetra/sdk
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Use
|
|
14
|
+
|
|
15
|
+
Register your app in the [Remetra app](https://remetra.xyz/app) to get an app id and a metering key.
|
|
16
|
+
|
|
17
|
+
```js
|
|
18
|
+
const { createMeter } = require('@remetra/sdk');
|
|
19
|
+
|
|
20
|
+
const meter = await createMeter({
|
|
21
|
+
appId: '9f2c41d07ab3e615',
|
|
22
|
+
secretKey: process.env.REMETRA_METER_KEY, // the metering key, never your wallet
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
// Wrap once, then use the module exactly as before.
|
|
26
|
+
const pdf = meter.wrap('@northwind/pdf-render', require('@northwind/pdf-render'));
|
|
27
|
+
await pdf.render(invoice); // counted as one call
|
|
28
|
+
|
|
29
|
+
// On shutdown
|
|
30
|
+
await meter.stop();
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Receipts are sent every minute. If one is rejected or the network is down, the counts are kept and
|
|
34
|
+
sent with the next one.
|
|
35
|
+
|
|
36
|
+
### WebAssembly
|
|
37
|
+
|
|
38
|
+
```js
|
|
39
|
+
const codec = await meter.instantiateWasm('img-codec', wasmBytes, imports);
|
|
40
|
+
codec.encode(ptr, len); // every exported function is counted
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
### Native libraries (Linux)
|
|
44
|
+
|
|
45
|
+
The eBPF agent counts calls into shared libraries from the kernel, with no change to your app.
|
|
46
|
+
It needs root and [bpftrace](https://github.com/bpftrace/bpftrace).
|
|
47
|
+
|
|
48
|
+
```sh
|
|
49
|
+
sudo npx remetra-ebpf config.json
|
|
50
|
+
```
|
|
51
|
+
|
|
52
|
+
The config format is in the [docs](https://remetra.xyz/docs#ebpf).
|
|
53
|
+
|
|
54
|
+
## Zero-knowledge receipts
|
|
55
|
+
|
|
56
|
+
Each component's calls are kept in sixteen private buckets, by function name. Every receipt carries a
|
|
57
|
+
proof that the billed total is exactly the sum of those buckets, without revealing the breakdown.
|
|
58
|
+
|
|
59
|
+
The proving files (about 18 MB) are downloaded once on first use, checked against SHA-256 hashes
|
|
60
|
+
pinned in this package, and cached in `~/.cache/remetra`. Set `REMETRA_ZK_DIR` to choose another
|
|
61
|
+
folder. A proof takes a few seconds per component per receipt.
|
|
62
|
+
|
|
63
|
+
## Options
|
|
64
|
+
|
|
65
|
+
| Option | Default | Meaning |
|
|
66
|
+
|---|---|---|
|
|
67
|
+
| `appId` | required | Your app's id |
|
|
68
|
+
| `secretKey` | required | The metering key issued at registration |
|
|
69
|
+
| `endpoint` | `https://remetra.xyz` | Base address of the API |
|
|
70
|
+
| `flushMs` | `60000` | How often a receipt is sent |
|
|
71
|
+
| `revenue` | `() => 0` | Revenue in micro-dollars since the last receipt, for revenue-share components |
|
|
72
|
+
| `prove` | `'auto'` | `true` requires a proof, `false` sends none |
|
|
73
|
+
|
|
74
|
+
## What is and is not verified
|
|
75
|
+
|
|
76
|
+
A proof shows a receipt is internally consistent. It does not show that an app counted honestly in
|
|
77
|
+
the first place: the SDK runs inside your app, so its counts are your app's own word. The
|
|
78
|
+
[trust model](https://remetra.xyz/docs#trust) spells this out.
|
|
79
|
+
|
|
80
|
+
Remetra is in early development and has not been audited.
|
|
81
|
+
|
|
82
|
+
## License
|
|
83
|
+
|
|
84
|
+
Apache-2.0
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// Remetra eBPF metering agent (Linux, needs root).
|
|
3
|
+
//
|
|
4
|
+
// Counts calls into native components from outside the application: the kernel fires a uprobe each
|
|
5
|
+
// time a watched function in a shared library or binary is entered, and bumps a counter in a BPF map.
|
|
6
|
+
// The app's code, arguments and data are never read; only "function X was entered N times" leaves
|
|
7
|
+
// the kernel. Counts are sent through the same signed (and zero-knowledge) receipts as the SDK.
|
|
8
|
+
//
|
|
9
|
+
// sudo node agent/ebpf-meter.js agent/config.json
|
|
10
|
+
//
|
|
11
|
+
// config.json:
|
|
12
|
+
// { "endpoint": "https://remetra.xyz", "appId": "…", "secretKey": "…", (or env REMETRA_METER_KEY)
|
|
13
|
+
// "intervalSeconds": 60,
|
|
14
|
+
// "pid": 1234, optional: only this process; or "comm": "node" for a process name
|
|
15
|
+
// "probes": [ { "component": "fast-zlib", "binary": "/usr/lib/x86_64-linux-gnu/libz.so.1", "functions": ["deflate", "inflate"] } ] }
|
|
16
|
+
// Uses bpftrace to load the BPF program (apt install bpftrace).
|
|
17
|
+
const fs = require('fs');
|
|
18
|
+
const { spawn } = require('child_process');
|
|
19
|
+
const { createMeter } = require('../sdk/meter');
|
|
20
|
+
|
|
21
|
+
const SAFE = /^[A-Za-z0-9_.$@*?\[\]-]+$/;
|
|
22
|
+
function program(cfg) {
|
|
23
|
+
const filter = cfg.pid ? `/pid == ${Number(cfg.pid)}/ ` : cfg.comm ? `/comm == "${String(cfg.comm).replace(/[^\w.-]/g, '')}"/ ` : '';
|
|
24
|
+
const lines = [];
|
|
25
|
+
cfg.probes.forEach((p, n) => {
|
|
26
|
+
if (!fs.existsSync(p.binary)) throw new Error(`binary not found: ${p.binary}`);
|
|
27
|
+
p.functions.forEach((f, k) => {
|
|
28
|
+
if (!SAFE.test(f)) throw new Error(`unsupported function name: ${f}`);
|
|
29
|
+
lines.push(`uprobe:${p.binary}:${f} ${filter}{ @c[${n}, ${k}] = count(); }`);
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
lines.push(`interval:s:${Math.max(1, Number(cfg.intervalSeconds) || 60)} { print(@c); clear(@c); }`);
|
|
33
|
+
lines.push('END { print(@c); clear(@c); }');
|
|
34
|
+
return lines.join('\n');
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// bpftrace -f json prints maps as {"type":"map","data":{"@c":{"0,1":12,…}}} (probe index, function index)
|
|
38
|
+
function parse(line, probes) {
|
|
39
|
+
let m; try { m = JSON.parse(line); } catch { return []; }
|
|
40
|
+
if (m.type !== 'map' || !m.data || !m.data['@c']) return [];
|
|
41
|
+
const out = [];
|
|
42
|
+
const walk = (key, v) => {
|
|
43
|
+
const [n, k] = String(key).split(',').map((x) => Number(x.trim()));
|
|
44
|
+
if (probes[n] && probes[n].functions[k] !== undefined && Number.isSafeInteger(v) && v > 0) out.push({ component: probes[n].component, fn: probes[n].functions[k], count: v });
|
|
45
|
+
};
|
|
46
|
+
const data = m.data['@c'];
|
|
47
|
+
if (Array.isArray(data)) for (const [k, v] of data) walk(Array.isArray(k) ? k.join(',') : k, v); // newer bpftrace: [[keys], value] pairs
|
|
48
|
+
else for (const [k, v] of Object.entries(data)) walk(k, v);
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
async function main() {
|
|
53
|
+
const file = process.argv[2];
|
|
54
|
+
if (!file) { console.error('usage: sudo remetra-ebpf config.json'); process.exit(2); }
|
|
55
|
+
const cfg = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
56
|
+
cfg.secretKey ||= process.env.REMETRA_METER_KEY;
|
|
57
|
+
if (!Array.isArray(cfg.probes) || !cfg.probes.length) throw new Error('config needs at least one probe');
|
|
58
|
+
const prog = program(cfg);
|
|
59
|
+
if (process.argv.includes('--print')) { console.log(prog); return; }
|
|
60
|
+
|
|
61
|
+
// some systems (WSL, minimal containers) do not mount the kernel's tracing filesystem by default
|
|
62
|
+
if (!fs.existsSync('/sys/kernel/tracing/available_events')) require('child_process').spawnSync('mount', ['-t', 'tracefs', 'tracefs', '/sys/kernel/tracing'], { stdio: 'ignore' });
|
|
63
|
+
|
|
64
|
+
const meter = await createMeter({ endpoint: cfg.endpoint, appId: cfg.appId, secretKey: cfg.secretKey, flushMs: 24 * 3600 * 1000, prove: cfg.prove ?? 'auto' });
|
|
65
|
+
const bpf = spawn(cfg.bpftrace || 'bpftrace', ['-q', '-B', 'line', '-f', 'json', '-e', prog], { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
66
|
+
let buf = '', sending = Promise.resolve(), errText = '';
|
|
67
|
+
const send = () => { sending = sending.then(() => meter.flush()).then((r) => { if (r) console.log(`receipt ${r.seq}: ${r.metered} component(s) metered, ${r.proved} proved`); }).catch((e) => console.error(e.message)); return sending; };
|
|
68
|
+
bpf.stdout.on('data', (d) => {
|
|
69
|
+
buf += d;
|
|
70
|
+
let nl; let got = false;
|
|
71
|
+
while ((nl = buf.indexOf('\n')) >= 0) {
|
|
72
|
+
for (const c of parse(buf.slice(0, nl), cfg.probes)) { meter.record(c.component, c.fn, c.count); got = true; }
|
|
73
|
+
buf = buf.slice(nl + 1);
|
|
74
|
+
}
|
|
75
|
+
if (got) send();
|
|
76
|
+
});
|
|
77
|
+
bpf.stderr.on('data', (d) => { errText += d; });
|
|
78
|
+
bpf.on('error', (e) => { console.error('could not start bpftrace:', e.message); process.exit(1); });
|
|
79
|
+
// 'close' (not 'exit') fires after the last output has been read
|
|
80
|
+
bpf.on('close', async (code) => { await send(); await require('../zk').close(); if (code) console.error(`bpftrace exited with ${code}: ${errText.trim().slice(0, 400)}`); process.exit(code || 0); });
|
|
81
|
+
const stop = () => bpf.kill('SIGINT'); // bpftrace runs END, printing the last counts, then exits
|
|
82
|
+
process.on('SIGINT', stop); process.on('SIGTERM', stop);
|
|
83
|
+
console.log(`eBPF metering started: ${cfg.probes.map((p) => `${p.component} (${p.functions.length} function${p.functions.length === 1 ? '' : 's'})`).join(', ')}${meter.proving ? ' · zero-knowledge receipts on' : ''}`);
|
|
84
|
+
}
|
|
85
|
+
if (require.main === module) main().catch((e) => { console.error('agent failed:', e.message); process.exit(1); });
|
|
86
|
+
module.exports = { program, parse, main };
|
package/backend/lib.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Shared primitives: base58, canonical JSON, ed25519 (Solana-compatible keys), Merkle trees.
|
|
2
|
+
const crypto = require('crypto');
|
|
3
|
+
|
|
4
|
+
const A = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
|
|
5
|
+
function b58enc(buf) {
|
|
6
|
+
buf = Buffer.from(buf);
|
|
7
|
+
let n = buf.length ? BigInt('0x' + buf.toString('hex')) : 0n, s = '';
|
|
8
|
+
while (n > 0n) { s = A[Number(n % 58n)] + s; n /= 58n; }
|
|
9
|
+
for (const b of buf) { if (b === 0) s = '1' + s; else break; }
|
|
10
|
+
return s;
|
|
11
|
+
}
|
|
12
|
+
function b58dec(str) {
|
|
13
|
+
if (typeof str !== 'string' || !str.length || str.length > 128) throw new Error('bad base58');
|
|
14
|
+
let n = 0n;
|
|
15
|
+
for (const ch of str) { const i = A.indexOf(ch); if (i < 0) throw new Error('bad base58'); n = n * 58n + BigInt(i); }
|
|
16
|
+
let hex = n.toString(16); if (hex.length % 2) hex = '0' + hex;
|
|
17
|
+
const body = n === 0n ? Buffer.alloc(0) : Buffer.from(hex, 'hex');
|
|
18
|
+
let z = 0; for (const ch of str) { if (ch === '1') z++; else break; }
|
|
19
|
+
return Buffer.concat([Buffer.alloc(z), body]);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// Deterministic JSON: object keys sorted, so signer and verifier hash identical bytes.
|
|
23
|
+
function canonical(v) {
|
|
24
|
+
if (v === null || typeof v !== 'object') return JSON.stringify(v);
|
|
25
|
+
if (Array.isArray(v)) return '[' + v.map(canonical).join(',') + ']';
|
|
26
|
+
return '{' + Object.keys(v).sort().map((k) => JSON.stringify(k) + ':' + canonical(v[k])).join(',') + '}';
|
|
27
|
+
}
|
|
28
|
+
const sha256 = (data) => crypto.createHash('sha256').update(data).digest();
|
|
29
|
+
const sha256hex = (data) => sha256(data).toString('hex');
|
|
30
|
+
const message = (payload) => Buffer.from('REMETRA:' + canonical(payload), 'utf8');
|
|
31
|
+
|
|
32
|
+
const SPKI = Buffer.from('302a300506032b6570032100', 'hex');
|
|
33
|
+
const PKCS8 = Buffer.from('302e020100300506032b657004220420', 'hex');
|
|
34
|
+
function isPubkey(s) { try { return b58dec(s).length === 32; } catch { return false; } }
|
|
35
|
+
function verify(pubkeyB58, payload, sigB58) {
|
|
36
|
+
try {
|
|
37
|
+
const pub = b58dec(pubkeyB58), sig = b58dec(sigB58);
|
|
38
|
+
if (pub.length !== 32 || sig.length !== 64) return false;
|
|
39
|
+
const key = crypto.createPublicKey({ key: Buffer.concat([SPKI, pub]), format: 'der', type: 'spki' });
|
|
40
|
+
return crypto.verify(null, message(payload), key, sig);
|
|
41
|
+
} catch { return false; }
|
|
42
|
+
}
|
|
43
|
+
// A key is a 32-byte seed, base58 encoded. Used by the SDK, the demo script and tests.
|
|
44
|
+
function keypair(seedB58) {
|
|
45
|
+
const seed = seedB58 ? b58dec(seedB58) : crypto.randomBytes(32);
|
|
46
|
+
if (seed.length !== 32) throw new Error('seed must be 32 bytes');
|
|
47
|
+
const priv = crypto.createPrivateKey({ key: Buffer.concat([PKCS8, seed]), format: 'der', type: 'pkcs8' });
|
|
48
|
+
const pub = crypto.createPublicKey(priv).export({ format: 'der', type: 'spki' }).subarray(-32);
|
|
49
|
+
return { seed: b58enc(seed), pubkey: b58enc(pub), sign: (payload) => b58enc(crypto.sign(null, message(payload), priv)) };
|
|
50
|
+
}
|
|
51
|
+
function signed(kp, action, data = {}) {
|
|
52
|
+
const payload = { ...data, action, ts: Math.floor(Date.now() / 1000), nonce: crypto.randomBytes(12).toString('hex') };
|
|
53
|
+
return { payload, pubkey: kp.pubkey, sig: kp.sign(payload) };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Merkle tree over payout leaves. Odd nodes are paired with themselves.
|
|
57
|
+
// Binary leaf, byte-identical to the Solana program (onchain/programs/remetra/src/lib.rs):
|
|
58
|
+
// sha256("remetra-payout" || epoch u64 LE || wallet 32 bytes || amount u64 LE)
|
|
59
|
+
const u64le = (n) => { const b = Buffer.alloc(8); b.writeBigUInt64LE(BigInt(n)); return b; };
|
|
60
|
+
function leafHash(epoch, wallet, amountMicro) {
|
|
61
|
+
const key = b58dec(wallet);
|
|
62
|
+
if (key.length !== 32) throw new Error('wallet must be a 32-byte public key');
|
|
63
|
+
return sha256(Buffer.concat([Buffer.from('remetra-payout'), u64le(epoch), key, u64le(amountMicro)]));
|
|
64
|
+
}
|
|
65
|
+
function merkleLevels(leaves) {
|
|
66
|
+
const levels = [leaves.length ? leaves : [sha256('remetra-empty')]];
|
|
67
|
+
while (levels[levels.length - 1].length > 1) {
|
|
68
|
+
const cur = levels[levels.length - 1], next = [];
|
|
69
|
+
for (let i = 0; i < cur.length; i += 2) next.push(sha256(Buffer.concat([cur[i], cur[i + 1] || cur[i]])));
|
|
70
|
+
levels.push(next);
|
|
71
|
+
}
|
|
72
|
+
return levels;
|
|
73
|
+
}
|
|
74
|
+
const merkleRoot = (leaves) => merkleLevels(leaves).at(-1)[0].toString('hex');
|
|
75
|
+
function merkleProof(leaves, index) {
|
|
76
|
+
const levels = merkleLevels(leaves), proof = [];
|
|
77
|
+
for (let l = 0; l < levels.length - 1; l++) {
|
|
78
|
+
const cur = levels[l], sib = index ^ 1;
|
|
79
|
+
proof.push({ hash: (cur[sib] || cur[index]).toString('hex'), left: sib < index });
|
|
80
|
+
index >>= 1;
|
|
81
|
+
}
|
|
82
|
+
return proof;
|
|
83
|
+
}
|
|
84
|
+
function merkleVerify(leaf, proof, rootHex) {
|
|
85
|
+
let h = leaf;
|
|
86
|
+
for (const p of proof) { const s = Buffer.from(p.hash, 'hex'); h = sha256(p.left ? Buffer.concat([s, h]) : Buffer.concat([h, s])); }
|
|
87
|
+
return h.toString('hex') === rootHex;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
module.exports = { b58enc, b58dec, canonical, sha256, sha256hex, message, verify, isPubkey, keypair, signed, leafHash, merkleRoot, merkleProof, merkleVerify };
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/** Options for {@link createMeter}. */
|
|
2
|
+
export interface MeterOptions {
|
|
3
|
+
/** The app's 16-character id, from the "My app" tab. */
|
|
4
|
+
appId: string;
|
|
5
|
+
/** The metering key issued when the app was registered. Never your wallet key. */
|
|
6
|
+
secretKey: string;
|
|
7
|
+
/** Base address of the Remetra API. Defaults to https://remetra.xyz */
|
|
8
|
+
endpoint?: string;
|
|
9
|
+
/** How often a receipt is sent, in milliseconds. Defaults to 60000. */
|
|
10
|
+
flushMs?: number;
|
|
11
|
+
/** Revenue in micro-dollars since the last receipt. Only needed for revenue-share components. */
|
|
12
|
+
revenue?: () => number | Promise<number>;
|
|
13
|
+
/** 'auto' (default) attaches a zero-knowledge proof when possible, true requires one, false sends none. */
|
|
14
|
+
prove?: 'auto' | boolean;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** What the API answers when it accepts a receipt. */
|
|
18
|
+
export interface ReceiptResult {
|
|
19
|
+
accepted: true;
|
|
20
|
+
seq: number;
|
|
21
|
+
/** Items counted: registered components that are in the app's manifest. */
|
|
22
|
+
metered: number;
|
|
23
|
+
/** Items skipped: unregistered, or not in the manifest. */
|
|
24
|
+
ignored: number;
|
|
25
|
+
/** Items whose zero-knowledge proof was verified. */
|
|
26
|
+
proved: number;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface Meter {
|
|
30
|
+
/** Returns the module with every function call counted against `name`. */
|
|
31
|
+
wrap<T extends object>(name: string, target: T): T;
|
|
32
|
+
/** Returns a WebAssembly instance's exports with every exported function counted. */
|
|
33
|
+
wrapWasm<T extends Record<string, unknown>>(name: string, instance: WebAssembly.Instance | T): T;
|
|
34
|
+
/** Instantiates a WebAssembly module and returns its metered exports. */
|
|
35
|
+
instantiateWasm(name: string, bytes: BufferSource, imports?: WebAssembly.Imports): Promise<Record<string, any>>;
|
|
36
|
+
/** Adds `n` calls by hand, for usage the wrappers cannot see. */
|
|
37
|
+
record(name: string, key?: string, n?: number): void;
|
|
38
|
+
/** Sends a receipt now. Resolves to null when there is nothing to send. */
|
|
39
|
+
flush(): Promise<ReceiptResult | null>;
|
|
40
|
+
/** Stops the timer and sends a final receipt. Call on shutdown. */
|
|
41
|
+
stop(): Promise<ReceiptResult | null>;
|
|
42
|
+
/** The metering key's public half. */
|
|
43
|
+
readonly pubkey: string;
|
|
44
|
+
/** Whether receipts carry zero-knowledge proofs. */
|
|
45
|
+
readonly proving: boolean;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Starts metering for one app. Only counts leave the process: no arguments, results or user data. */
|
|
49
|
+
export function createMeter(options: MeterOptions): Promise<Meter>;
|
|
50
|
+
|
|
51
|
+
export interface Keypair { seed: string; pubkey: string; sign(payload: object): string; }
|
|
52
|
+
export interface Envelope { payload: Record<string, unknown>; pubkey: string; sig: string; }
|
|
53
|
+
/** An ed25519 key (base58), new or restored from its seed. */
|
|
54
|
+
export function keypair(seed?: string): Keypair;
|
|
55
|
+
/** A signed request envelope for the Remetra API. */
|
|
56
|
+
export function signed(key: Keypair, action: string, fields?: Record<string, unknown>): Envelope;
|
|
57
|
+
export function verify(pubkey: string, payload: object, sig: string): boolean;
|
package/index.js
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@remetra/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Metering SDK for Remetra: count calls into royalty-bearing dependencies and send signed, zero-knowledge usage receipts.",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"types": "index.d.ts",
|
|
8
|
+
"bin": {
|
|
9
|
+
"remetra-ebpf": "bin/remetra-ebpf.js"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"index.js",
|
|
13
|
+
"index.d.ts",
|
|
14
|
+
"sdk",
|
|
15
|
+
"zk",
|
|
16
|
+
"backend",
|
|
17
|
+
"agent",
|
|
18
|
+
"bin"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=18"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"snarkjs": "^0.7.5"
|
|
25
|
+
},
|
|
26
|
+
"keywords": [
|
|
27
|
+
"remetra",
|
|
28
|
+
"solana",
|
|
29
|
+
"royalties",
|
|
30
|
+
"metering",
|
|
31
|
+
"dependencies",
|
|
32
|
+
"zero-knowledge",
|
|
33
|
+
"ebpf",
|
|
34
|
+
"webassembly",
|
|
35
|
+
"usdc"
|
|
36
|
+
],
|
|
37
|
+
"homepage": "https://remetra.xyz/docs",
|
|
38
|
+
"repository": {
|
|
39
|
+
"type": "git",
|
|
40
|
+
"url": "git+https://github.com/remetrasolana/remetra.git"
|
|
41
|
+
},
|
|
42
|
+
"bugs": {
|
|
43
|
+
"url": "https://github.com/remetrasolana/remetra/issues"
|
|
44
|
+
}
|
|
45
|
+
}
|
package/sdk/meter.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Remetra metering SDK for Node. Counts calls into registered components and periodically
|
|
2
|
+
// sends a signed usage receipt. Only counts leave the process: no arguments, results or user data.
|
|
3
|
+
//
|
|
4
|
+
// const { createMeter } = require('./sdk/meter');
|
|
5
|
+
// const meter = await createMeter({ endpoint: 'http://localhost:8080', appId, secretKey: process.env.REMETRA_METER_KEY });
|
|
6
|
+
// const pdf = meter.wrap('@northwind/pdf-render', require('@northwind/pdf-render')); // JS modules
|
|
7
|
+
// const img = await meter.instantiateWasm('img-codec', wasmBytes, imports); // WebAssembly modules
|
|
8
|
+
// ...use them as normal...
|
|
9
|
+
// await meter.flush(); // also runs on an interval
|
|
10
|
+
//
|
|
11
|
+
// Zero-knowledge receipts: each component's calls are kept in private buckets (by function name).
|
|
12
|
+
// When the proving files are present (zk/build), every receipt item carries a proof that its total
|
|
13
|
+
// is the sum of a committed bucket breakdown, without revealing the breakdown. See zk/index.js.
|
|
14
|
+
const L = require('../backend/lib');
|
|
15
|
+
const zk = require('../zk');
|
|
16
|
+
|
|
17
|
+
async function createMeter({ endpoint = 'https://remetra.xyz', appId, secretKey, flushMs = 60000, revenue = () => 0, prove = 'auto' }) {
|
|
18
|
+
if (!appId || !secretKey) throw new Error('appId and secretKey are required');
|
|
19
|
+
const useZk = prove === true || (prove === 'auto' && zk.canProve());
|
|
20
|
+
if (prove === true && !zk.canProve()) throw new Error('zero-knowledge proving files are missing; build them with zk/build.sh');
|
|
21
|
+
const kp = L.keypair(secretKey), base = endpoint.replace(/\/+$/, '') + '/api';
|
|
22
|
+
const info = await (await fetch(`${base}/apps/${appId}`)).json();
|
|
23
|
+
if (info.error) throw new Error('REMETRA: ' + info.error);
|
|
24
|
+
let seq = info.lastSeq;
|
|
25
|
+
const counts = new Map(); // component -> { buckets: number[], since }
|
|
26
|
+
const entry = (name) => { if (!counts.has(name)) counts.set(name, { buckets: Array(zk.SLOTS).fill(0), since: Date.now() }); return counts.get(name); };
|
|
27
|
+
const slots = new Map();
|
|
28
|
+
const slot = (key) => { if (!slots.has(key)) slots.set(key, zk.bucket(key)); return slots.get(key); };
|
|
29
|
+
|
|
30
|
+
// The one counting primitive. `key` is the function or export name; it only picks a private bucket.
|
|
31
|
+
function record(name, key = '', n = 1) { entry(name).buckets[slot(String(key))] += n; }
|
|
32
|
+
|
|
33
|
+
function wrap(name, target) {
|
|
34
|
+
const e = entry(name);
|
|
35
|
+
let proxy = null; // declared before fn so the wrapper can compare against it safely
|
|
36
|
+
const fn = (f, self, b) => function (...args) { e.buckets[b]++; return f.apply(this === undefined || this === proxy ? self : this, args); };
|
|
37
|
+
if (typeof target === 'function') { const w = fn(target, undefined, slot(target.name || '')); return Object.assign(w, target); }
|
|
38
|
+
const cache = new Map();
|
|
39
|
+
proxy = new Proxy(target, { get(t, k, r) {
|
|
40
|
+
const v = Reflect.get(t, k, r);
|
|
41
|
+
if (typeof v !== 'function') return v;
|
|
42
|
+
if (!cache.has(k)) cache.set(k, fn(v, t, slot(String(k))));
|
|
43
|
+
return cache.get(k);
|
|
44
|
+
} });
|
|
45
|
+
return proxy;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// WebAssembly: meter every exported function of an instance. Memories, tables and globals pass through untouched.
|
|
49
|
+
function wrapWasm(name, instance) {
|
|
50
|
+
const e = entry(name), src = instance.exports || instance, out = {};
|
|
51
|
+
for (const [k, v] of Object.entries(src)) {
|
|
52
|
+
if (typeof v !== 'function') { out[k] = v; continue; }
|
|
53
|
+
const b = slot(k);
|
|
54
|
+
out[k] = (...args) => { e.buckets[b]++; return v(...args); };
|
|
55
|
+
}
|
|
56
|
+
return Object.freeze(out);
|
|
57
|
+
}
|
|
58
|
+
async function instantiateWasm(name, bytes, imports = {}) {
|
|
59
|
+
const { instance } = await WebAssembly.instantiate(bytes, imports);
|
|
60
|
+
return wrapWasm(name, instance);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
async function flush() {
|
|
64
|
+
const t = Date.now(), items = [], next = seq + 1;
|
|
65
|
+
for (const [component, e] of counts) {
|
|
66
|
+
const sent = e.buckets.slice(), calls = sent.reduce((a, b) => a + b, 0), seconds = Math.floor((t - e.since) / 1000);
|
|
67
|
+
if (!calls && !seconds) continue;
|
|
68
|
+
const item = { component, calls, seconds };
|
|
69
|
+
if (useZk && calls) { const p = await zk.prove(sent, zk.context(appId, next, component)); item.zk = { commitment: p.commitment, proof: p.proof }; }
|
|
70
|
+
items.push({ item, e, sent, seconds });
|
|
71
|
+
}
|
|
72
|
+
if (!items.length) return null;
|
|
73
|
+
const body = L.signed(kp, 'receipt.submit', { appId, seq: next, items: items.map((i) => i.item), revenueMicro: Math.max(0, Math.floor(Number(await revenue()) || 0)) });
|
|
74
|
+
const res = await fetch(`${base}/receipts`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
75
|
+
const out = await res.json();
|
|
76
|
+
if (!res.ok) throw new Error('Remetra receipt rejected: ' + out.error); // counts are kept and retried on the next flush
|
|
77
|
+
seq = next;
|
|
78
|
+
for (const i of items) { i.sent.forEach((n, b) => { i.e.buckets[b] -= n; }); i.e.since += i.seconds * 1000; }
|
|
79
|
+
return out;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const timer = setInterval(() => flush().catch((e) => console.error(e.message)), flushMs);
|
|
83
|
+
timer.unref();
|
|
84
|
+
return { wrap, wrapWasm, instantiateWasm, record, flush, stop: async () => { clearInterval(timer); return flush(); }, pubkey: kp.pubkey, proving: useZk };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
module.exports = { createMeter };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": "v1",
|
|
3
|
+
"base": "https://remetra.xyz/zk",
|
|
4
|
+
"files": {
|
|
5
|
+
"wasm": {
|
|
6
|
+
"name": "receipt.wasm",
|
|
7
|
+
"size": 3142349,
|
|
8
|
+
"sha256": "104e2d590cfba50b53f26626504a2babfe6c49429622dba8a5a5d3b6259bf5ad"
|
|
9
|
+
},
|
|
10
|
+
"zkey": {
|
|
11
|
+
"name": "receipt.zkey",
|
|
12
|
+
"size": 15201932,
|
|
13
|
+
"sha256": "f82647ea3ce03dd3e0c9b83f09b6673e96f26e0e81f92aef4a27df4c82f7224c"
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
{
|
|
2
|
+
"protocol": "plonk",
|
|
3
|
+
"curve": "bn128",
|
|
4
|
+
"nPublic": 3,
|
|
5
|
+
"power": 13,
|
|
6
|
+
"k1": "2",
|
|
7
|
+
"k2": "3",
|
|
8
|
+
"Qm": [
|
|
9
|
+
"7533185188683265488484165464204945722867425047324831789986679099564628674714",
|
|
10
|
+
"2270629324687887350574334295529272654272008489250146033084930119754284327561",
|
|
11
|
+
"1"
|
|
12
|
+
],
|
|
13
|
+
"Ql": [
|
|
14
|
+
"328327289624292602123340464994707431542050299753766845892487054002865205478",
|
|
15
|
+
"3099509064232248894322404196919084009411772714471152453538453639520947791514",
|
|
16
|
+
"1"
|
|
17
|
+
],
|
|
18
|
+
"Qr": [
|
|
19
|
+
"6238339677034989706912242245787201776554668052903934070472977723370291970061",
|
|
20
|
+
"2276592072185623324645264106936567577804572715572038935340856800204351205943",
|
|
21
|
+
"1"
|
|
22
|
+
],
|
|
23
|
+
"Qo": [
|
|
24
|
+
"20979122888024976719462186367857454823639786472137569597266157112552458225947",
|
|
25
|
+
"13207791522792230548516541970394985038851111856323868854795056562254860921563",
|
|
26
|
+
"1"
|
|
27
|
+
],
|
|
28
|
+
"Qc": [
|
|
29
|
+
"319029779545061970782083792875116484286499458160183840726976697288482697718",
|
|
30
|
+
"8919305436435520335396808290116483613637724048092786108823887160372354743769",
|
|
31
|
+
"1"
|
|
32
|
+
],
|
|
33
|
+
"S1": [
|
|
34
|
+
"601503525897941037281658479870251824247166503495753492437107175734079721013",
|
|
35
|
+
"13367189105910197230294881181536393243318158168803444521502473094231358717466",
|
|
36
|
+
"1"
|
|
37
|
+
],
|
|
38
|
+
"S2": [
|
|
39
|
+
"7294833141287661625907409055194012128945049691624306561731034518978599607368",
|
|
40
|
+
"9294044327838886548464450578317998843962817214403886986373404647384009028687",
|
|
41
|
+
"1"
|
|
42
|
+
],
|
|
43
|
+
"S3": [
|
|
44
|
+
"1565212308942335850583842864316761918043658556759607980455629715978935371451",
|
|
45
|
+
"17194378503433974524587484820264775182151353937909386524450143470210909819346",
|
|
46
|
+
"1"
|
|
47
|
+
],
|
|
48
|
+
"X_2": [
|
|
49
|
+
[
|
|
50
|
+
"18253511544609001572866960948873128266198935669250718031100637619547827597184",
|
|
51
|
+
"10764647077472957448033591885865458661573660819003350325268673957890498500987"
|
|
52
|
+
],
|
|
53
|
+
[
|
|
54
|
+
"19756181390911900613508142947142748782977087973617411469215564659012323409872",
|
|
55
|
+
"15207030507740967976352749097256929091435606784526748170016829002013506957017"
|
|
56
|
+
],
|
|
57
|
+
[
|
|
58
|
+
"1",
|
|
59
|
+
"0"
|
|
60
|
+
]
|
|
61
|
+
],
|
|
62
|
+
"w": "197302210312744933010843010704445784068657690384188106020011018676818793232"
|
|
63
|
+
}
|
package/zk/index.js
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Zero-knowledge usage receipts: prove and verify (circuit: zk/receipt.circom, files: zk/build).
|
|
2
|
+
//
|
|
3
|
+
// What a proof establishes: the billed total is the sum of sixteen private per-function counts that
|
|
4
|
+
// are fixed by a public commitment. What it does not establish: that the app counted honestly in the
|
|
5
|
+
// first place. It makes a receipt internally consistent and later auditable without exposing the breakdown.
|
|
6
|
+
const fs = require('fs');
|
|
7
|
+
const path = require('path');
|
|
8
|
+
const crypto = require('crypto');
|
|
9
|
+
const os = require('os');
|
|
10
|
+
|
|
11
|
+
const DIR = path.join(__dirname, 'build');
|
|
12
|
+
const WASM = path.join(DIR, 'receipt.wasm'), ZKEY = path.join(DIR, 'receipt.zkey'), VKEY = path.join(DIR, 'verification_key.json');
|
|
13
|
+
const FILES = path.join(DIR, 'files.json'); // where to fetch the proving files, and the SHA-256 each must have
|
|
14
|
+
const SLOTS = 16, MAX = 2 ** 32;
|
|
15
|
+
|
|
16
|
+
let snark = null, vkey = null;
|
|
17
|
+
function lib() {
|
|
18
|
+
if (!snark) { try { snark = require('snarkjs'); } catch { throw new Error('snarkjs is not installed; run npm install'); } }
|
|
19
|
+
return snark;
|
|
20
|
+
}
|
|
21
|
+
const hasLib = () => { try { require.resolve('snarkjs'); return true; } catch { return false; } };
|
|
22
|
+
const canVerify = () => hasLib() && fs.existsSync(VKEY);
|
|
23
|
+
const haveLocal = () => fs.existsSync(WASM) && fs.existsSync(ZKEY);
|
|
24
|
+
const canProve = () => canVerify() && (haveLocal() || fs.existsSync(FILES));
|
|
25
|
+
|
|
26
|
+
// The proving files are large (about 18 MB), so the installed package does not carry them. They are
|
|
27
|
+
// fetched once, checked against the SHA-256 pinned in files.json, and cached. A file that does not
|
|
28
|
+
// match its hash is never used. Set REMETRA_ZK_DIR to choose the cache folder or to supply the files yourself.
|
|
29
|
+
let ready = null;
|
|
30
|
+
function provingFiles() {
|
|
31
|
+
if (haveLocal()) return Promise.resolve({ wasm: WASM, zkey: ZKEY });
|
|
32
|
+
ready ||= (async () => {
|
|
33
|
+
const m = JSON.parse(fs.readFileSync(FILES, 'utf8'));
|
|
34
|
+
const dir = process.env.REMETRA_ZK_DIR || path.join(os.homedir(), '.cache', 'remetra', 'zk-' + m.version);
|
|
35
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
36
|
+
const hashOf = (file) => new Promise((res, rej) => { const h = crypto.createHash('sha256'); fs.createReadStream(file).on('data', (d) => h.update(d)).on('end', () => res(h.digest('hex'))).on('error', rej); });
|
|
37
|
+
const out = {};
|
|
38
|
+
for (const [kind, f] of Object.entries(m.files)) {
|
|
39
|
+
const file = path.join(dir, f.name);
|
|
40
|
+
if (!fs.existsSync(file) || fs.statSync(file).size !== f.size || (await hashOf(file)) !== f.sha256) {
|
|
41
|
+
const res = await fetch(m.base + '/' + f.name);
|
|
42
|
+
if (!res.ok) throw new Error(`could not download ${f.name} (${res.status})`);
|
|
43
|
+
const bytes = Buffer.from(await res.arrayBuffer());
|
|
44
|
+
if (crypto.createHash('sha256').update(bytes).digest('hex') !== f.sha256) throw new Error(`${f.name} does not match its expected hash; refusing to use it`);
|
|
45
|
+
const tmp = file + '.' + process.pid + '.part';
|
|
46
|
+
fs.writeFileSync(tmp, bytes); fs.renameSync(tmp, file);
|
|
47
|
+
}
|
|
48
|
+
out[kind] = file;
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
})().catch((e) => { ready = null; throw e; });
|
|
52
|
+
return ready;
|
|
53
|
+
}
|
|
54
|
+
const key = () => (vkey ||= JSON.parse(fs.readFileSync(VKEY, 'utf8')));
|
|
55
|
+
|
|
56
|
+
const sha = (s) => crypto.createHash('sha256').update(s).digest();
|
|
57
|
+
const bucket = (name) => sha('remetra-bucket:' + name)[0] % SLOTS;
|
|
58
|
+
// 248 bits, so it always fits in the proof system's field
|
|
59
|
+
const context = (appId, seq, component) => (BigInt('0x' + sha(`remetra-receipt:${appId}:${seq}:${component}`).toString('hex')) >> 8n).toString();
|
|
60
|
+
|
|
61
|
+
async function prove(counts, ctx) {
|
|
62
|
+
if (counts.length !== SLOTS || counts.some((c) => !Number.isSafeInteger(c) || c < 0 || c >= MAX)) throw new Error('counts must be sixteen integers below 2^32');
|
|
63
|
+
const salt = BigInt('0x' + crypto.randomBytes(31).toString('hex')).toString();
|
|
64
|
+
const f = await provingFiles();
|
|
65
|
+
let out;
|
|
66
|
+
try { out = await lib()[key().protocol].fullProve({ counts: counts.map(String), salt, context: ctx }, f.wasm, f.zkey); }
|
|
67
|
+
catch (e) { ready = null; throw e; } // a damaged cached file: re-check (and re-download) on the next attempt
|
|
68
|
+
const { proof, publicSignals } = out;
|
|
69
|
+
return { commitment: publicSignals[0], total: Number(publicSignals[1]), proof, salt }; // salt stays with the app: it opens the commitment for an audit
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
async function verify(zk, total, ctx) {
|
|
73
|
+
if (!zk || typeof zk.commitment !== 'string' || !/^\d{1,80}$/.test(zk.commitment) || !zk.proof || typeof zk.proof !== 'object') return false;
|
|
74
|
+
try { return await lib()[key().protocol].verify(key(), [zk.commitment, String(total), ctx], zk.proof); } catch { return false; }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Check every item of a receipt. Marks items `proved`; throws on a bad proof, or on a missing one when proofs are required.
|
|
78
|
+
async function checkReceipt(p, required) {
|
|
79
|
+
const fail = (m) => Object.assign(new Error(m), { status: 400 });
|
|
80
|
+
if (!Array.isArray(p.items)) return 0;
|
|
81
|
+
let proved = 0;
|
|
82
|
+
for (const i of p.items) {
|
|
83
|
+
if (!i || typeof i !== 'object') continue;
|
|
84
|
+
delete i.proved;
|
|
85
|
+
if (i.zk === undefined) { if (required && i.calls > 0) throw fail(`a zero-knowledge proof is required for ${String(i.component).slice(0, 60)}`); continue; }
|
|
86
|
+
if (!canVerify()) throw fail('this server cannot verify zero-knowledge receipts');
|
|
87
|
+
if (!(await verify(i.zk, i.calls, context(p.appId, p.seq, i.component)))) throw fail(`invalid zero-knowledge proof for ${String(i.component).slice(0, 60)}`);
|
|
88
|
+
i.proved = true; proved++;
|
|
89
|
+
}
|
|
90
|
+
return proved;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// snarkjs keeps worker threads alive; scripts and tests call this so the process can exit
|
|
94
|
+
async function close() { if (globalThis.curve_bn128) { await globalThis.curve_bn128.terminate(); globalThis.curve_bn128 = null; } }
|
|
95
|
+
|
|
96
|
+
module.exports = { SLOTS, bucket, context, prove, verify, checkReceipt, canProve, canVerify, close };
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
pragma circom 2.1.6;
|
|
2
|
+
|
|
3
|
+
include "circomlib/circuits/poseidon.circom";
|
|
4
|
+
include "circomlib/circuits/bitify.circom";
|
|
5
|
+
|
|
6
|
+
// A Remetra usage receipt for one component.
|
|
7
|
+
//
|
|
8
|
+
// Private: counts[16] how many calls fell in each bucket (buckets are keyed by function name)
|
|
9
|
+
// salt random, so the commitment reveals nothing about the counts
|
|
10
|
+
// Public: context ties the proof to one app, receipt number and component (no replay elsewhere)
|
|
11
|
+
// commitment Poseidon hash of the private breakdown
|
|
12
|
+
// total the number of calls being billed
|
|
13
|
+
//
|
|
14
|
+
// The proof shows that `total` is exactly the sum of sixteen 32-bit counts that hash to `commitment`,
|
|
15
|
+
// without revealing any of them. An auditor who is later given counts and salt can check them
|
|
16
|
+
// against the commitment.
|
|
17
|
+
template Receipt() {
|
|
18
|
+
signal input counts[16];
|
|
19
|
+
signal input salt;
|
|
20
|
+
signal input context;
|
|
21
|
+
signal output commitment;
|
|
22
|
+
signal output total;
|
|
23
|
+
|
|
24
|
+
component range[16];
|
|
25
|
+
var sum = 0;
|
|
26
|
+
for (var i = 0; i < 16; i++) {
|
|
27
|
+
range[i] = Num2Bits(32); // each bucket is in [0, 2^32): no negative or wrapped values
|
|
28
|
+
range[i].in <== counts[i];
|
|
29
|
+
sum += counts[i];
|
|
30
|
+
}
|
|
31
|
+
total <== sum;
|
|
32
|
+
|
|
33
|
+
component lo = Poseidon(8);
|
|
34
|
+
component hi = Poseidon(8);
|
|
35
|
+
for (var i = 0; i < 8; i++) {
|
|
36
|
+
lo.inputs[i] <== counts[i];
|
|
37
|
+
hi.inputs[i] <== counts[8 + i];
|
|
38
|
+
}
|
|
39
|
+
component top = Poseidon(4);
|
|
40
|
+
top.inputs[0] <== lo.out;
|
|
41
|
+
top.inputs[1] <== hi.out;
|
|
42
|
+
top.inputs[2] <== salt;
|
|
43
|
+
top.inputs[3] <== context;
|
|
44
|
+
commitment <== top.out;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
component main {public [context]} = Receipt();
|