@needmoretruth/nmts-cli 0.56.0 → 0.58.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/CHANGELOG.md +21 -0
- package/README.ko.md +1 -1
- package/README.md +1 -1
- package/dist/artifact-about.d.ts +1 -1
- package/dist/commands/receive.js +30 -87
- package/dist/commands/share.d.ts +7 -0
- package/dist/commands/share.js +58 -180
- package/dist/commands/shares-sent.js +4 -29
- package/dist/commands/wallet-storage-buy.d.ts +22 -0
- package/dist/commands/wallet-storage-buy.js +111 -0
- package/dist/commands/wallet.js +3 -1
- package/dist/help-options.js +4 -2
- package/dist/help.js +2 -0
- package/dist/links.d.ts +5 -0
- package/dist/links.js +6 -1
- package/dist/platform-sign.d.ts +7 -1
- package/dist/platform-sign.js +12 -1
- package/dist/portable.d.ts +8 -1
- package/dist/portable.js +8 -1
- package/dist/product.d.ts +1 -1
- package/dist/product.js +1 -1
- package/dist/sharing-inbox.d.ts +52 -0
- package/dist/sharing-inbox.js +146 -0
- package/dist/sharing.d.ts +52 -0
- package/dist/sharing.js +218 -0
- package/dist/sponsor-check.d.ts +56 -0
- package/dist/sponsor-check.js +270 -0
- package/dist/sponsor-facts.d.ts +10 -0
- package/dist/sponsor-facts.js +75 -0
- package/dist/storage-control/buy.d.ts +65 -0
- package/dist/storage-control/buy.js +145 -0
- package/dist/storage-control-chain.d.ts +7 -0
- package/dist/storage-control-chain.js +19 -1
- package/dist/storage-control.d.ts +2 -0
- package/dist/storage-control.js +1 -0
- package/dist/upload-quote.d.ts +93 -0
- package/dist/upload-quote.js +135 -0
- package/dist/wallet-sign.d.ts +24 -0
- package/dist/wallet-sign.js +31 -1
- package/package.json +5 -1
- package/server.json +2 -2
package/dist/sharing.js
ADDED
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
// Sharing as a library: send one file to another account, list what came in and what went out,
|
|
2
|
+
// receive one, and take one back — for the command line, the SDK and a page, with nothing in it
|
|
3
|
+
// that needs Node (spec 2026-09-20 unit C).
|
|
4
|
+
//
|
|
5
|
+
// ⛔ WHY IT IS ITS OWN ENTRY. An app built on NMTS could not share a person's file: the steps lived
|
|
6
|
+
// inside `nmts share` and `nmts receive`, with the terminal wound through them. The commands are
|
|
7
|
+
// now shells over these functions, so what an app sends is what the command sends, byte for
|
|
8
|
+
// byte — the sealing itself is `share.ts`, untouched, and its order is load-bearing.
|
|
9
|
+
//
|
|
10
|
+
// ⛔ THE SAME FOR EVERY KEY HOLDER. `ShareAccount.bearer` is an API key or a delegation token. A
|
|
11
|
+
// token reaches the two sending doors only with its `share` bit AND the code's proof
|
|
12
|
+
// (`accountProof`), so the proof is sent on those two requests and on no other. An API key is
|
|
13
|
+
// asked for a live human check there instead, and the proof is simply not needed.
|
|
14
|
+
//
|
|
15
|
+
// ⛔ RECEIVING IS `sharing-inbox.ts`, re-exported here so `./share` is one entry.
|
|
16
|
+
//
|
|
17
|
+
// ⛔ NO `node:`, NO `Buffer`, NO `process.` — `test/portable-closure.test.ts` walks this file.
|
|
18
|
+
import { request, ServerError } from "./api.js";
|
|
19
|
+
import { fromBase64Url, toBase64Url, utf8 } from "./bytes.js";
|
|
20
|
+
import { AAD, DERIVED, loadCrypto } from "./crypto.js";
|
|
21
|
+
import { buildIndex, entryAt, fullPathOf, KIND_FILE, normalisePath } from "./drive-paths.js";
|
|
22
|
+
import { NmtsError } from "./errors.js";
|
|
23
|
+
import { readFileList } from "./manifest.js";
|
|
24
|
+
import { BINARY_NAME } from "./product.js";
|
|
25
|
+
import { differentCode, notLiveCode, publicCodeRefusal } from "./public-code-refusals.js";
|
|
26
|
+
import { ensureLiveCode, liveCodes, PUBLISH_TRIES } from "./public-codes.js";
|
|
27
|
+
import { identityMatches, sealShare } from "./share.js";
|
|
28
|
+
import { shareKeyRing, shareKeysAt } from "./share-codes.js";
|
|
29
|
+
export { addressFromTyped } from "./share.js";
|
|
30
|
+
export { receivedShares, receiveShare } from "./sharing-inbox.js";
|
|
31
|
+
/** The file at `target`, checked for the key and the hash a share carries. */
|
|
32
|
+
export async function shareableFileAt(account, target) {
|
|
33
|
+
const list = await readFileList(account.server, account.bearer, account.code, account.accountId);
|
|
34
|
+
if (list.manifest === null) {
|
|
35
|
+
throw new NmtsError("This account has no file list, so there is nothing to share.", { exitCode: 4 });
|
|
36
|
+
}
|
|
37
|
+
const index = buildIndex(list.manifest.entries);
|
|
38
|
+
const entry = entryAt(list.manifest.entries, normalisePath(target), {
|
|
39
|
+
nothingHappened: "Nothing was shared.",
|
|
40
|
+
});
|
|
41
|
+
if (entry.kind !== KIND_FILE) {
|
|
42
|
+
throw new NmtsError(`No file at "${fullPathOf(index, entry)}".`, {
|
|
43
|
+
exitCode: 4,
|
|
44
|
+
nextStep: "That is a folder. Nothing was shared — this version shares one file at a time.",
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
const { dekWrapped, contentHashCt } = entry;
|
|
48
|
+
if (dekWrapped === undefined || contentHashCt === undefined) {
|
|
49
|
+
throw new NmtsError(`The file list holds no ${dekWrapped === undefined ? "key" : "hash"} for "${entry.name}".`, {
|
|
50
|
+
exitCode: 4,
|
|
51
|
+
nextStep: "A share carries both — the key that opens the file and the hash the recipient checks the " +
|
|
52
|
+
"bytes against. Nothing was shared.",
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
return { entry: { ...entry, dekWrapped, contentHashCt }, path: fullPathOf(index, entry) };
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Which live code sends: `as` when named, else the lowest-numbered live one — published first when
|
|
59
|
+
* the account has none, as a first share does.
|
|
60
|
+
*
|
|
61
|
+
* ⚠ A DELEGATION TOKEN CANNOT READ THE CODE LIST (its business replaces a user's one code through
|
|
62
|
+
* its own signed batch, and that list stays closed to it). So for a token the codes are asked
|
|
63
|
+
* one number at a time at the public lookup, from 0: a revoked one answers 410, the live one 200,
|
|
64
|
+
* and the first number never published 404 — there is nothing after it.
|
|
65
|
+
*/
|
|
66
|
+
async function senderKeys(crypt, account, as, onFirstCode) {
|
|
67
|
+
const door = { server: account.server, token: account.bearer };
|
|
68
|
+
let codes;
|
|
69
|
+
try {
|
|
70
|
+
({ list: codes } = await ensureLiveCode(crypt, account.code, door, onFirstCode));
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
if (!(error instanceof ServerError && error.code === "DELEGATION_SCOPE"))
|
|
74
|
+
throw publicCodeRefusal(error);
|
|
75
|
+
return as === undefined ? await walkToLiveCode(crypt, account) : shareKeysAt(crypt, account.code, as);
|
|
76
|
+
}
|
|
77
|
+
const live = liveCodes(codes);
|
|
78
|
+
const sender = as === undefined ? live[0] : live.find((c) => c.index === as);
|
|
79
|
+
if (sender === undefined)
|
|
80
|
+
throw notLiveCode(as ?? 0);
|
|
81
|
+
const keys = shareKeysAt(crypt, account.code, sender.index);
|
|
82
|
+
if (toBase64Url(keys.address) !== sender.address) {
|
|
83
|
+
keys.wipe();
|
|
84
|
+
throw differentCode();
|
|
85
|
+
}
|
|
86
|
+
return keys;
|
|
87
|
+
}
|
|
88
|
+
async function walkToLiveCode(crypt, account) {
|
|
89
|
+
const ring = shareKeyRing(crypt, account.code);
|
|
90
|
+
try {
|
|
91
|
+
for (let index = 0; index < PUBLISH_TRIES; index += 1) {
|
|
92
|
+
const address = toBase64Url(ring.at(index).address);
|
|
93
|
+
try {
|
|
94
|
+
await request(account.server, `/v1/share-recipients/${encodeURIComponent(address)}`, { token: account.bearer });
|
|
95
|
+
return shareKeysAt(crypt, account.code, index);
|
|
96
|
+
}
|
|
97
|
+
catch (error) {
|
|
98
|
+
if (error instanceof ServerError && error.status === 410)
|
|
99
|
+
continue;
|
|
100
|
+
if (error instanceof ServerError && error.status === 404)
|
|
101
|
+
break;
|
|
102
|
+
throw error;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
ring.wipe();
|
|
108
|
+
}
|
|
109
|
+
throw new NmtsError("This account has no public code yet, so nothing can be shared from it.", {
|
|
110
|
+
exitCode: 4,
|
|
111
|
+
nextStep: "Nothing was shared. The business that issued this token publishes one with setPublicCodes; then share again.",
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Seal one file for one public code and send it.
|
|
116
|
+
*
|
|
117
|
+
* ⛔ THE CALLER HAS ALREADY DECIDED. The command asks its person between `shareableFileAt` and this
|
|
118
|
+
* call; a program decides by calling. Nothing here asks anybody anything.
|
|
119
|
+
*/
|
|
120
|
+
export async function sendShare(account, file, recipientAddress, options = {}) {
|
|
121
|
+
const crypt = await loadCrypto();
|
|
122
|
+
const { entry } = file;
|
|
123
|
+
let keys = null;
|
|
124
|
+
const derived = crypt.kdf_derive(crypt.account_code_parse(account.code));
|
|
125
|
+
const dataKey = derived.slice(DERIVED.dataKey[0], DERIVED.dataKey[1]);
|
|
126
|
+
derived.fill(0);
|
|
127
|
+
let dek = null;
|
|
128
|
+
let digest = null;
|
|
129
|
+
try {
|
|
130
|
+
dek = crypt.envelope_open(dataKey, utf8(AAD.dekWrap), fromBase64Url(entry.dekWrapped));
|
|
131
|
+
digest = crypt.envelope_open(dataKey, utf8(AAD.contentHash), fromBase64Url(entry.contentHashCt));
|
|
132
|
+
dataKey.fill(0);
|
|
133
|
+
keys = await senderKeys(crypt, account, options.as, options.onFirstCode);
|
|
134
|
+
const answer = await request(account.server, `/v1/share-recipients/${encodeURIComponent(toBase64Url(recipientAddress))}`, { token: account.bearer });
|
|
135
|
+
const identityB64 = typeof answer === "object" && answer !== null ? Reflect.get(answer, "share_public_key") : null;
|
|
136
|
+
if (typeof identityB64 !== "string") {
|
|
137
|
+
throw new NmtsError("That public code has never published an identity to share to.", {
|
|
138
|
+
exitCode: 4,
|
|
139
|
+
nextStep: "Nothing was shared. The code may be right and unused — somebody has to open " +
|
|
140
|
+
"their account once before anything can be encrypted to them.",
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
const recipientIdentity = fromBase64Url(identityB64);
|
|
144
|
+
// ⛔ CHECKED BEFORE ANYTHING IS ENCRYPTED TO IT. The engine checks it again inside the wrap;
|
|
145
|
+
// this exists so the refusal names WHICH thing was wrong.
|
|
146
|
+
if (!identityMatches(crypt, recipientIdentity, recipientAddress)) {
|
|
147
|
+
throw new NmtsError("The identity the server returned is not the one that public code names.", {
|
|
148
|
+
exitCode: 1,
|
|
149
|
+
nextStep: "Nothing was shared. Encrypting to it would hand the file to somebody else.",
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
const payload = sealShare(crypt, {
|
|
153
|
+
keys,
|
|
154
|
+
recipientIdentity,
|
|
155
|
+
recipientAddress,
|
|
156
|
+
dek,
|
|
157
|
+
itemId: entry.id,
|
|
158
|
+
name: entry.name,
|
|
159
|
+
size: entry.size,
|
|
160
|
+
digest,
|
|
161
|
+
});
|
|
162
|
+
const created = await request(account.server, "/v1/shares", {
|
|
163
|
+
token: account.bearer,
|
|
164
|
+
method: "POST",
|
|
165
|
+
body: { item_id: entry.id, recipient_address: toBase64Url(recipientAddress), ...payload },
|
|
166
|
+
...(account.accountProof === undefined ? {} : { accountProof: account.accountProof }),
|
|
167
|
+
});
|
|
168
|
+
// ⛔ READ BACK, NOT ECHOED. The server returns the address it actually STORED the share under.
|
|
169
|
+
const stored = typeof created === "object" && created !== null ? Reflect.get(created, "recipient_address") : null;
|
|
170
|
+
if (typeof stored !== "string" || stored !== toBase64Url(recipientAddress)) {
|
|
171
|
+
throw new NmtsError("The server filed this share against a different public code.", {
|
|
172
|
+
exitCode: 1,
|
|
173
|
+
nextStep: `Withdraw it now with \`${BINARY_NAME} unshare\` and share it again. The file's key was ` +
|
|
174
|
+
`wrapped for the address you typed, so it is not readable by whoever it was filed under.`,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
const id = typeof created === "object" && created !== null ? Reflect.get(created, "id") : null;
|
|
178
|
+
return {
|
|
179
|
+
id: typeof id === "string" ? id : null,
|
|
180
|
+
name: entry.name,
|
|
181
|
+
recipient: crypt.share_address_display(recipientAddress),
|
|
182
|
+
fromIndex: keys.index,
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
finally {
|
|
186
|
+
dataKey.fill(0);
|
|
187
|
+
dek?.fill(0);
|
|
188
|
+
digest?.fill(0);
|
|
189
|
+
keys?.wipe();
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
/** Who one file was shared with: the server's rows, unchanged, beside the file's path and id. */
|
|
193
|
+
export async function sentShares(account, target) {
|
|
194
|
+
const list = await readFileList(account.server, account.bearer, account.code, account.accountId);
|
|
195
|
+
if (list.manifest === null) {
|
|
196
|
+
throw new NmtsError("This account has no file list, so there is nothing to look up.", { exitCode: 4 });
|
|
197
|
+
}
|
|
198
|
+
const index = buildIndex(list.manifest.entries);
|
|
199
|
+
const entry = entryAt(list.manifest.entries, normalisePath(target), { nothingHappened: "Nothing was changed." });
|
|
200
|
+
if (entry.kind !== KIND_FILE) {
|
|
201
|
+
throw new NmtsError(`No file at "${fullPathOf(index, entry)}".`, {
|
|
202
|
+
exitCode: 4,
|
|
203
|
+
nextStep: "That is a folder, and a share is of one file.",
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
const answer = await request(account.server, `/v1/shares/sent?item_id=${encodeURIComponent(entry.id)}`, { token: account.bearer });
|
|
207
|
+
const rows = typeof answer === "object" && answer !== null ? Reflect.get(answer, "shares") : null;
|
|
208
|
+
if (!Array.isArray(rows)) {
|
|
209
|
+
throw new NmtsError("The server's answer did not carry a list of shares.", {
|
|
210
|
+
nextStep: "Nothing was changed. Report it rather than retrying — the shape, not the network, is wrong.",
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
return { path: fullPathOf(index, entry), itemId: entry.id, rows };
|
|
214
|
+
}
|
|
215
|
+
/** Withdraw a share this account sent, or remove one it was sent. A copy already taken stays taken. */
|
|
216
|
+
export async function removeShare(account, id) {
|
|
217
|
+
await request(account.server, `/v1/shares/${encodeURIComponent(id)}`, { token: account.bearer, method: "DELETE" });
|
|
218
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import type { Network } from "./network.ts";
|
|
2
|
+
/** What the operator agrees to pay for in ONE transaction. Amounts in base units. */
|
|
3
|
+
export interface SponsorPolicy {
|
|
4
|
+
network: Network;
|
|
5
|
+
/** The operator's address: the only sender and gas owner signed for. */
|
|
6
|
+
operator: string;
|
|
7
|
+
/** Bytes the blobs registered or extended may hold in total (unencoded, as registered). */
|
|
8
|
+
maxBytes: number;
|
|
9
|
+
/** The longest term one reservation or extension may buy, in epochs. */
|
|
10
|
+
maxEpochs: number;
|
|
11
|
+
/** WAL the Walrus calls may take, in FROST. */
|
|
12
|
+
maxWalFrost: bigint | number | string;
|
|
13
|
+
/** SUI the transaction may spend — its gas budget plus relay tips — in MIST. */
|
|
14
|
+
maxSuiMist: bigint | number | string;
|
|
15
|
+
/** The highest gas budget accepted, in MIST. Default: `maxSuiMist`. */
|
|
16
|
+
maxGasBudgetMist?: bigint | number | string | undefined;
|
|
17
|
+
/** Pin the Walrus package instead of reading it from the chain. */
|
|
18
|
+
walrusPackageId?: string | undefined;
|
|
19
|
+
/** Pin the relays' tip addresses instead of asking the relays. */
|
|
20
|
+
relayTipAddresses?: readonly string[] | undefined;
|
|
21
|
+
}
|
|
22
|
+
/** The chain facts a judgement needs. */
|
|
23
|
+
export interface SponsorFacts {
|
|
24
|
+
walrusPackageId: string;
|
|
25
|
+
systemObjectId: string;
|
|
26
|
+
relayTipAddresses: readonly string[];
|
|
27
|
+
/** What a blob of `size` bytes occupies once encoded — the chain's own number. */
|
|
28
|
+
encodedLength(size: number): Promise<number>;
|
|
29
|
+
/** The unencoded size of a blob object, or null when it could not be read. */
|
|
30
|
+
blobSize(objectId: string): Promise<number | null>;
|
|
31
|
+
}
|
|
32
|
+
/** What a passing transaction spends, as decimal strings so a log and JSON carry them whole. */
|
|
33
|
+
export interface SponsorSpend {
|
|
34
|
+
walFrost: string;
|
|
35
|
+
/** Gas budget plus tips: the most SUI it can take. */
|
|
36
|
+
suiMist: string;
|
|
37
|
+
gasBudgetMist: string;
|
|
38
|
+
tipMist: string;
|
|
39
|
+
/** Bytes registered or extended. */
|
|
40
|
+
bytes: number;
|
|
41
|
+
/** The longest term bought, in epochs. 0 for a certification. */
|
|
42
|
+
epochs: number;
|
|
43
|
+
/** The Walrus calls it makes, in order. */
|
|
44
|
+
calls: string[];
|
|
45
|
+
}
|
|
46
|
+
export type SponsorVerdict = {
|
|
47
|
+
ok: true;
|
|
48
|
+
spends: SponsorSpend;
|
|
49
|
+
} | {
|
|
50
|
+
ok: false;
|
|
51
|
+
code: SponsorRefusal;
|
|
52
|
+
reason: string;
|
|
53
|
+
};
|
|
54
|
+
export type SponsorRefusal = "SPONSOR_NOT_A_TRANSACTION" | "SPONSOR_SENDER" | "SPONSOR_GAS_OWNER" | "SPONSOR_GAS_BUDGET" | "SPONSOR_INPUT" | "SPONSOR_COMMAND" | "SPONSOR_CALL" | "SPONSOR_NETWORK" | "SPONSOR_TRANSFER" | "SPONSOR_UNBOUNDED" | "SPONSOR_STORAGE" | "SPONSOR_SIZE" | "SPONSOR_EPOCHS" | "SPONSOR_WAL" | "SPONSOR_SUI" | "SPONSOR_EMPTY";
|
|
55
|
+
/** Judge one transaction against a policy. Never throws for a refusal: the verdict says it. */
|
|
56
|
+
export declare function judgeSponsored(bytes: Uint8Array | string, policy: SponsorPolicy, facts: SponsorFacts): Promise<SponsorVerdict>;
|
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
// Before an operator's wallet signs a transaction somebody else's device built: is it only the
|
|
2
|
+
// Walrus work the operator agreed to pay for, inside the limits it set?
|
|
3
|
+
//
|
|
4
|
+
// ⛔ WHY (spec 2026-09-20 Deponejo · gap B · plan 2026-11-10 §1.3). A business that takes its
|
|
5
|
+
// customers' money however it likes can let its own wallet pay their storage: the device calls
|
|
6
|
+
// `put(file, { pay: { signer } })` and that signer forwards each transaction to the business's
|
|
7
|
+
// server, which signs as the sender. Without a check the server signs whatever bytes arrive —
|
|
8
|
+
// including a transaction that sends the business's coins to the person who built it. Sui's own
|
|
9
|
+
// gas sponsorship was rejected: it pays only the gas, and WAL can come only from the sender.
|
|
10
|
+
//
|
|
11
|
+
// ⛔ AN ALLOW LIST, READ OFF THE BYTES, NEVER A DENY LIST. What passes is exactly: the sender and the
|
|
12
|
+
// gas owner are the operator; every Move call is `system::reserve_space`, `register_blob`,
|
|
13
|
+
// `certify_blob` or `extend_blob` of the network's Walrus package on the network's own system
|
|
14
|
+
// object, or the coin plumbing the Sui SDK writes for a payment (`coin::redeem_funds`,
|
|
15
|
+
// `coin::destroy_zero`, `coin::zero`, `coin::send_funds` back to the operator); every transfer
|
|
16
|
+
// goes to the operator, except SUI coins of a known amount to an upload relay's tip address; and
|
|
17
|
+
// the size, the term, the WAL and the SUI are within the policy. Anything else is refused with a
|
|
18
|
+
// code and a sentence a log can hold. A new kind of command is refused until somebody decides it
|
|
19
|
+
// here, in the open.
|
|
20
|
+
//
|
|
21
|
+
// ⛔ EVERY COIN THAT LEAVES IS A COIN OF A KNOWN AMOUNT. The WAL a Walrus call may take is bounded by
|
|
22
|
+
// the coins it is handed: each must be cut by `SplitCoins` to an amount written in the bytes (or
|
|
23
|
+
// drawn from the address balance by a reservation of a written amount), and not grown by a merge
|
|
24
|
+
// since. A whole coin, the gas coin, or a coin of unknown amount handed to any call is refused —
|
|
25
|
+
// so even a lying node that named a wrong package could not take more than the policy's WAL.
|
|
26
|
+
//
|
|
27
|
+
// ⚠ PURE: no network and no key. The chain facts it needs — the package, the relays' tip addresses,
|
|
28
|
+
// the encoded length of a size, the size of a blob being extended — are handed in
|
|
29
|
+
// (`sponsor-facts.ts` reads them; a test hands in a table).
|
|
30
|
+
import { bcs } from "@mysten/sui/bcs";
|
|
31
|
+
import { Transaction } from "@mysten/sui/transactions";
|
|
32
|
+
import { fromBase64, normalizeSuiAddress } from "@mysten/sui/utils";
|
|
33
|
+
const WALRUS_CALLS = new Set(["reserve_space", "register_blob", "certify_blob", "extend_blob"]);
|
|
34
|
+
const SUI_TYPE = "0x0000000000000000000000000000000000000000000000000000000000000002::sui::SUI";
|
|
35
|
+
const FRAMEWORK = normalizeSuiAddress("0x2");
|
|
36
|
+
class Refused extends Error {
|
|
37
|
+
code;
|
|
38
|
+
constructor(code, reason) {
|
|
39
|
+
super(reason);
|
|
40
|
+
this.code = code;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
function amountOf(value, name) {
|
|
44
|
+
try {
|
|
45
|
+
const n = BigInt(value);
|
|
46
|
+
if (n >= 0n)
|
|
47
|
+
return n;
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
// Refused below with the field's name.
|
|
51
|
+
}
|
|
52
|
+
throw new Refused("SPONSOR_NOT_A_TRANSACTION", `the policy's ${name} is not a whole number of base units`);
|
|
53
|
+
}
|
|
54
|
+
function typeIsSui(type) {
|
|
55
|
+
const [address, ...rest] = type.split("::");
|
|
56
|
+
return address !== undefined && `${normalizeSuiAddress(address)}::${rest.join("::")}` === SUI_TYPE;
|
|
57
|
+
}
|
|
58
|
+
/** Judge one transaction against a policy. Never throws for a refusal: the verdict says it. */
|
|
59
|
+
export async function judgeSponsored(bytes, policy, facts) {
|
|
60
|
+
try {
|
|
61
|
+
return { ok: true, spends: await judge(bytes, policy, facts) };
|
|
62
|
+
}
|
|
63
|
+
catch (error) {
|
|
64
|
+
if (error instanceof Refused)
|
|
65
|
+
return { ok: false, code: error.code, reason: error.message };
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
async function judge(raw, policy, facts) {
|
|
70
|
+
let data;
|
|
71
|
+
try {
|
|
72
|
+
data = Transaction.from(typeof raw === "string" ? fromBase64(raw) : raw).getData();
|
|
73
|
+
}
|
|
74
|
+
catch (error) {
|
|
75
|
+
throw new Refused("SPONSOR_NOT_A_TRANSACTION", `the bytes are not a Sui transaction (${error instanceof Error ? error.message : String(error)})`);
|
|
76
|
+
}
|
|
77
|
+
const operator = normalizeSuiAddress(policy.operator);
|
|
78
|
+
const maxWal = amountOf(policy.maxWalFrost, "maxWalFrost");
|
|
79
|
+
const maxSui = amountOf(policy.maxSuiMist, "maxSuiMist");
|
|
80
|
+
const maxBudget = policy.maxGasBudgetMist === undefined ? maxSui : amountOf(policy.maxGasBudgetMist, "maxGasBudgetMist");
|
|
81
|
+
const walrus = normalizeSuiAddress(policy.walrusPackageId ?? facts.walrusPackageId);
|
|
82
|
+
const system = normalizeSuiAddress(facts.systemObjectId);
|
|
83
|
+
const tipTo = new Set((policy.relayTipAddresses ?? facts.relayTipAddresses).map((a) => normalizeSuiAddress(a)));
|
|
84
|
+
// ① Who signs and who pays the gas.
|
|
85
|
+
if (data.sender === null || data.sender === undefined || normalizeSuiAddress(data.sender) !== operator) {
|
|
86
|
+
throw new Refused("SPONSOR_SENDER", `the sender is ${data.sender ?? "missing"}, not the operator ${operator}`);
|
|
87
|
+
}
|
|
88
|
+
const gasOwner = data.gasData.owner ?? data.sender;
|
|
89
|
+
if (normalizeSuiAddress(gasOwner) !== operator) {
|
|
90
|
+
throw new Refused("SPONSOR_GAS_OWNER", `the gas is paid by ${gasOwner}, not the operator ${operator}`);
|
|
91
|
+
}
|
|
92
|
+
if (data.gasData.budget === null || data.gasData.budget === undefined) {
|
|
93
|
+
throw new Refused("SPONSOR_GAS_BUDGET", "the transaction names no gas budget");
|
|
94
|
+
}
|
|
95
|
+
const budget = BigInt(data.gasData.budget);
|
|
96
|
+
if (budget > maxBudget)
|
|
97
|
+
throw new Refused("SPONSOR_GAS_BUDGET", `the gas budget ${budget} MIST is over the cap ${maxBudget} MIST`);
|
|
98
|
+
// ② The inputs: plain values, objects, and withdrawals from the operator's own balance only.
|
|
99
|
+
const inputs = data.inputs;
|
|
100
|
+
const pure = (arg, what) => {
|
|
101
|
+
const input = arg?.Input === undefined ? undefined : inputs[arg.Input];
|
|
102
|
+
if (input?.Pure === undefined)
|
|
103
|
+
throw new Refused("SPONSOR_INPUT", `${what} is not a plain value written in the transaction`);
|
|
104
|
+
return fromBase64(input.Pure.bytes);
|
|
105
|
+
};
|
|
106
|
+
const u64 = (arg, what) => BigInt(bcs.u64().parse(pure(arg, what)));
|
|
107
|
+
const u32 = (arg, what) => bcs.u32().parse(pure(arg, what));
|
|
108
|
+
const address = (arg, what) => normalizeSuiAddress(bcs.Address.parse(pure(arg, what)));
|
|
109
|
+
for (const [i, input] of inputs.entries()) {
|
|
110
|
+
if (input.Object?.Receiving !== undefined)
|
|
111
|
+
throw new Refused("SPONSOR_INPUT", `input ${i} receives an object sent to another object`);
|
|
112
|
+
const w = input.FundsWithdrawal;
|
|
113
|
+
if (w !== undefined && w.withdrawFrom.Sender !== true && w.withdrawFrom.Sponsor !== true) {
|
|
114
|
+
throw new Refused("SPONSOR_INPUT", `input ${i} withdraws from an allowance, not from the operator's own balance`);
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
// ③ The commands, one by one, with every coin followed from where it was made.
|
|
118
|
+
const coins = new Map();
|
|
119
|
+
const keyOf = (arg) => arg.Result !== undefined ? `${arg.Result}` : arg.NestedResult !== undefined ? `${arg.NestedResult[0]}:${arg.NestedResult[1]}` : null;
|
|
120
|
+
const reserves = new Map();
|
|
121
|
+
const payments = new Map();
|
|
122
|
+
const extended = [];
|
|
123
|
+
const registered = [];
|
|
124
|
+
const calls = [];
|
|
125
|
+
let tips = 0n;
|
|
126
|
+
let epochs = 0;
|
|
127
|
+
const payment = (arg, call) => {
|
|
128
|
+
const key = arg === undefined ? null : keyOf(arg);
|
|
129
|
+
const coin = key === null ? undefined : coins.get(key);
|
|
130
|
+
if (key === null || coin === undefined || coin.amount === null) {
|
|
131
|
+
throw new Refused("SPONSOR_UNBOUNDED", `${call} is paid from a coin whose amount the transaction does not bound`);
|
|
132
|
+
}
|
|
133
|
+
payments.set(key, coin.amount);
|
|
134
|
+
};
|
|
135
|
+
for (const [index, command] of data.commands.entries()) {
|
|
136
|
+
if (command.SplitCoins !== undefined) {
|
|
137
|
+
const source = command.SplitCoins.coin;
|
|
138
|
+
const from = source.GasCoin === true ? { sui: true, amount: null } : (coins.get(keyOf(source) ?? "") ?? { sui: null, amount: null });
|
|
139
|
+
command.SplitCoins.amounts.forEach((amount, j) => {
|
|
140
|
+
const input = amount.Input === undefined ? undefined : inputs[amount.Input];
|
|
141
|
+
coins.set(`${index}:${j}`, { sui: from.sui, amount: input?.Pure === undefined ? null : u64(amount, "a split amount") });
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
else if (command.MergeCoins !== undefined) {
|
|
145
|
+
// ⛔ A MERGED-INTO COIN NO LONGER HAS THE AMOUNT IT WAS CUT TO: anything could have joined it.
|
|
146
|
+
const key = keyOf(command.MergeCoins.destination);
|
|
147
|
+
const coin = key === null ? undefined : coins.get(key);
|
|
148
|
+
if (key !== null && coin !== undefined)
|
|
149
|
+
coins.set(key, { sui: coin.sui, amount: null });
|
|
150
|
+
}
|
|
151
|
+
else if (command.TransferObjects !== undefined) {
|
|
152
|
+
const to = address(command.TransferObjects.address, "a transfer's recipient");
|
|
153
|
+
if (to === operator)
|
|
154
|
+
continue;
|
|
155
|
+
if (!tipTo.has(to))
|
|
156
|
+
throw new Refused("SPONSOR_TRANSFER", `command ${index} sends to ${to}, which is neither the operator nor an upload relay's tip address`);
|
|
157
|
+
for (const object of command.TransferObjects.objects) {
|
|
158
|
+
const coin = coins.get(keyOf(object) ?? "");
|
|
159
|
+
if (coin === undefined || coin.sui !== true || coin.amount === null) {
|
|
160
|
+
throw new Refused("SPONSOR_TRANSFER", `command ${index} sends the relay something other than a SUI coin of a written amount`);
|
|
161
|
+
}
|
|
162
|
+
tips += coin.amount;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
else if (command.MoveCall !== undefined) {
|
|
166
|
+
const call = command.MoveCall;
|
|
167
|
+
const args = call.arguments;
|
|
168
|
+
const name = `${call.package}::${call.module}::${call.function}`;
|
|
169
|
+
if (args.some((a) => a.GasCoin === true))
|
|
170
|
+
throw new Refused("SPONSOR_CALL", `${name} is handed the gas coin`);
|
|
171
|
+
const pkg = normalizeSuiAddress(call.package);
|
|
172
|
+
if (pkg === FRAMEWORK && call.module === "coin") {
|
|
173
|
+
if (call.function === "redeem_funds") {
|
|
174
|
+
const input = args[0]?.Input === undefined ? undefined : inputs[args[0].Input];
|
|
175
|
+
const w = input?.FundsWithdrawal;
|
|
176
|
+
if (w === undefined)
|
|
177
|
+
throw new Refused("SPONSOR_CALL", `${name} redeems something other than a withdrawal`);
|
|
178
|
+
coins.set(`${index}`, { sui: typeIsSui(w.typeArg.Balance), amount: BigInt(w.reservation.MaxAmountU64) });
|
|
179
|
+
}
|
|
180
|
+
else if (call.function === "send_funds") {
|
|
181
|
+
const to = address(args[1], "send_funds's recipient");
|
|
182
|
+
if (to !== operator)
|
|
183
|
+
throw new Refused("SPONSOR_TRANSFER", `command ${index} sends funds to ${to}, not back to the operator`);
|
|
184
|
+
}
|
|
185
|
+
else if (call.function !== "destroy_zero" && call.function !== "zero") {
|
|
186
|
+
throw new Refused("SPONSOR_CALL", `${name} is not part of paying for Walrus storage`);
|
|
187
|
+
}
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
if (pkg !== walrus || call.module !== "system" || !WALRUS_CALLS.has(call.function)) {
|
|
191
|
+
throw new Refused("SPONSOR_CALL", `${name} is not a Walrus reservation, registration, certification or extension`);
|
|
192
|
+
}
|
|
193
|
+
// ⛔ THE NETWORK'S OWN SYSTEM OBJECT, which is what proves the network named is the network signed for.
|
|
194
|
+
const self = args[0]?.Input === undefined ? undefined : inputs[args[0].Input]?.Object?.SharedObject;
|
|
195
|
+
if (self === undefined || normalizeSuiAddress(self.objectId) !== system) {
|
|
196
|
+
throw new Refused("SPONSOR_NETWORK", `${call.function} is not called on the ${policy.network} Walrus system object`);
|
|
197
|
+
}
|
|
198
|
+
calls.push(call.function);
|
|
199
|
+
if (call.function === "reserve_space") {
|
|
200
|
+
const term = u32(args[2], "a reservation's term");
|
|
201
|
+
payment(args[3], call.function);
|
|
202
|
+
reserves.set(`${index}`, { amount: u64(args[1], "a reservation's size"), epochs: term, used: false });
|
|
203
|
+
epochs = Math.max(epochs, term);
|
|
204
|
+
}
|
|
205
|
+
else if (call.function === "register_blob") {
|
|
206
|
+
const reserve = reserves.get(keyOf(args[1] ?? {}) ?? "");
|
|
207
|
+
if (reserve === undefined || reserve.used) {
|
|
208
|
+
throw new Refused("SPONSOR_STORAGE", "a registration binds storage the operator already holds instead of storage bought in this transaction");
|
|
209
|
+
}
|
|
210
|
+
reserve.used = true;
|
|
211
|
+
const size = u64(args[4], "a registration's size");
|
|
212
|
+
if (size > BigInt(Number.MAX_SAFE_INTEGER))
|
|
213
|
+
throw new Refused("SPONSOR_SIZE", `a registration of ${size} bytes`);
|
|
214
|
+
registered.push({ size: Number(size), reserve });
|
|
215
|
+
payment(args[7], call.function);
|
|
216
|
+
}
|
|
217
|
+
else if (call.function === "extend_blob") {
|
|
218
|
+
const blob = args[1]?.Input === undefined ? undefined : inputs[args[1].Input]?.Object?.ImmOrOwnedObject;
|
|
219
|
+
if (blob === undefined)
|
|
220
|
+
throw new Refused("SPONSOR_INPUT", "an extension names no blob object");
|
|
221
|
+
extended.push(blob.objectId);
|
|
222
|
+
const term = u32(args[2], "an extension's term");
|
|
223
|
+
epochs = Math.max(epochs, term);
|
|
224
|
+
payment(args[3], call.function);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
else {
|
|
228
|
+
throw new Refused("SPONSOR_COMMAND", `command ${index} is a ${command.$kind ?? "command"}, which a sponsored upload never needs`);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
// ④ What it all adds up to, against the policy.
|
|
232
|
+
if (calls.length === 0)
|
|
233
|
+
throw new Refused("SPONSOR_EMPTY", "the transaction does no Walrus work");
|
|
234
|
+
if ([...reserves.values()].some((r) => !r.used)) {
|
|
235
|
+
throw new Refused("SPONSOR_STORAGE", "storage is reserved and not written into: that is buying storage, not an upload");
|
|
236
|
+
}
|
|
237
|
+
let bytes = 0;
|
|
238
|
+
for (const { size, reserve } of registered) {
|
|
239
|
+
bytes += size;
|
|
240
|
+
const most = await facts.encodedLength(size);
|
|
241
|
+
if (reserve.amount > BigInt(most)) {
|
|
242
|
+
throw new Refused("SPONSOR_SIZE", `${reserve.amount} bytes are reserved for a blob of ${size}, which needs ${most} once encoded`);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
for (const id of extended) {
|
|
246
|
+
const size = await facts.blobSize(id);
|
|
247
|
+
if (size === null)
|
|
248
|
+
throw new Refused("SPONSOR_SIZE", `the size of blob ${id} could not be read, so the extension is not bounded`);
|
|
249
|
+
bytes += size;
|
|
250
|
+
}
|
|
251
|
+
if (bytes > policy.maxBytes)
|
|
252
|
+
throw new Refused("SPONSOR_SIZE", `${bytes} bytes are over the policy's ${policy.maxBytes}`);
|
|
253
|
+
if (epochs > policy.maxEpochs)
|
|
254
|
+
throw new Refused("SPONSOR_EPOCHS", `${epochs} epochs are over the policy's ${policy.maxEpochs}`);
|
|
255
|
+
const wal = [...payments.values()].reduce((sum, n) => sum + n, 0n);
|
|
256
|
+
if (wal > maxWal)
|
|
257
|
+
throw new Refused("SPONSOR_WAL", `${wal} FROST of WAL is over the policy's ${maxWal}`);
|
|
258
|
+
const sui = budget + tips;
|
|
259
|
+
if (sui > maxSui)
|
|
260
|
+
throw new Refused("SPONSOR_SUI", `${sui} MIST of SUI (gas budget ${budget} + tips ${tips}) is over the policy's ${maxSui}`);
|
|
261
|
+
return {
|
|
262
|
+
walFrost: wal.toString(),
|
|
263
|
+
suiMist: sui.toString(),
|
|
264
|
+
gasBudgetMist: budget.toString(),
|
|
265
|
+
tipMist: tips.toString(),
|
|
266
|
+
bytes,
|
|
267
|
+
epochs,
|
|
268
|
+
calls,
|
|
269
|
+
};
|
|
270
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Network } from "./network.ts";
|
|
2
|
+
import type { SponsorFacts } from "./sponsor-check.ts";
|
|
3
|
+
/** Every relay's tip address that answers now, for `network`. */
|
|
4
|
+
export declare function readRelayTipAddresses(network: Network, extra?: readonly string[]): Promise<string[]>;
|
|
5
|
+
/**
|
|
6
|
+
* The live facts for `network`, read once and kept: the package, the system object and the tip
|
|
7
|
+
* addresses do not change between two transactions of one upload. `operator` is the address the
|
|
8
|
+
* encoded-length question is asked as (a read; nothing is signed).
|
|
9
|
+
*/
|
|
10
|
+
export declare function sponsorFacts(network: Network, operator: string): Promise<SponsorFacts>;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// The chain facts a sponsored-transaction check needs, read live for one network.
|
|
2
|
+
//
|
|
3
|
+
// ⛔ WHAT A NODE ANSWERS DOES NOT DECIDE WHAT IS SIGNED BY ITSELF. The system object is this
|
|
4
|
+
// package's own constant (`packageConfig`), so a call on any other object is refused whatever a
|
|
5
|
+
// node says. The Walrus package id is read from that object; a node that lied about it could only
|
|
6
|
+
// point at a call that is still handed coins of written amounts (`sponsor-check.ts`), so the most
|
|
7
|
+
// it could take is the policy's WAL. An operator who wants no node in that answer pins
|
|
8
|
+
// `walrusPackageId` in the policy.
|
|
9
|
+
//
|
|
10
|
+
// ⚠ THE RELAYS' TIP ADDRESSES COME FROM THE RELAYS THEMSELVES — the relay this tool uploads through
|
|
11
|
+
// and the known ones for the network. A relay that cannot be read adds no address, so a tip to it
|
|
12
|
+
// is refused rather than guessed; pin `relayTipAddresses` to decide them yourself.
|
|
13
|
+
import { parseTipConfig } from "./shared/lib/walrus/tip-config.js";
|
|
14
|
+
const TIP_READ_TIMEOUT_MS = 8_000;
|
|
15
|
+
/** Every relay's tip address that answers now, for `network`. */
|
|
16
|
+
export async function readRelayTipAddresses(network, extra = []) {
|
|
17
|
+
const { RELAY_HOSTS, relayHost } = await import("./walrus.js");
|
|
18
|
+
let own = null;
|
|
19
|
+
try {
|
|
20
|
+
own = relayHost(network);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
own = null;
|
|
24
|
+
}
|
|
25
|
+
const hosts = [...new Set([...(own === null ? [] : [own]), ...(RELAY_HOSTS[network] ?? []), ...extra])];
|
|
26
|
+
const found = await Promise.all(hosts.map(async (host) => {
|
|
27
|
+
try {
|
|
28
|
+
const res = await fetch(new URL("/v1/tip-config", host), { signal: AbortSignal.timeout(TIP_READ_TIMEOUT_MS) });
|
|
29
|
+
if (!res.ok)
|
|
30
|
+
return null;
|
|
31
|
+
const tip = parseTipConfig(await res.json());
|
|
32
|
+
return tip.kind === "const" || tip.kind === "linear" ? tip.address : null;
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
}));
|
|
38
|
+
return [...new Set(found.filter((a) => a !== null && a !== ""))];
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* The live facts for `network`, read once and kept: the package, the system object and the tip
|
|
42
|
+
* addresses do not change between two transactions of one upload. `operator` is the address the
|
|
43
|
+
* encoded-length question is asked as (a read; nothing is signed).
|
|
44
|
+
*/
|
|
45
|
+
export async function sponsorFacts(network, operator) {
|
|
46
|
+
const [{ packageConfig, payingClient, encodedLength }, { relayHost }, { walrusClient, readBlobLease }] = await Promise.all([
|
|
47
|
+
import("./upload-wallet-chain.js"),
|
|
48
|
+
import("./walrus.js"),
|
|
49
|
+
import("./extend-chain.js"),
|
|
50
|
+
]);
|
|
51
|
+
const client = payingClient(network, relayHost(network));
|
|
52
|
+
const [system, relayTipAddresses] = await Promise.all([client.walrus.systemObject(), readRelayTipAddresses(network)]);
|
|
53
|
+
const lengths = new Map();
|
|
54
|
+
return {
|
|
55
|
+
walrusPackageId: system.package_id,
|
|
56
|
+
systemObjectId: packageConfig(network).systemObjectId,
|
|
57
|
+
relayTipAddresses,
|
|
58
|
+
async encodedLength(size) {
|
|
59
|
+
const known = lengths.get(size);
|
|
60
|
+
if (known !== undefined)
|
|
61
|
+
return known;
|
|
62
|
+
const n = await encodedLength(client, operator, size);
|
|
63
|
+
lengths.set(size, n);
|
|
64
|
+
return n;
|
|
65
|
+
},
|
|
66
|
+
async blobSize(objectId) {
|
|
67
|
+
try {
|
|
68
|
+
return (await readBlobLease(walrusClient(network), objectId)).size;
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
},
|
|
74
|
+
};
|
|
75
|
+
}
|