Repository navigation
Expand file tree
/
Copy pathrollback-contracts.cjs
More file actions
483 lines (432 loc) · 15.6 KB
/
Copy pathrollback-contracts.cjs
File metadata and controls
483 lines (432 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
#!/usr/bin/env node
'use strict';
/**
* rollback-contracts.cjs
*
* Rolls the backend back to a previous set of Soroban contract IDs.
*
* IMPORTANT — Soroban contracts are immutable:
* Once a contract is deployed to the Stellar/Soroban network it cannot be
* undeployed, upgraded in place, or deleted. "Rolling back a deployment"
* therefore does NOT mean removing the new contracts from the chain. It
* means pointing the backend (environment variables / Kubernetes ConfigMap)
* back at the *previous* contract IDs so the application talks to the older,
* known-good contract instances again.
*
* The newly deployed contracts simply become unused. They remain on-chain
* forever and can be re-adopted later by pointing the backend at them again.
*
* What this script does:
* 1. Reads a previous contract-ids.env backup file.
* 2. Verifies each old contract still exists on-chain (via Soroban RPC).
* 3. Updates the backend environment / ConfigMap to the previous contract IDs.
*
* Contract-ID keys are normalised to the canonical `STELLAR_CONTRACT_*` names
* the backend reads, so backups written by either deploy path are supported:
* STELLAR_CONTRACT_VAULT_REGISTRY (canonical; both deploy paths)
* VAULT_REGISTRY_CONTRACT_ID (legacy SDK deployer)
* vault_registry (legacy bash deployer)
*
* Usage:
* node scripts/rollback-contracts.cjs \
* --backup ./backups/contract-ids.env.2024-01-01T00-00-00Z \
* [--target-env .env] \
* [--configmap my-backend-config] \
* [--namespace synapsvault] \
* [--rpc-url https://soroban-testnet.stellar.org] \
* [--network testnet] \
* [--dry-run]
*
* Exit codes:
* 0 success
* 1 usage / configuration error
* 2 verification failure (one or more old contracts missing on-chain)
* 3 environment / ConfigMap update failure
*/
const fs = require('fs');
const path = require('path');
const { execFileSync } = require('child_process');
// ---------------------------------------------------------------------------
// Minimal .env parser (no external dependencies).
// ---------------------------------------------------------------------------
function parseEnvFile(contents) {
const result = {};
const lines = contents.split(/\r?\n/);
for (const rawLine of lines) {
const line = rawLine.trim();
if (!line || line.startsWith('#')) continue;
const eq = line.indexOf('=');
if (eq === -1) continue;
const key = line.slice(0, eq).trim();
let value = line.slice(eq + 1).trim();
// Strip surrounding quotes if present.
if (
(value.startsWith('"') && value.endsWith('"')) ||
(value.startsWith("'") && value.endsWith("'"))
) {
value = value.slice(1, -1);
}
result[key] = value;
}
return result;
}
function readEnvFile(filePath) {
if (!fs.existsSync(filePath)) {
throw new Error(`Env file not found: ${filePath}`);
}
return parseEnvFile(fs.readFileSync(filePath, 'utf8'));
}
// ---------------------------------------------------------------------------
// Argument parsing.
// ---------------------------------------------------------------------------
function parseArgs(argv) {
const args = {
backup: null,
envFile: '.env',
configmap: null,
namespace: 'synapsvault',
rpcUrl: process.env.SOROBAN_RPC_URL || null,
network: process.env.STELLAR_NETWORK || 'testnet',
dryRun: false,
};
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
const next = () => {
if (i + 1 >= argv.length) {
throw new Error(`Missing value for argument: ${arg}`);
}
return argv[++i];
};
switch (arg) {
case '--backup':
args.backup = next();
break;
// Node >= 22 intercepts a literal `--env-file` anywhere in argv, so
// `--target-env` is the portable spelling; `--env-file` is kept for Node 20.
case '--target-env':
case '--env-file':
args.envFile = next();
break;
case '--configmap':
args.configmap = next();
break;
case '--namespace':
args.namespace = next();
break;
case '--rpc-url':
args.rpcUrl = next();
break;
case '--network':
args.network = next();
break;
case '--dry-run':
args.dryRun = true;
break;
case '--help':
case '-h':
printUsage();
process.exit(0);
break;
default:
throw new Error(`Unknown argument: ${arg}`);
}
}
if (!args.backup) {
throw new Error('Missing required argument: --backup <path>');
}
if (!args.rpcUrl) {
args.rpcUrl = DEFAULT_RPC_URLS[args.network];
if (!args.rpcUrl) {
throw new Error(`No default RPC URL for network "${args.network}"; pass --rpc-url`);
}
}
return args;
}
function printUsage() {
process.stdout.write(
[
'Usage: node scripts/rollback-contracts.cjs --backup <path> [options]',
'',
'Options:',
' --backup <path> Path to the previous contract-ids.env backup (required)',
' --target-env <path> Backend .env file to update (default: .env)',
' (alias: --env-file, which newer Node versions intercept)',
' --configmap <name> Kubernetes ConfigMap to update (optional)',
' --namespace <ns> Kubernetes namespace (default: synapsvault)',
' --rpc-url <url> Soroban RPC endpoint (default: $SOROBAN_RPC_URL, or the',
' public RPC for testnet/futurenet; required for mainnet)',
' --network <name> Stellar network name (testnet|mainnet|futurenet)',
' --dry-run Verify and report without writing changes',
' -h, --help Show this help',
'',
'Note: Soroban contracts are immutable. This script does not undeploy',
'anything; it reverts the backend contract-ID references only.',
'',
].join('\n')
);
}
// ---------------------------------------------------------------------------
// Contract ID validation & on-chain verification.
// ---------------------------------------------------------------------------
const CONTRACT_ID_RE = /^C[A-Z2-7]{55}$/;
const DEFAULT_RPC_URLS = {
testnet: 'https://soroban-testnet.stellar.org',
futurenet: 'https://rpc-futurenet.stellar.org',
};
function isValidContractId(id) {
return typeof id === 'string' && CONTRACT_ID_RE.test(id);
}
// Canonical env var prefix for deployed contract IDs (the names the backend
// reads), e.g. `vault_registry` -> `STELLAR_CONTRACT_VAULT_REGISTRY`.
const CONTRACT_ENV_PREFIX = 'STELLAR_CONTRACT_';
// Legacy keys whose canonical target is not a plain prefix/suffix rewrite:
// `REGISTRY_CONTRACT_ID` is the older name for the vault registry contract
// (see docs/ENVIRONMENT-VARIABLES.md).
const CONTRACT_KEY_ALIASES = {
REGISTRY_CONTRACT_ID: `${CONTRACT_ENV_PREFIX}VAULT_REGISTRY`,
REGISTRY_CONTRACT: `${CONTRACT_ENV_PREFIX}VAULT_REGISTRY`,
};
/**
* Map any recognised contract-ID key to its canonical `STELLAR_CONTRACT_*`
* name, so backups written by any deploy path can be rolled back.
*
* Returns null when `key` is not a contract-ID reference.
*/
function canonicalContractKey(key, value) {
if (typeof key !== 'string') return null;
if (key.startsWith(CONTRACT_ENV_PREFIX)) {
const stem = key.slice(CONTRACT_ENV_PREFIX.length);
return stem ? key : null;
}
if (Object.prototype.hasOwnProperty.call(CONTRACT_KEY_ALIASES, key)) {
return CONTRACT_KEY_ALIASES[key];
}
for (const suffix of ['_CONTRACT_ID', '_CONTRACT']) {
if (key.endsWith(suffix)) {
const stem = key.slice(0, -suffix.length);
return stem ? `${CONTRACT_ENV_PREFIX}${stem}` : null;
}
}
// Bare lower-case contract name as written by 03-deploy-contracts.sh
// (e.g. `vault_registry=C...`). Only treat it as a contract reference when
// the value is a well-formed contract ID, so ordinary settings are ignored.
if (/^[a-z][a-z0-9_]*$/.test(key) && isValidContractId(value)) {
return `${CONTRACT_ENV_PREFIX}${key.toUpperCase()}`;
}
return null;
}
/**
* Verify a contract exists on-chain by reading its instance ledger entry
* (persistent `LedgerKeyContractInstance`) from Soroban RPC.
*
* Resolves to true when the entry exists, false when the RPC reports it as
* missing, and throws on transport errors so the caller can tell "missing"
* apart from "could not check".
*/
async function contractExistsOnChain(contractId, rpcUrl) {
const { rpc, xdr } = require('@stellar/stellar-sdk');
const server = new rpc.Server(rpcUrl, { allowHttp: rpcUrl.startsWith('http://') });
try {
const entry = await server.getContractData(
contractId,
xdr.ScVal.scvLedgerKeyContractInstance(),
rpc.Durability.Persistent
);
return Boolean(entry && entry.val);
} catch (err) {
// The SDK rejects with a { code: 404 } object when the entry is absent.
if (err && (err.code === 404 || /not found/i.test(String(err.message || err)))) {
return false;
}
throw err instanceof Error ? err : new Error(JSON.stringify(err));
}
}
// ---------------------------------------------------------------------------
// Environment / ConfigMap updates.
// ---------------------------------------------------------------------------
function updateEnvFile(envFilePath, contractIds, dryRun) {
const existing = fs.existsSync(envFilePath)
? fs.readFileSync(envFilePath, 'utf8')
: '';
const lines = existing.split(/\r?\n/);
// Drop the empty element produced by a trailing newline so appended keys
// follow the last line directly; the newline is re-added on write.
if (lines.length > 0 && lines[lines.length - 1] === '') lines.pop();
const keys = Object.keys(contractIds);
const seen = new Set();
const updated = lines.map((line) => {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) return line;
const eq = trimmed.indexOf('=');
if (eq === -1) return line;
const key = trimmed.slice(0, eq).trim();
const value = trimmed.slice(eq + 1).trim();
const canonicalKey = canonicalContractKey(key, value);
if (
canonicalKey &&
Object.prototype.hasOwnProperty.call(contractIds, canonicalKey)
) {
// Update canonical keys in place. Legacy aliases (e.g.
// VAULT_REGISTRY_CONTRACT_ID) are kept in sync as well, while the
// canonical key is still appended below unless already present verbatim.
if (key === canonicalKey) seen.add(canonicalKey);
return `${key}=${contractIds[canonicalKey]}`;
}
return line;
});
// Append any keys that were not already present.
for (const key of keys) {
if (!seen.has(key)) {
updated.push(`${key}=${contractIds[key]}`);
}
}
const contents = updated.join('\n') + '\n';
if (dryRun) {
process.stdout.write(
`[dry-run] Would write ${envFilePath}:\n${contents}\n`
);
return;
}
fs.writeFileSync(envFilePath, contents, 'utf8');
process.stdout.write(`[ok] Updated env file: ${envFilePath}\n`);
}
function updateConfigMap(name, namespace, contractIds, dryRun) {
// Merge-patch only the contract ID keys so the rest of the ConfigMap
// (NODE_ENV, PORT, RPC URLs, ...) is left untouched.
const patch = JSON.stringify({ data: contractIds });
const args = ['patch', 'configmap', name, '--namespace', namespace, '--type', 'merge', '-p', patch];
if (dryRun) {
process.stdout.write(
`[dry-run] Would patch ConfigMap ${namespace}/${name} with:\n` +
Object.entries(contractIds)
.map(([k, v]) => ` ${k}=${v}`)
.join('\n') +
'\n'
);
return;
}
try {
execFileSync('kubectl', args, { encoding: 'utf8', stdio: ['ignore', 'inherit', 'inherit'] });
process.stdout.write(
`[ok] Updated ConfigMap: ${namespace}/${name}\n` +
' Pods only read envFrom at start-up; run `kubectl rollout restart deployment/backend`\n' +
' to pick up the new contract IDs.\n'
);
} catch (err) {
throw new Error(
`Failed to update ConfigMap ${namespace}/${name}: ${err.message}`
);
}
}
// ---------------------------------------------------------------------------
// Main.
// ---------------------------------------------------------------------------
async function main() {
let args;
try {
args = parseArgs(process.argv.slice(2));
} catch (err) {
process.stderr.write(`[error] ${err.message}\n\n`);
printUsage();
process.exit(1);
}
const backupPath = path.resolve(args.backup);
process.stdout.write(`[info] Reading backup: ${backupPath}\n`);
let previous;
try {
previous = readEnvFile(backupPath);
} catch (err) {
process.stderr.write(`[error] ${err.message}\n`);
process.exit(1);
}
// Only consider keys that reference a contract ID, normalising each to its
// canonical STELLAR_CONTRACT_* name so either deploy path can be rolled back.
const contractIds = {};
for (const [key, value] of Object.entries(previous)) {
const canonicalKey = canonicalContractKey(key, value);
if (!canonicalKey) continue;
if (!isValidContractId(value)) {
process.stderr.write(
`[error] Backup key ${key} has invalid contract ID: ${value}\n`
);
process.exit(1);
}
contractIds[canonicalKey] = value;
}
if (Object.keys(contractIds).length === 0) {
process.stderr.write(
'[error] No contract ID entries found in backup file.\n' +
' Expected STELLAR_CONTRACT_* keys, *_CONTRACT_ID keys or bare\n' +
' contract names (vault_registry, access_lease, subscription).\n'
);
process.exit(1);
}
process.stdout.write(
`[info] Found ${Object.keys(contractIds).length} contract ID(s) in backup.\n`
);
// Verify each old contract still exists on-chain.
let allVerified = true;
for (const [key, id] of Object.entries(contractIds)) {
process.stdout.write(`[info] Verifying ${key} = ${id} ... `);
let exists = false;
try {
exists = await contractExistsOnChain(id, args.rpcUrl);
} catch (err) {
process.stdout.write('\n');
process.stderr.write(
`[error] Verification failed for ${key} (${id}): ${err.message}\n`
);
allVerified = false;
continue;
}
process.stdout.write(exists ? 'OK\n' : 'MISSING\n');
if (!exists) allVerified = false;
}
if (!allVerified) {
process.stderr.write(
'\n[error] One or more previous contracts could not be verified on-chain.\n' +
' Refusing to roll back to unverified contract IDs.\n' +
' (Note: Soroban contracts are immutable and are never removed\n' +
' from the chain, so a MISSING result usually indicates a wrong\n' +
' network/RPC URL or a malformed contract ID.)\n'
);
process.exit(2);
}
process.stdout.write('[ok] All previous contracts verified on-chain.\n');
// Apply the rollback.
try {
updateEnvFile(args.envFile, contractIds, args.dryRun);
if (args.configmap) {
updateConfigMap(
args.configmap,
args.namespace,
contractIds,
args.dryRun
);
}
} catch (err) {
process.stderr.write(`[error] ${err.message}\n`);
process.exit(3);
}
process.stdout.write(
'\n[ok] Rollback complete. Backend now references the previous contract IDs.\n' +
' Reminder: the newer contracts remain deployed on-chain (Soroban\n' +
' contracts are immutable); they are simply no longer referenced.\n'
);
}
if (require.main === module) {
main().catch((err) => {
process.stderr.write(`[fatal] ${err && err.stack ? err.stack : err}\n`);
process.exit(1);
});
}
module.exports = {
parseEnvFile,
readEnvFile,
parseArgs,
isValidContractId,
canonicalContractKey,
contractExistsOnChain,
updateEnvFile,
updateConfigMap,
};