@parity/ppn 0.2.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (147) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +84 -0
  3. package/config/ports.env +128 -0
  4. package/config/versions.env +120 -0
  5. package/dist/bin.d.ts +2 -0
  6. package/dist/bin.js +30 -0
  7. package/dist/bin.js.map +1 -0
  8. package/dist/cli.d.ts +3 -0
  9. package/dist/cli.js +471 -0
  10. package/dist/cli.js.map +1 -0
  11. package/dist/commands/bite.d.ts +27 -0
  12. package/dist/commands/bite.js +556 -0
  13. package/dist/commands/bite.js.map +1 -0
  14. package/dist/commands/dashboard.d.ts +2 -0
  15. package/dist/commands/dashboard.js +503 -0
  16. package/dist/commands/dashboard.js.map +1 -0
  17. package/dist/commands/dist.d.ts +7 -0
  18. package/dist/commands/dist.js +121 -0
  19. package/dist/commands/dist.js.map +1 -0
  20. package/dist/commands/fetch.d.ts +11 -0
  21. package/dist/commands/fetch.js +550 -0
  22. package/dist/commands/fetch.js.map +1 -0
  23. package/dist/commands/fork.d.ts +1 -0
  24. package/dist/commands/fork.js +164 -0
  25. package/dist/commands/fork.js.map +1 -0
  26. package/dist/commands/generate.d.ts +7 -0
  27. package/dist/commands/generate.js +201 -0
  28. package/dist/commands/generate.js.map +1 -0
  29. package/dist/commands/genesis-toml.d.ts +1 -0
  30. package/dist/commands/genesis-toml.js +26 -0
  31. package/dist/commands/genesis-toml.js.map +1 -0
  32. package/dist/commands/nginx-conf.d.ts +1 -0
  33. package/dist/commands/nginx-conf.js +32 -0
  34. package/dist/commands/nginx-conf.js.map +1 -0
  35. package/dist/commands/service-context.d.ts +13 -0
  36. package/dist/commands/service-context.js +5 -0
  37. package/dist/commands/service-context.js.map +1 -0
  38. package/dist/commands/service.d.ts +28 -0
  39. package/dist/commands/service.js +807 -0
  40. package/dist/commands/service.js.map +1 -0
  41. package/dist/commands/stamp-spawn.d.ts +7 -0
  42. package/dist/commands/stamp-spawn.js +43 -0
  43. package/dist/commands/stamp-spawn.js.map +1 -0
  44. package/dist/commands/start.d.ts +33 -0
  45. package/dist/commands/start.js +462 -0
  46. package/dist/commands/start.js.map +1 -0
  47. package/dist/commands/upgrade.d.ts +15 -0
  48. package/dist/commands/upgrade.js +101 -0
  49. package/dist/commands/upgrade.js.map +1 -0
  50. package/dist/fork/chains.d.ts +25 -0
  51. package/dist/fork/chains.js +36 -0
  52. package/dist/fork/chains.js.map +1 -0
  53. package/dist/fork/codec.d.ts +36 -0
  54. package/dist/fork/codec.js +122 -0
  55. package/dist/fork/codec.js.map +1 -0
  56. package/dist/fork/manifest.d.ts +13 -0
  57. package/dist/fork/manifest.js +77 -0
  58. package/dist/fork/manifest.js.map +1 -0
  59. package/dist/fork/overrides.d.ts +45 -0
  60. package/dist/fork/overrides.js +255 -0
  61. package/dist/fork/overrides.js.map +1 -0
  62. package/dist/fork/products.d.ts +68 -0
  63. package/dist/fork/products.js +265 -0
  64. package/dist/fork/products.js.map +1 -0
  65. package/dist/fork/rpc.d.ts +25 -0
  66. package/dist/fork/rpc.js +51 -0
  67. package/dist/fork/rpc.js.map +1 -0
  68. package/dist/fork/shared-relay.d.ts +99 -0
  69. package/dist/fork/shared-relay.js +162 -0
  70. package/dist/fork/shared-relay.js.map +1 -0
  71. package/dist/fork/sleep.d.ts +3 -0
  72. package/dist/fork/sleep.js +2 -0
  73. package/dist/fork/sleep.js.map +1 -0
  74. package/dist/fork/validators.d.ts +81 -0
  75. package/dist/fork/validators.js +170 -0
  76. package/dist/fork/validators.js.map +1 -0
  77. package/dist/fork/verify.d.ts +79 -0
  78. package/dist/fork/verify.js +192 -0
  79. package/dist/fork/verify.js.map +1 -0
  80. package/dist/lib/archive.d.ts +8 -0
  81. package/dist/lib/archive.js +40 -0
  82. package/dist/lib/archive.js.map +1 -0
  83. package/dist/lib/fork-bundle-name.d.ts +4 -0
  84. package/dist/lib/fork-bundle-name.js +20 -0
  85. package/dist/lib/fork-bundle-name.js.map +1 -0
  86. package/dist/lib/github.d.ts +48 -0
  87. package/dist/lib/github.js +192 -0
  88. package/dist/lib/github.js.map +1 -0
  89. package/dist/lib/provenance.d.ts +67 -0
  90. package/dist/lib/provenance.js +98 -0
  91. package/dist/lib/provenance.js.map +1 -0
  92. package/dist/lib/spawn-env.d.ts +33 -0
  93. package/dist/lib/spawn-env.js +71 -0
  94. package/dist/lib/spawn-env.js.map +1 -0
  95. package/dist/lib/spawn-stamp.d.ts +34 -0
  96. package/dist/lib/spawn-stamp.js +63 -0
  97. package/dist/lib/spawn-stamp.js.map +1 -0
  98. package/dist/upgrade/chains.d.ts +4 -0
  99. package/dist/upgrade/chains.js +17 -0
  100. package/dist/upgrade/chains.js.map +1 -0
  101. package/dist/upgrade/fund.d.ts +38 -0
  102. package/dist/upgrade/fund.js +119 -0
  103. package/dist/upgrade/fund.js.map +1 -0
  104. package/dist/upgrade/provider-node.d.ts +2 -0
  105. package/dist/upgrade/provider-node.js +7 -0
  106. package/dist/upgrade/provider-node.js.map +1 -0
  107. package/dist/upgrade/signer.d.ts +21 -0
  108. package/dist/upgrade/signer.js +48 -0
  109. package/dist/upgrade/signer.js.map +1 -0
  110. package/dist/upgrade/sudo.d.ts +2 -0
  111. package/dist/upgrade/sudo.js +26 -0
  112. package/dist/upgrade/sudo.js.map +1 -0
  113. package/dist/upgrade/upgrade.d.ts +128 -0
  114. package/dist/upgrade/upgrade.js +539 -0
  115. package/dist/upgrade/upgrade.js.map +1 -0
  116. package/networks/README.md +120 -0
  117. package/networks/devnet.json +113 -0
  118. package/networks/kusama.json +56 -0
  119. package/networks/paseo-next-v2.json +87 -0
  120. package/networks/polkadot.json +57 -0
  121. package/networks/previewnet.json +186 -0
  122. package/package.json +54 -0
  123. package/scripts/assign-cores.sh +12 -0
  124. package/scripts/dashboard.sh +11 -0
  125. package/scripts/docker-entrypoint.sh +52 -0
  126. package/scripts/dub/postgres.sh +116 -0
  127. package/scripts/dub/service.sh +202 -0
  128. package/scripts/ensure-dot-cli.sh +23 -0
  129. package/scripts/eth-rpc.sh +45 -0
  130. package/scripts/force-open-hrmp.sh +11 -0
  131. package/scripts/grant-invites.sh +11 -0
  132. package/scripts/increase-people-lite-attestation-allowance.sh +11 -0
  133. package/scripts/install.sh +12 -0
  134. package/scripts/ipfs-daemon.sh +48 -0
  135. package/scripts/ipfs-swarm.sh +48 -0
  136. package/scripts/kill-port.sh +11 -0
  137. package/scripts/lib/workspace.sh +47 -0
  138. package/scripts/omni-node.sh +112 -0
  139. package/scripts/patch-bootnodes.sh +11 -0
  140. package/scripts/pin-bulletin-products.sh +11 -0
  141. package/scripts/pin-design-families.sh +144 -0
  142. package/scripts/set-dispatcher-address.sh +11 -0
  143. package/scripts/storage-provider-node.sh +11 -0
  144. package/web/assets/index-BW4b1s2y.js +7 -0
  145. package/web/assets/index-X3pZpnYk.css +1 -0
  146. package/web/index.html +13 -0
  147. package/zombienet-configs/local-dev.toml +253 -0
@@ -0,0 +1,807 @@
1
+ // `ppn service <name>` — the processes zombienet starts alongside the nodes.
2
+ //
3
+ // zombienet's `custom_processes` spawns a command path, so each of these keeps a one-line
4
+ // launcher under scripts/. The launcher is all that stays in shell; the decisions live
5
+ // here, next to the descriptor they are made from.
6
+ //
7
+ // zombie-cli does not forward environment variables to custom processes, which is why the
8
+ // network selector is read off disk (config/ports.local.env, written by `make start`)
9
+ // rather than inherited.
10
+ import fs from 'node:fs';
11
+ import os from 'node:os';
12
+ import path from 'node:path';
13
+ import { execFileSync, spawn } from 'node:child_process';
14
+ import { loadCurrentNetwork, readEnvFile, hrmpChannels, repoRoot, workspaceRoot, BOB_SS58, } from '@parity/ppn-network-config';
15
+ import { forkBundleName } from '../lib/fork-bundle-name.js';
16
+ const REPO = repoRoot();
17
+ /** Mutable state — binaries, chain data, bundles — lives in the workspace, not the package. */
18
+ const WS = workspaceRoot();
19
+ const SECRETS_FILE = '/etc/ppn/secrets.env';
20
+ function loadContext() {
21
+ // The deployable profile's keys; server/redeploy.sh exports them, a local run does not.
22
+ if (fs.existsSync(SECRETS_FILE)) {
23
+ for (const [k, v] of Object.entries(readEnvFile(SECRETS_FILE)))
24
+ process.env[k] ??= v;
25
+ }
26
+ const ports = readEnvFile(path.join(REPO, 'config', 'ports.env'));
27
+ const localOverride = path.join(WS, 'config', 'ports.local.env');
28
+ if (fs.existsSync(localOverride)) {
29
+ for (const [k, v] of Object.entries(readEnvFile(localOverride))) {
30
+ ports[k] = v;
31
+ process.env[k] ??= v;
32
+ }
33
+ }
34
+ const net = loadCurrentNetwork();
35
+ // `make start` exports BIN for the custom processes, and the test harness relies on it
36
+ // to point a service at a fixture directory.
37
+ const binDir = process.env.BIN
38
+ ? path.resolve(process.env.BIN)
39
+ : path.join(WS, 'bin', net.name === 'previewnet' ? '' : net.name);
40
+ return {
41
+ net,
42
+ ports,
43
+ binDir,
44
+ sharedBinDir: net.name === 'previewnet' || process.env.BIN ? binDir : path.dirname(binDir),
45
+ relayWs: process.env.RELAY_WS || `ws://127.0.0.1:${ports.RELAY_ALICE_PORT}`,
46
+ sudoUri: process.env.PPN_SUDO_URI || '//Alice',
47
+ };
48
+ }
49
+ const services = {
50
+ 'assign-cores': assignCores,
51
+ dashboard: async (ctx) => (await import('./dashboard.js')).dashboard(ctx),
52
+ 'force-open-hrmp': forceOpenHrmp,
53
+ 'increase-people-lite-attestation-allowance': increaseAttestationAllowance,
54
+ 'grant-invites': grantInvites,
55
+ 'set-dispatcher-address': setDispatcherAddress,
56
+ 'patch-bootnodes': patchBootnodes,
57
+ 'storage-provider-node': storageProviderNode,
58
+ 'pin-bulletin-products': pinBulletinProducts,
59
+ };
60
+ export { pinBulletinProducts };
61
+ export function serviceNames() {
62
+ return Object.keys(services);
63
+ }
64
+ export async function run(args, deps = {}) {
65
+ const name = args[0];
66
+ const service = services[name];
67
+ if (!service) {
68
+ throw new Error(`unknown service "${name ?? ''}" (one of: ${serviceNames().join(', ')})\n` +
69
+ ' Services not listed here are still shell scripts under scripts/.');
70
+ }
71
+ await service(loadContext(), deps);
72
+ }
73
+ // ---------------------------------------------------------------------------
74
+ // assign-cores — Asset Hub's 2-second blocks
75
+ // ---------------------------------------------------------------------------
76
+ /**
77
+ * Give Asset Hub two extra cores so it can author at 2 seconds via elastic scaling.
78
+ * zombienet assigns it one; these are cores 0 and 1 at 100% each (57600 parts).
79
+ *
80
+ * Which para id gets them comes from the descriptor — this used to be a shell script
81
+ * exporting an env var into a Node script, with the id fetched by a third process.
82
+ */
83
+ async function assignCores(ctx, _deps = {}) {
84
+ const assetHub = ctx.net.parachains.find((p) => p.key === 'asset-hub');
85
+ if (!assetHub) {
86
+ console.log(`assign-cores: ${ctx.net.name} has no asset-hub — nothing to assign`);
87
+ return;
88
+ }
89
+ const waitSeconds = Number(process.env.WAIT_SECONDS ?? 30);
90
+ if (waitSeconds > 0) {
91
+ console.log(`assign-cores: waiting ${waitSeconds}s for the relay chain to be ready...`);
92
+ await new Promise((r) => setTimeout(r, waitSeconds * 1000));
93
+ }
94
+ const { ApiPromise, WsProvider, Keyring } = await import('@polkadot/api');
95
+ console.log(`assign-cores: relay ${ctx.relayWs}, para ${assetHub.paraId}`);
96
+ const api = await ApiPromise.create({ provider: new WsProvider(ctx.relayWs) });
97
+ try {
98
+ console.log(` connected to ${(await api.rpc.system.chain()).toString()}`);
99
+ const signer = new Keyring({ type: 'sr25519' }).addFromUri(ctx.sudoUri);
100
+ // assignCore(coreIndex, begin=0 (immediately), [[assignment, parts]], endHint=null)
101
+ const assign = (core) => api.tx.coretime.assignCore(core, 0, [[{ Task: assetHub.paraId }, 57600]], null);
102
+ const call = api.tx.sudo.sudo(api.tx.utility.batch([assign(0), assign(1)]));
103
+ await new Promise((resolve, reject) => {
104
+ call
105
+ .signAndSend(signer, ({ status, dispatchError }) => {
106
+ if (status.isInBlock)
107
+ console.log(` included in ${status.asInBlock.toString()}`);
108
+ if (!status.isFinalized)
109
+ return;
110
+ console.log(` finalized in ${status.asFinalized.toString()}`);
111
+ if (!dispatchError)
112
+ return resolve();
113
+ if (dispatchError.isModule) {
114
+ const e = api.registry.findMetaError(dispatchError.asModule);
115
+ reject(new Error(`${e.section}.${e.name}: ${e.docs.join(' ')}`));
116
+ }
117
+ else {
118
+ reject(new Error(dispatchError.toString()));
119
+ }
120
+ })
121
+ .catch(reject);
122
+ });
123
+ console.log(`assign-cores: para ${assetHub.paraId} now has 3 cores (1 from zombienet + 2 here) — ~2s blocks`);
124
+ }
125
+ finally {
126
+ await api.disconnect();
127
+ }
128
+ }
129
+ // ---------------------------------------------------------------------------
130
+ // Shared helpers
131
+ // ---------------------------------------------------------------------------
132
+ const sleep = (seconds) => new Promise((r) => setTimeout(r, seconds * 1000));
133
+ /** Reject after `seconds` if the promise has not settled, so a silent stall becomes an error. */
134
+ function withDeadline(promise, seconds, why) {
135
+ let timer;
136
+ return Promise.race([
137
+ promise,
138
+ new Promise((_, reject) => {
139
+ timer = setTimeout(() => reject(new Error(why)), seconds * 1000);
140
+ }),
141
+ ]).finally(() => clearTimeout(timer));
142
+ }
143
+ async function waitSeconds(label, fallback) {
144
+ const s = Number(process.env.WAIT_SECONDS ?? fallback);
145
+ if (s <= 0)
146
+ return;
147
+ console.log(` waiting ${s}s for ${label} to be ready...`);
148
+ await sleep(s);
149
+ }
150
+ /** Submit a sudo-wrapped batch and resolve once it is finalized, surfacing module errors. */
151
+ async function submitSudo(api, signer, call) {
152
+ // Several services start together and all sign as the same sudo account, so two can pick
153
+ // the same nonce and the node rejects the loser: "Priority is too low — too low priority to
154
+ // replace another transaction already in the pool". It is transient contention between
155
+ // independent processes, not a bad call, so back off and take a fresh nonce. Without this,
156
+ // force-open-hrmp lost the race and opened nothing while reporting success.
157
+ const transient = (e) => /priority is too low|temporarily banned|1014|already imported|not included within/i.test(e instanceof Error ? e.message : String(e));
158
+ for (let attempt = 0;; attempt++) {
159
+ try {
160
+ // Never wait forever. A transaction can be accepted into the pool and then simply
161
+ // never included — another service having taken the same nonce is enough — and
162
+ // signAndSend just stays silent, so the service hangs with no error at all. That is
163
+ // how force-open-hrmp ended a run having printed its intentions and nothing else.
164
+ await withDeadline(submitOnce(api, signer, call), 120, 'not included within 120s');
165
+ return;
166
+ }
167
+ catch (err) {
168
+ if (attempt >= 5 || !transient(err))
169
+ throw err;
170
+ const wait = 3 + attempt * 2;
171
+ console.log(` sudo pool collision, retrying in ${wait}s`);
172
+ await sleep(wait);
173
+ }
174
+ }
175
+ }
176
+ async function submitOnce(api, signer, call) {
177
+ await new Promise((resolve, reject) => {
178
+ call
179
+ // nonce -1 means "next index, counting what is already in the pool". Several services
180
+ // start at once and all sign as the same sudo account, so with an implicit nonce the
181
+ // second one collides with the first and the node rejects it: "Priority is too low —
182
+ // the transaction has too low priority to replace another transaction already in the
183
+ // pool". That rejection is why force-open-hrmp opened nothing while appearing to work.
184
+ .signAndSend(signer, { nonce: -1 }, ({ status, events, dispatchError }) => {
185
+ if (status.isInBlock)
186
+ console.log(` included in ${status.asInBlock.toString()}`);
187
+ if (!status.isFinalized)
188
+ return;
189
+ console.log(` finalized in ${status.asFinalized.toString()}`);
190
+ const describe = (err) => {
191
+ if (err?.isModule) {
192
+ const e = api.registry.findMetaError(err.asModule);
193
+ return `${e.section}.${e.name}: ${e.docs.join(' ')}`;
194
+ }
195
+ return String(err);
196
+ };
197
+ if (dispatchError)
198
+ return reject(new Error(describe(dispatchError)));
199
+ // `dispatchError` only covers the *outer* extrinsic. Wrapped in sudo, and again in
200
+ // utility.batch, a failing inner call leaves the outer one perfectly successful — so
201
+ // checking it alone reports "done" while nothing happened. That is not hypothetical:
202
+ // force-open-hrmp announced four open channels and opened none, and the failure only
203
+ // surfaced later as an XCM test finding every channel CLOSED.
204
+ for (const { event } of events ?? []) {
205
+ if (api.events?.sudo?.Sudid?.is?.(event)) {
206
+ const result = event.data?.[0];
207
+ if (result?.isErr)
208
+ return reject(new Error(`sudo call failed — ${describe(result.asErr)}`));
209
+ }
210
+ if (api.events?.utility?.BatchInterrupted?.is?.(event)) {
211
+ const [index, error] = event.data ?? [];
212
+ return reject(new Error(`batch stopped at call ${index?.toString()} — ${describe(error)}`));
213
+ }
214
+ if (api.events?.system?.ExtrinsicFailed?.is?.(event)) {
215
+ return reject(new Error(describe(event.data?.[0])));
216
+ }
217
+ }
218
+ resolve();
219
+ })
220
+ .catch(reject);
221
+ });
222
+ }
223
+ /**
224
+ * The `dot` CLI signs the two calls that go through it. It cannot take a SURI derivation
225
+ * path, so `//Alice`-style keys are rejected with the reason rather than a codec error
226
+ * deep inside the tool.
227
+ */
228
+ function dotSudoAccount() {
229
+ const uri = process.env.PPN_SUDO_URI;
230
+ if (!uri)
231
+ return 'Alice';
232
+ if (uri.startsWith('//')) {
233
+ throw new Error('PPN_SUDO_URI starts with "//" — the dot CLI does not accept SURI derivation paths.\n' +
234
+ ' Use a BIP39 mnemonic or a 0x-prefixed 32-byte hex seed.');
235
+ }
236
+ const dot = (args) => execFileSync('dot', args, { stdio: ['pipe', 'pipe', 'ignore'] });
237
+ try {
238
+ dot(['account', 'remove', 'ppn-sudo']);
239
+ }
240
+ catch {
241
+ /* not present */
242
+ }
243
+ dot(['account', 'add', 'ppn-sudo', '--env', 'PPN_SUDO_URI']);
244
+ return 'ppn-sudo';
245
+ }
246
+ const dotRun = (args) => execFileSync('dot', args, { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'inherit'] }).trim();
247
+ async function chainReachable(httpUrl, attempts, gapSeconds) {
248
+ for (let i = 0; i < attempts; i++) {
249
+ try {
250
+ const res = await fetch(httpUrl, {
251
+ method: 'POST',
252
+ headers: { 'content-type': 'application/json' },
253
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'system_health', params: [] }),
254
+ signal: AbortSignal.timeout(5000),
255
+ });
256
+ if (res.ok)
257
+ return true;
258
+ }
259
+ catch {
260
+ /* not up yet */
261
+ }
262
+ await sleep(gapSeconds);
263
+ }
264
+ return false;
265
+ }
266
+ // ---------------------------------------------------------------------------
267
+ // force-open-hrmp
268
+ // ---------------------------------------------------------------------------
269
+ /**
270
+ * Open the network's HRMP channels on a running relay. Which channels those are comes from
271
+ * the same list the genesis config is generated from — this used to parse the generated
272
+ * TOML back out of the file to rediscover them.
273
+ */
274
+ async function forceOpenHrmp(ctx, _deps = {}) {
275
+ const channels = hrmpChannels(ctx.net.parachains.map((p) => p.key));
276
+ if (channels.length === 0) {
277
+ console.log(`force-open-hrmp: ${ctx.net.name} declares no channels — nothing to open`);
278
+ return;
279
+ }
280
+ await waitSeconds('the relay chain', 30);
281
+ const { ApiPromise, WsProvider, Keyring } = await import('@polkadot/api');
282
+ console.log(`force-open-hrmp: relay ${ctx.relayWs}, ${channels.length} channel(s)`);
283
+ const api = await ApiPromise.create({ provider: new WsProvider(ctx.relayWs) });
284
+ try {
285
+ console.log(` connected to ${(await api.rpc.system.chain()).toString()}`);
286
+ // A channel cannot be opened for a parachain the relay has not onboarded yet, and the
287
+ // call fails inside the batch — where, wrapped in sudo, it used to look like success.
288
+ // Waiting a fixed number of seconds is a guess about how long registration takes; this
289
+ // waits for the fact itself.
290
+ const wanted = [...new Set(channels.flatMap((c) => [c.sender, c.recipient]))];
291
+ const onboarded = async () => {
292
+ const states = await Promise.all(wanted.map(async (id) => (await api.query.paras.paraLifecycles(id)).toString()));
293
+ return states.every((s) => s === 'Parachain');
294
+ };
295
+ for (let i = 0; i < 60; i++) {
296
+ if (await onboarded())
297
+ break;
298
+ if (i === 0)
299
+ console.log(` waiting for ${wanted.join(', ')} to be onboarded...`);
300
+ if (i === 59)
301
+ throw new Error(`parachains ${wanted.join(', ')} were not onboarded in 5 minutes`);
302
+ await sleep(5);
303
+ }
304
+ console.log(` onboarded: ${wanted.join(', ')}`);
305
+ const signer = new Keyring({ type: 'sr25519' }).addFromUri(ctx.sudoUri);
306
+ const calls = channels.map((c) => api.tx.hrmp.forceOpenHrmpChannel(c.sender, c.recipient, c.maxCapacity, c.maxMessageSize));
307
+ for (const c of channels)
308
+ console.log(` ${c.sender} -> ${c.recipient}`);
309
+ await submitSudo(api, signer, api.tx.sudo.sudo(api.tx.utility.batch(calls)));
310
+ console.log('force-open-hrmp: channels open');
311
+ }
312
+ finally {
313
+ await api.disconnect();
314
+ }
315
+ }
316
+ // ---------------------------------------------------------------------------
317
+ // increase-people-lite-attestation-allowance
318
+ // ---------------------------------------------------------------------------
319
+ /**
320
+ * Grant attestation allowance to the account the identity backend signs PeopleLite.attest
321
+ * with. Runs in both genesis and fork mode: a fork carries the source network's grants,
322
+ * which say nothing about the account signing here. The grant is additive, so re-running
323
+ * it is safe.
324
+ */
325
+ async function increaseAttestationAllowance(ctx, _deps = {}) {
326
+ const ALLOWANCE_COUNT = '1000';
327
+ const profile = process.env.PPN_PROFILE ?? 'local';
328
+ // In deployable mode Alice has been stripped from balances, so granting to her would be
329
+ // silently useless — the recipient must be named.
330
+ if (profile === 'deployable' && !process.env.PPN_ALLOWANCE_SS58) {
331
+ throw new Error('the deployable profile requires PPN_ALLOWANCE_SS58 (the attestation allowance\n' +
332
+ ' recipient) in /etc/ppn/secrets.env');
333
+ }
334
+ const account = process.env.PPN_ALLOWANCE_SS58 ||
335
+ process.env.ALLOWANCE_ACCOUNT ||
336
+ '5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY';
337
+ await waitSeconds('the People chain', 20);
338
+ const peopleWs = `ws://127.0.0.1:${ctx.ports.PEOPLE_PORT}`;
339
+ dotRun(['chain', 'add', 'People', '--rpc', peopleWs]);
340
+ const from = dotSudoAccount();
341
+ console.log(`increase-attestation-allowance: ${ALLOWANCE_COUNT} to ${account}`);
342
+ const encoded = dotRun([
343
+ 'People.tx.PeopleLite.increase_attestation_allowance',
344
+ account,
345
+ ALLOWANCE_COUNT,
346
+ '--encode',
347
+ ]);
348
+ dotRun(['People.tx.Sudo.sudo', encoded, '--from', from]);
349
+ }
350
+ // ---------------------------------------------------------------------------
351
+ // grant-invites
352
+ // ---------------------------------------------------------------------------
353
+ /**
354
+ * Give the identity backend's inviter account invites to hand out, in both dimensions.
355
+ *
356
+ * Without this, invite-tickets-pool is not merely idle — it is actively harmful. It submits a
357
+ * `Utility.force_batch` of `set_invite_ticket` every ~30 seconds regardless, every inner call
358
+ * fails with no invites available (`submitted=1 registered=0 failed=1`, for ever), and the
359
+ * batch still consumes a nonce. Before the inviter was moved off Alice that starved
360
+ * the chain writer out of its own nonce lane and no username could ever land.
361
+ *
362
+ * Sudo, because the origin is `InvitationsOrigin`. Additive, so re-running is safe, which
363
+ * matters in fork mode where the source network's grants say nothing about the account
364
+ * signing here.
365
+ */
366
+ async function grantInvites(ctx, _deps = {}) {
367
+ const INVITE_COUNT = 1000;
368
+ if (!ctx.net.parachains.some((p) => p.key === 'people')) {
369
+ console.log(`grant-invites: ${ctx.net.name} has no people chain — nothing to grant`);
370
+ return;
371
+ }
372
+ // Kept in step with INVITER_ADDRESS in the generated TOML and INVITER_SIGNER_SURI in
373
+ // scripts/dub/service.sh: granting to a different account than the one signing leaves
374
+ // the pool failing exactly as it did before.
375
+ const inviter = process.env.PPN_INVITER_SS58 || BOB_SS58;
376
+ // The dot CLI, not @polkadot/api, for the same reason the allowance grant uses it: People
377
+ // Chain's runtime carries signed extensions polkadot-js does not know (AsPerson,
378
+ // PeopleLiteAuth, AsResources…), and an extrinsic it builds anyway is rejected by
379
+ // validate_transaction with a wasm trap rather than a readable error.
380
+ await waitSeconds('the People chain', 20);
381
+ const peopleWs = `ws://127.0.0.1:${ctx.ports.PEOPLE_PORT}`;
382
+ dotRun(['chain', 'add', 'People', '--rpc', peopleWs]);
383
+ const from = dotSudoAccount();
384
+ // Both dimensions the ticket pool cycles through; each pallet keeps its own invite book.
385
+ const dims = ['ProofOfInk', 'Game'];
386
+ const available = (pallet) => Number(dotRun([`People.query.${pallet}.AvailableInvites`, inviter]).trim() || '0');
387
+ // Submit, then read the invite book back. Every other service that signs as sudo here has
388
+ // taught the same lesson: a submission can be accepted and then lose its nonce to another
389
+ // service starting at the same moment, and reporting success off the submission alone is
390
+ // how force-open-hrmp opened no channels while printing that it had.
391
+ for (let attempt = 1;; attempt++) {
392
+ const short = dims.filter((d) => available(d) < INVITE_COUNT);
393
+ if (short.length === 0) {
394
+ console.log(`grant-invites: ${inviter} holds invites for ${dims.join(' and ')}`);
395
+ return;
396
+ }
397
+ if (attempt > 4) {
398
+ throw new Error(`grant-invites: ${short.join(', ')} still short of invites for ${inviter} after ${attempt - 1} attempts`);
399
+ }
400
+ for (const pallet of short) {
401
+ console.log(`grant-invites: ${INVITE_COUNT} ${pallet} invites to ${inviter}`);
402
+ const encoded = dotRun([`People.tx.${pallet}.grant_invites`, inviter, String(INVITE_COUNT), '--encode']);
403
+ try {
404
+ dotRun(['People.tx.Sudo.sudo', encoded, '--from', from]);
405
+ }
406
+ catch (err) {
407
+ // A rejected submission is not the answer — the next pass reads the invite book and
408
+ // decides. Back-to-back sudo calls collide on the nonce here ("Invalid: Stale") because
409
+ // the tool takes a fresh nonce per call while the previous one is still in the pool,
410
+ // and the allowance grant is signing as the same account at the same moment.
411
+ console.log(` ${pallet} submission rejected (${err.message.split('\n')[0]}), will re-check`);
412
+ }
413
+ // Enough for the previous submission to be in a block, so the next call sees its nonce.
414
+ await sleep(6);
415
+ }
416
+ }
417
+ }
418
+ // ---------------------------------------------------------------------------
419
+ // set-dispatcher-address
420
+ // ---------------------------------------------------------------------------
421
+ /** Point DotnsGateway at the RootGatewayDispatcher this release deployed. */
422
+ async function setDispatcherAddress(ctx, _deps = {}) {
423
+ const addrFile = path.join(ctx.binDir, 'dotns-addresses.json');
424
+ if (!fs.existsSync(addrFile)) {
425
+ console.log(`set-dispatcher-address: no ${addrFile} — skipping (release predates the manifest)`);
426
+ return;
427
+ }
428
+ const dispatcher = JSON.parse(fs.readFileSync(addrFile, 'utf-8')).RootGatewayDispatcher;
429
+ if (!dispatcher) {
430
+ console.log(`set-dispatcher-address: no RootGatewayDispatcher in ${addrFile} — skipping`);
431
+ return;
432
+ }
433
+ await waitSeconds('Asset Hub', 20);
434
+ dotRun(['chain', 'add', 'AssetHub', '--rpc', `ws://127.0.0.1:${ctx.ports.ASSET_HUB_PORT}`]);
435
+ const from = dotSudoAccount();
436
+ console.log(`set-dispatcher-address: DotnsGateway.DispatcherAddress = ${dispatcher}`);
437
+ const encoded = dotRun(['AssetHub.tx.DotnsGateway.set_dispatcher_address', dispatcher, '--encode']);
438
+ dotRun(['AssetHub.tx.Sudo.sudo', encoded, '--from', from]);
439
+ }
440
+ // ---------------------------------------------------------------------------
441
+ // patch-bootnodes
442
+ // ---------------------------------------------------------------------------
443
+ /**
444
+ * zombienet regenerates bootNodes from the running nodes, so the specs it publishes
445
+ * advertise /ip4/127.0.0.1/. Without this, the chainspecs a deployment serves are unusable
446
+ * to anything off the box. It rewrites addresses only; it touches no chain state.
447
+ */
448
+ async function patchBootnodes(ctx, _deps = {}) {
449
+ const hostname = ctx.ports.BOOTNODE_HOSTNAME ?? '127.0.0.1';
450
+ if (hostname === '127.0.0.1') {
451
+ console.log('patch-bootnodes: BOOTNODE_HOSTNAME is 127.0.0.1, nothing to advertise');
452
+ return;
453
+ }
454
+ const dataDir = fs.existsSync('/var/lib/ppn/data')
455
+ ? '/var/lib/ppn/data'
456
+ : path.join(WS, process.env.DATA_DIR ? '' : 'data');
457
+ const dir = process.env.DATA_DIR || dataDir;
458
+ if (!fs.existsSync(dir))
459
+ throw new Error(`DATA_DIR does not exist: ${dir}`);
460
+ // A raw chainspec is any top-level JSON with an id and a bootNodes list. Matching by
461
+ // shape rather than name matters: previewnet's specs are <chain>-local.json, but a fork
462
+ // of a public network carries the source's ids.
463
+ const rawSpecs = () => fs
464
+ .readdirSync(dir)
465
+ .filter((f) => f.endsWith('.json') && !f.endsWith('-plain.json') && f !== 'zombie.json')
466
+ .filter((f) => {
467
+ try {
468
+ const s = JSON.parse(fs.readFileSync(path.join(dir, f), 'utf-8'));
469
+ return Boolean(s?.id) && Array.isArray(s.bootNodes);
470
+ }
471
+ catch {
472
+ return false;
473
+ }
474
+ });
475
+ console.log(`patch-bootnodes: ${dir} -> ${hostname}`);
476
+ for (let waited = 0; rawSpecs().length === 0 && waited < 120; waited += 5) {
477
+ await sleep(5);
478
+ console.log(` waiting for raw chainspecs... (${waited + 5}s)`);
479
+ }
480
+ const specs = rawSpecs();
481
+ if (specs.length === 0)
482
+ throw new Error('no raw chainspecs found after 120s');
483
+ const addrType = /^\d+\.\d+\.\d+\.\d+$/.test(hostname) ? 'ip4' : 'dns4';
484
+ for (const file of specs) {
485
+ const full = path.join(dir, file);
486
+ const spec = JSON.parse(fs.readFileSync(full, 'utf-8'));
487
+ if (!spec.bootNodes?.length) {
488
+ console.log(` ${file}: no bootNodes to patch`);
489
+ continue;
490
+ }
491
+ spec.bootNodes = spec.bootNodes.map((bn) => bn.replaceAll('/ip4/127.0.0.1/', `/${addrType}/${hostname}/`));
492
+ fs.writeFileSync(full, JSON.stringify(spec, null, 2) + '\n');
493
+ console.log(` ${file}: ${spec.bootNodes.length} bootNode(s) -> ${addrType}/${hostname}`);
494
+ }
495
+ }
496
+ // ---------------------------------------------------------------------------
497
+ // storage-provider-node
498
+ // ---------------------------------------------------------------------------
499
+ /**
500
+ * Run the Web3 Storage provider. Mostly a launcher, but it decides three things: which
501
+ * binary (release or a sibling dev build), where content lives (disk or in-memory, which
502
+ * follows DATA_DIR so genesis and fork stay separate), and the multiaddr it advertises —
503
+ * which must match what the genesis preset registered, or the node re-syncs it to its
504
+ * loopback bind address and clients can no longer reach it.
505
+ */
506
+ async function storageProviderNode(ctx, _deps = {}) {
507
+ let binary = path.join(ctx.binDir, 'storage-provider-node');
508
+ if (!fs.existsSync(binary)) {
509
+ const sibling = path.join(WS, '..', 'web3-storage', 'target', 'release', 'storage-provider-node');
510
+ if (!fs.existsSync(sibling)) {
511
+ throw new Error(`storage-provider-node not found.\n` +
512
+ ` Expected at: ${binary}\n` +
513
+ ` Or fallback at: ${sibling}\n` +
514
+ ' To build it: (cd ../web3-storage && cargo build --release -p storage-provider-node)');
515
+ }
516
+ binary = sibling;
517
+ console.log(` using sibling build: ${binary}`);
518
+ }
519
+ const keyfile = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'ppn-sp-')), 'key');
520
+ fs.writeFileSync(keyfile, '//Alice\n', { mode: 0o600 });
521
+ process.on('exit', () => fs.rmSync(path.dirname(keyfile), { recursive: true, force: true }));
522
+ const chainPort = ctx.ports.WEB3_STORAGE_PORT;
523
+ console.log(`storage-provider-node: waiting for the web3-storage chain on 127.0.0.1:${chainPort}...`);
524
+ if (await chainReachable(`http://127.0.0.1:${chainPort}`, 60, 2))
525
+ console.log(' chain reachable');
526
+ let publicMultiaddr = process.env.PUBLIC_MULTIADDR ?? '';
527
+ const hostname = ctx.ports.BOOTNODE_HOSTNAME ?? '127.0.0.1';
528
+ if (!publicMultiaddr && hostname !== '127.0.0.1') {
529
+ publicMultiaddr = `/dns4/${hostname}/tcp/443/tls/http/http-path/web3-storage-provider`;
530
+ }
531
+ const inMemory = (ctx.ports.WEB3_STORAGE_PROVIDER_STORAGE_MODE ?? 'disk') === 'inmemory';
532
+ const storageArgs = ['--storage-mode', 'inmemory'];
533
+ if (!inMemory) {
534
+ const storagePath = process.env.STORAGE_PATH ||
535
+ ctx.ports.WEB3_STORAGE_PROVIDER_DATA_DIR ||
536
+ path.join(process.env.DATA_DIR || ctx.ports.PPN_DATA_DIR || path.join(WS, 'data'), 'web3-storage-provider');
537
+ fs.mkdirSync(storagePath, { recursive: true });
538
+ storageArgs.length = 0;
539
+ storageArgs.push('--storage-mode', 'disk', '--storage-path', storagePath);
540
+ }
541
+ const args = [
542
+ '--keyfile', keyfile,
543
+ ...storageArgs,
544
+ '--bind-addr', `127.0.0.1:${ctx.ports.WEB3_STORAGE_PROVIDER_PORT}`,
545
+ '--chain-rpc', `ws://127.0.0.1:${chainPort}`,
546
+ ...(publicMultiaddr ? ['--public-multiaddr', publicMultiaddr] : []),
547
+ '--enable-checkpoint-coordinator',
548
+ ];
549
+ console.log(` storage: ${storageArgs.join(' ')}`);
550
+ if (publicMultiaddr)
551
+ console.log(` advertising: ${publicMultiaddr}`);
552
+ // Replaces this process for the lifetime of the network, the way the wrapper's exec did.
553
+ const child = spawn(binary, args, {
554
+ stdio: 'inherit',
555
+ env: { ...process.env, RUST_LOG: process.env.RUST_LOG ?? 'info' },
556
+ });
557
+ await new Promise((resolve, reject) => {
558
+ child.on('exit', (code) => (code === 0 ? resolve() : reject(new Error(`storage-provider-node exited ${code}`))));
559
+ child.on('error', reject);
560
+ });
561
+ }
562
+ // ---------------------------------------------------------------------------
563
+ // pin-bulletin-products
564
+ // ---------------------------------------------------------------------------
565
+ /**
566
+ * Import the DotNS products a forked bulletin cannot serve on its own.
567
+ *
568
+ * A fork carries chain state but not bulletin's stored bytes — those live in block bodies
569
+ * and the bite is a warp sync. So a forked bulletin lists content it does not hold. Copying
570
+ * all of bulletin is not viable (35 GiB on paseo-next-v2), so this copies only what DotNS
571
+ * points at, and only the versions still within bulletin's retention window.
572
+ *
573
+ * Which CIDs are needed is resolved from the fork's own state, so it never guesses; only
574
+ * the bytes come from the source, over HTTP. Best effort by design — it must never block a
575
+ * spawn, so every failure path returns rather than throwing.
576
+ */
577
+ async function pinBulletinProducts(ctx, deps = {}) {
578
+ if (process.env.PRODUCT_SYNC === '0') {
579
+ console.log('pin-bulletin-products: PRODUCT_SYNC=0, skipping');
580
+ return;
581
+ }
582
+ // Bundles are per network, previewnet included — the same rule `ppn start --fork` uses.
583
+ // Reading only one hard-coded path made this service announce "not a fork, nothing to do"
584
+ // on every other network's fork, indistinguishable from a fork with genuinely no products.
585
+ const forkDir = process.env.FORK_DIR || path.join(WS, forkBundleName(ctx.net.name));
586
+ const manifestPath = path.join(forkDir, 'manifest.json');
587
+ if (!fs.existsSync(manifestPath)) {
588
+ console.log(`pin-bulletin-products: no ${manifestPath} — not a fork, nothing to do`);
589
+ return;
590
+ }
591
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8'));
592
+ // Every DotNS deployment has its own resolver. The descriptor states it; a genesis network
593
+ // also derives one into the release's address manifest, and the two must agree — a resolver
594
+ // that exists in neither place is the honest failure, but one that differs between them
595
+ // would import a deployment nobody asked for and say nothing.
596
+ const { loadNetwork } = await import('@parity/ppn-network-config');
597
+ const bundleNet = loadNetwork(manifest.network ?? 'previewnet');
598
+ let resolver = bundleNet.dotns?.resolver;
599
+ const addrFile = path.join(ctx.binDir, 'dotns-addresses.json');
600
+ const derived = fs.existsSync(addrFile)
601
+ ? JSON.parse(fs.readFileSync(addrFile, 'utf-8')).DotnsContentResolver
602
+ : undefined;
603
+ if (resolver && derived && resolver.toLowerCase() !== String(derived).toLowerCase()) {
604
+ console.error(`pin-bulletin-products: ${bundleNet.name} declares resolver ${resolver}, but ` +
605
+ `${addrFile} says ${derived}. One of them is stale; refusing to import against a guess.`);
606
+ return;
607
+ }
608
+ if (!resolver)
609
+ resolver = derived;
610
+ if (!resolver) {
611
+ console.log(`pin-bulletin-products: no resolver for ${bundleNet.name} — skipping`);
612
+ return;
613
+ }
614
+ // Where the bytes come from. The bundle records the URL it was bitten from, which for
615
+ // previewnet and devnet is also their IPFS gateway — but that is a coincidence of how those
616
+ // two are hosted, not a rule. paseo-next-v2 is bitten from https://dot.li, a single-page app
617
+ // that answers *every* path with the same 20 KB of its own HTML, status 200 and all: asking
618
+ // it for a CAR does not 404, it quietly returns markup. So a network whose gateway lives
619
+ // somewhere else names it, rather than being trusted to fail loudly.
620
+ const gateway = process.env.PRODUCT_SOURCE_GATEWAY || bundleNet.dotns?.gateway || manifest.source;
621
+ const ipfsApiPort = ctx.ports.IPFS_API_PORT;
622
+ const ipfsApi = `/ip4/127.0.0.1/tcp/${ipfsApiPort}`;
623
+ const assetHub = `http://127.0.0.1:${ctx.ports.ASSET_HUB_PORT}`;
624
+ const bulletin = `http://127.0.0.1:${ctx.ports.BULLETIN_PORT}`;
625
+ console.log(`pin-bulletin-products: resolver ${resolver}`);
626
+ console.log(` resolving from the fork: ${assetHub} + ${bulletin}`);
627
+ console.log(` fetching bytes from: ${gateway}`);
628
+ // Probe the API socket, not `ipfs id`: that succeeds in offline mode too by opening the
629
+ // repo directly, and treating it as "daemon ready" is how a second process ends up
630
+ // holding repo.lock and making every later pin fail.
631
+ const apiUp = async () => {
632
+ try {
633
+ const r = await fetch(`http://127.0.0.1:${ipfsApiPort}/api/v0/id`, {
634
+ method: 'POST',
635
+ signal: AbortSignal.timeout(5000),
636
+ });
637
+ return r.ok;
638
+ }
639
+ catch {
640
+ return false;
641
+ }
642
+ };
643
+ for (let i = 0; i < 60; i++) {
644
+ if ((await apiUp()) && (await chainReachable(assetHub, 1, 0)) && (await chainReachable(bulletin, 1, 0)))
645
+ break;
646
+ await sleep(5);
647
+ }
648
+ const scanProducts = deps.scanProducts ?? (await import('../fork/products.js')).scanProducts;
649
+ let scan;
650
+ try {
651
+ scan = await scanProducts(assetHub, bulletin, resolver);
652
+ }
653
+ catch (err) {
654
+ console.log(` could not resolve products, skipping: ${err instanceof Error ? err.message : err}`);
655
+ return;
656
+ }
657
+ if (scan.resolver.toLowerCase() !== resolver.toLowerCase()) {
658
+ console.log(` ${resolver} held nothing; using ${scan.resolver} found on chain`);
659
+ }
660
+ console.log(` ${scan.records} contenthash records, ${scan.bulletinEntries} bulletin entries -> ` +
661
+ `${scan.cids.length} products (${scan.unmatched} records no longer retained)`);
662
+ if (scan.records === 0) {
663
+ console.log(' No contenthash records on any contract — this network has no registered products.');
664
+ }
665
+ const limit = Number(process.env.PRODUCT_SYNC_LIMIT ?? scan.cids.length);
666
+ const cids = scan.cids.slice(0, limit);
667
+ // Nothing to import still ends with the summary line below, because "no products" is a real
668
+ // outcome — a source network wiped an hour ago has none — and a reader waiting for the
669
+ // summary cannot tell a service that finished with nothing to do from one that died before
670
+ // printing it. Returning silently here is what made the fork-e2e leg fail with "product
671
+ // import never reported" against a freshly redeployed previewnet.
672
+ if (cids.length === 0) {
673
+ console.log('pin-bulletin-products: imported 0, failed 0 — 0/0 served locally (nothing to import)');
674
+ return;
675
+ }
676
+ console.log(` ${cids.length} products to import`);
677
+ const ipfsBin = path.join(ctx.sharedBinDir, 'ipfs');
678
+ // kubo locates its repo through IPFS_PATH, falling back to $HOME/.ipfs. zombienet starts
679
+ // custom processes without HOME, so without this every call dies with "$HOME is not
680
+ // defined" before it reads the CAR — visible only as EPIPE. --api makes this a client
681
+ // call that never opens the repo, but kubo resolves the path before it looks at --api.
682
+ const ipfsEnv = {
683
+ ...process.env,
684
+ IPFS_PATH: process.env.IPFS_PATH ?? path.join(ctx.sharedBinDir, '.ipfs'),
685
+ };
686
+ let imported = 0;
687
+ let failed = 0;
688
+ let retried = 0;
689
+ let firstError = '';
690
+ /**
691
+ * Fetch one product's CAR from the source and import it. Returns null on success, or the
692
+ * reason it failed.
693
+ *
694
+ * The fetch and the import are one unit, because the failure worth retrying is a *truncated*
695
+ * CAR. `?format=car` comes back chunked with no Content-Length, so a gateway that abandons a
696
+ * DAG traversal part-way ends the stream cleanly: a well-formed HTTP 200 carrying an
697
+ * incomplete CAR. Nothing in the status, headers or length says so — kubo is the first thing
698
+ * to notice, and reports `unexpected EOF` after the last block it parsed whole. Re-running
699
+ * the import on the same bytes would fail identically, so a retry has to re-fetch.
700
+ */
701
+ const importProduct = async (cid) => {
702
+ try {
703
+ const res = await fetch(`${gateway}/ipfs/${cid}?format=car`, { signal: AbortSignal.timeout(300_000) });
704
+ if (!res.ok)
705
+ throw new Error(`HTTP ${res.status}`);
706
+ const car = Buffer.from(await res.arrayBuffer());
707
+ // A gateway under pressure answers 200 and then sends nothing — the plain fetch of the
708
+ // same CID 504s. An empty body is not a product; importing it "succeeds" and the miss
709
+ // only surfaces later as unservable, blamed on the fork instead of the source.
710
+ if (car.length === 0)
711
+ throw new Error('gateway returned an empty CAR (source timeout)');
712
+ // --allow-big-block: a product's CAR contains blocks over kubo's 1 MiB bitswap limit
713
+ // and the import is refused outright without it. The imported root is byte-identical
714
+ // either way; the limit only affects bitswap exchange, and the gateway reads these
715
+ // over HTTP.
716
+ // Keep stderr: when kubo rejects the import it writes the reason there and exits
717
+ // before reading the CAR off stdin, so the only error Node raises is a bare EPIPE.
718
+ // Ignoring stderr turns every diagnosable failure into that one useless word.
719
+ try {
720
+ execFileSync(ipfsBin, ['--api', ipfsApi, 'dag', 'import', '--pin-roots=true', '--allow-big-block'], {
721
+ input: car,
722
+ stdio: ['pipe', 'ignore', 'pipe'],
723
+ maxBuffer: 512 * 1024 * 1024,
724
+ env: ipfsEnv,
725
+ });
726
+ }
727
+ catch (err) {
728
+ const stderr = err.stderr?.toString().trim();
729
+ throw stderr ? new Error(stderr) : err;
730
+ }
731
+ return null;
732
+ }
733
+ catch (err) {
734
+ return err instanceof Error ? err.message : String(err);
735
+ }
736
+ };
737
+ for (const cid of cids) {
738
+ let reason = await importProduct(cid);
739
+ if (reason) {
740
+ // One retry, like the serve pass below. A truncation is a fact about one stream from a
741
+ // loaded gateway, not about the bytes: the block a real run choked on fetched cleanly
742
+ // afterwards. The pause is so a gateway that just gave up is not asked again instantly.
743
+ await new Promise((r) => setTimeout(r, 1000));
744
+ const second = await importProduct(cid);
745
+ if (second === null) {
746
+ retried++;
747
+ console.log(` imported on retry: ${cid} (first attempt: ${reason})`);
748
+ reason = null;
749
+ }
750
+ else {
751
+ reason = second;
752
+ }
753
+ }
754
+ if (reason === null) {
755
+ imported++;
756
+ if (imported % 25 === 0)
757
+ console.log(` imported ${imported}/${cids.length}`);
758
+ }
759
+ else {
760
+ // Keep the first reason. Swallowing it entirely turns "116 of 116 failed" into a
761
+ // number with no cause, and the summary below can still read "116/116 served
762
+ // locally" because ipfs-swarm lets the gateway fetch from the source network on
763
+ // demand — so a total import failure can look like a healthy run.
764
+ if (failed === 0)
765
+ firstError = reason;
766
+ failed++;
767
+ }
768
+ }
769
+ if (failed > 0)
770
+ console.log(` first failure: ${firstError}`);
771
+ // Reported on its own line, not folded into the summary below: that line's shape is matched
772
+ // by the fork-e2e gate and by tests, and a retry count is diagnostic rather than a result.
773
+ if (retried > 0)
774
+ console.log(` ${retried} product(s) imported only on the second attempt`);
775
+ // Importing is not the same as serving: a pin can succeed while the gateway cannot return
776
+ // the content. Ask the fork's own gateway for what was just pinned. One retry pass for
777
+ // the misses: with the import succeeded the bytes are local, so a failed probe is nearly
778
+ // always the gateway momentarily busy — a 377-CID sweep reliably trips one timeout, and a
779
+ // single flaky probe should not read as a missing product.
780
+ const serve = async (cid) => {
781
+ try {
782
+ const r = await fetch(`http://127.0.0.1:${ctx.ports.IPFS_GATEWAY_PORT}/ipfs/${cid}`, {
783
+ signal: AbortSignal.timeout(30_000),
784
+ });
785
+ return r.ok;
786
+ }
787
+ catch {
788
+ return false;
789
+ }
790
+ };
791
+ let served = 0;
792
+ const misses = [];
793
+ for (const cid of cids) {
794
+ if (await serve(cid))
795
+ served++;
796
+ else
797
+ misses.push(cid);
798
+ }
799
+ for (const cid of misses) {
800
+ if (await serve(cid))
801
+ served++;
802
+ else
803
+ console.log(` not served after retry: ${cid}`);
804
+ }
805
+ console.log(`pin-bulletin-products: imported ${imported}, failed ${failed} — ${served}/${cids.length} served locally`);
806
+ }
807
+ //# sourceMappingURL=service.js.map