neo-decompiler 0.11.0

Neo N3 NEF decompiler: parse, disassemble, lift bytecode to high-level pseudocode and C# skeletons, with a CLI, JSON reports, and optional WebAssembly bindings.
Documentation
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
import { ManifestParseError } from "./errors.js";

const MAX_MANIFEST_SIZE = 0xffff;

export function parseManifest(json, options = {}) {
  let value;
  if (typeof json === "string") {
    const size = Buffer.byteLength(json, "utf8");
    if (size > MAX_MANIFEST_SIZE) {
      throw new ManifestParseError(
        `manifest size ${size} exceeds maximum (${MAX_MANIFEST_SIZE} bytes)`,
        { code: "FileTooLarge", size, max: MAX_MANIFEST_SIZE },
      );
    }
    try {
      value = JSON.parse(json);
    } catch (cause) {
      throw new ManifestParseError(
        `invalid manifest JSON: ${cause.message}`,
        { code: "InvalidJson" },
      );
    }
  } else {
    value = json;
  }
  if (value === null || typeof value !== "object" || Array.isArray(value)) {
    throw new ManifestParseError(
      "manifest must be a JSON object",
      { code: "InvalidStructure" },
    );
  }
  requireString(value.name, "name");

  if (
    value.abi === null ||
    value.abi === undefined ||
    typeof value.abi !== "object" ||
    Array.isArray(value.abi)
  ) {
    throw new ManifestParseError("abi is required and must be an object", {
      code: "MissingField",
      path: "abi",
    });
  }

  if (value.supportedstandards !== undefined && !Array.isArray(value.supportedstandards)) {
    throw new ManifestParseError("supportedstandards must be an array", {
      code: "InvalidType",
      path: "supportedstandards",
    });
  }
  // Rust deserializes this field as `Vec<String>`, so serde rejects any
  // non-string element. Mirror that — without this check a number/object
  // element would be carried verbatim into the parsed manifest, diverging
  // from the authoritative Rust parser's reject decision.
  if (
    Array.isArray(value.supportedstandards) &&
    !value.supportedstandards.every((entry) => typeof entry === "string")
  ) {
    throw new ManifestParseError("supportedstandards must be an array of strings", {
      code: "InvalidType",
      path: "supportedstandards",
    });
  }

  const features = parseFeatures(value.features);

  requireArrayIfPresent(value.groups, "groups");
  requireArrayIfPresent(value.abi.methods, "abi.methods");
  requireArrayIfPresent(value.abi.events, "abi.events");
  requireArrayIfPresent(value.permissions, "permissions");

  const manifest = {
    name: value.name,
    groups: Array.isArray(value.groups)
      ? value.groups.map((group, groupIndex) => parseGroup(group, groupIndex))
      : [],
    supportedStandards: Array.isArray(value.supportedstandards)
      ? value.supportedstandards
      : [],
    features,
    abi: {
      methods: Array.isArray(value.abi.methods)
        ? value.abi.methods.map((method, methodIndex) =>
            parseAbiMethod(method, methodIndex),
          )
        : [],
      events: Array.isArray(value.abi.events)
        ? value.abi.events.map((event, eventIndex) =>
            parseAbiEvent(event, eventIndex),
          )
        : [],
    },
    permissions: Array.isArray(value.permissions)
      ? value.permissions.map((perm, permIndex) => parsePermission(perm, permIndex))
      : [],
    trusts:
      value.trusts === undefined
        ? null
        : Array.isArray(value.trusts)
          ? value.trusts
          : value.trusts,
    extra: value.extra ?? null,
  };

  if (options.strict) {
    validateManifestStrict(manifest);
  }

  return manifest;
}

function requireString(value, path) {
  if (typeof value !== "string") {
    throw new ManifestParseError(`${path} is required`, {
      code: "MissingField",
      path,
    });
  }
}

function requireArrayIfPresent(value, path) {
  if (value !== undefined && value !== null && !Array.isArray(value)) {
    throw new ManifestParseError(`${path} must be an array`, {
      code: "InvalidType",
      path,
    });
  }
}

function parseAbiParameter(parameter, path) {
  requireString(parameter?.name, `${path}.name`);
  requireString(parameter?.type, `${path}.type`);
  return { name: parameter.name, kind: parameter.type };
}

function parseFeatures(features) {
  if (features === undefined) {
    return {};
  }
  if (features === null || typeof features !== "object" || Array.isArray(features)) {
    throw new ManifestParseError("features must be an object", {
      code: "InvalidType",
      path: "features",
    });
  }
  // Neo N3's `ContractManifest.FromJson` requires `features` to be an
  // empty object (the legacy 2.x storage/payable flags do not exist in
  // N3). Tolerant parsing keeps the raw object so malformed manifests
  // stay inspectable; strict parsing rejects non-empty content.
  return { ...features };
}

/**
 * Classify a permission `contract` descriptor by shape, mirroring the
 * official `ContractPermissionDescriptor.FromJson()` (and the Rust
 * port's `ManifestPermissionContract::classify`):
 *
 * - `"*"` — wildcard,
 * - 42 characters, `0x` prefix + 40 hex digits — contract hash,
 * - 66 hex characters — group public key,
 * - anything else (including the non-official `{hash}`/`{group}`
 *   object forms) — `other`, a malformed descriptor the official
 *   parser rejects.
 */
export function classifyPermissionContract(value) {
  if (typeof value === "string") {
    if (value === "*") {
      return { kind: "wildcard", value };
    }
    if (isHashDescriptor(value)) {
      return { kind: "hash", hash: value };
    }
    if (isGroupDescriptor(value)) {
      return { kind: "group", group: value };
    }
  }
  return { kind: "other", value };
}

const HEX_DIGITS = /^[0-9a-fA-F]+$/u;

function isHashDescriptor(text) {
  return (
    text.length === 42 &&
    (text.startsWith("0x") || text.startsWith("0X")) &&
    HEX_DIGITS.test(text.slice(2))
  );
}

function isGroupDescriptor(text) {
  return text.length === 66 && HEX_DIGITS.test(text);
}

function parsePermission(perm, permIndex) {
  const path = `permissions[${permIndex}]`;
  if (perm === null || typeof perm !== "object" || Array.isArray(perm)) {
    throw new ManifestParseError(`${path} must be an object`, {
      code: "InvalidType",
      path,
    });
  }
  if (perm.contract === undefined) {
    throw new ManifestParseError(`${path}.contract is required`, {
      code: "MissingField",
      path: `${path}.contract`,
    });
  }
  // Mirror the Rust untagged enum `ManifestPermissionMethods`
  // (`Wildcard(String) | Methods(Vec<String>)`): when present, `methods` must
  // be a string or an array of strings. `undefined` stays valid (serde default).
  if (perm.methods !== undefined) {
    const validMethods =
      typeof perm.methods === "string" ||
      (Array.isArray(perm.methods) &&
        perm.methods.every((method) => typeof method === "string"));
    if (!validMethods) {
      throw new ManifestParseError(
        `${path}.methods must be a wildcard string or an array of strings`,
        { code: "InvalidType", path: `${path}.methods` },
      );
    }
  }
  return perm;
}

function parseGroup(group, groupIndex) {
  const path = `groups[${groupIndex}]`;
  requireString(group?.pubkey, `${path}.pubkey`);
  requireString(group?.signature, `${path}.signature`);
  return { pubkey: group.pubkey, signature: group.signature };
}

function parseAbiMethod(method, methodIndex) {
  const path = `abi.methods[${methodIndex}]`;
  requireString(method?.name, `${path}.name`);
  requireString(method?.returntype, `${path}.returntype`);
  requireArrayIfPresent(method.parameters, `${path}.parameters`);
  if (method.offset !== undefined && method.offset !== null) {
    // Rust deserializes offset as Option<i32>: serde rejects non-integers and
    // out-of-range values. Mirror that here (JSON.parse cannot distinguish the
    // `3.0` float-syntax that Rust also rejects, but every other case matches)
    // so a crafted manifest is rejected consistently across both ports.
    if (
      typeof method.offset !== "number" ||
      !Number.isInteger(method.offset) ||
      method.offset < -2147483648 ||
      method.offset > 2147483647
    ) {
      throw new ManifestParseError(
        `${path}.offset must be an i32 integer`,
        { code: "InvalidType", path: `${path}.offset` },
      );
    }
  }
  if (method.safe !== undefined && typeof method.safe !== "boolean") {
    throw new ManifestParseError(`${path}.safe must be a boolean`, {
      code: "InvalidType",
      path: `${path}.safe`,
    });
  }
  return {
    name: method.name,
    parameters: Array.isArray(method.parameters)
      ? method.parameters.map((parameter, parameterIndex) =>
          parseAbiParameter(parameter, `${path}.parameters[${parameterIndex}]`),
        )
      : [],
    returnType: method.returntype,
    offset:
      typeof method.offset === "number" && method.offset >= 0
        ? method.offset
        : null,
    safe: method.safe === true,
  };
}

function parseAbiEvent(event, eventIndex) {
  const path = `abi.events[${eventIndex}]`;
  requireString(event?.name, `${path}.name`);
  requireArrayIfPresent(event.parameters, `${path}.parameters`);
  return {
    name: event.name,
    parameters: Array.isArray(event.parameters)
      ? event.parameters.map((parameter, parameterIndex) =>
          parseAbiParameter(parameter, `${path}.parameters[${parameterIndex}]`),
        )
      : [],
  };
}

function validateManifestStrict(manifest) {
  if (Object.keys(manifest.features).length > 0) {
    throw new ManifestParseError(
      `features must be an empty object in Neo N3, got keys: ${Object.keys(manifest.features).join(", ")}`,
      { code: "Validation", path: "features", value: manifest.features },
    );
  }

  for (let i = 0; i < manifest.permissions.length; i++) {
    const perm = manifest.permissions[i];
    if (perm && typeof perm === "object" && !Array.isArray(perm)) {
      if (classifyPermissionContract(perm.contract).kind === "other") {
        throw new ManifestParseError(
          `permissions[${i}].contract must be "*", a 0x-prefixed 20-byte contract hash, or a 33-byte group public key, got ${JSON.stringify(perm.contract)}`,
          { code: "Validation", path: `permissions[${i}].contract`, value: perm.contract },
        );
      }
      if (typeof perm.methods === "string" && perm.methods !== "*") {
        throw new ManifestParseError(
          `permissions[${i}].methods wildcard must be "*", got ${JSON.stringify(perm.methods)}`,
          { code: "Validation", path: `permissions[${i}].methods`, value: perm.methods },
        );
      }
    }
  }
  if (typeof manifest.trusts === "string" && manifest.trusts !== "*") {
    throw new ManifestParseError(
      `trusts wildcard must be "*", got ${JSON.stringify(manifest.trusts)}`,
      { code: "Validation", path: "trusts", value: manifest.trusts },
    );
  }
}

export function sanitizeIdentifier(input) {
  let ident = "";
  for (const character of input) {
    if (/[A-Za-z0-9]/u.test(character)) {
      ident += character;
    } else if (
      character === "_" ||
      (/\s|-/u.test(character) && !ident.endsWith("_"))
    ) {
      // Mirror Rust precedence: explicit `_` is always preserved
      // (so `__foo` stays `__foo`); whitespace and `-` collapse into
      // a single `_` separator only when the previous char isn't
      // already `_`. Earlier the parens were `(_ || whitespace) &&
      // !ends_with("_")`, which silently collapsed leading double
      // underscores and broke parity with Rust's `sanitize_identifier`.
      ident += "_";
    }
  }

  ident = ident.replace(/_+$/u, "");
  if (ident.length === 0) {
    ident = "param";
  }
  if (/^[0-9]/u.test(ident)) {
    ident = `_${ident}`;
  }
  return ident;
}

/**
 * Extract and sanitise the contract name from a manifest, falling back
 * to `NeoContract` when the manifest is absent or the name trims to
 * empty. Mirrors Rust's `decompiler::helpers::extract_contract_name`
 * so manifest-less and empty-name outputs are byte-identical across
 * ports. Returns the sanitised identifier or `"NeoContract"`.
 */
export function extractContractName(manifest) {
  const trimmed = manifest?.name?.trim();
  if (!trimmed) {
    return "NeoContract";
  }
  const sanitised = sanitizeIdentifier(trimmed);
  return sanitised !== "" ? sanitised : "NeoContract";
}

export function makeUniqueIdentifier(base, used) {
  if (!used.has(base)) {
    used.add(base);
    return base;
  }

  let index = 1;
  while (used.has(`${base}_${index}`)) {
    index += 1;
  }
  const candidate = `${base}_${index}`;
  used.add(candidate);
  return candidate;
}

export function sanitizeParameterNames(parameters) {
  const used = new Set();
  return parameters.map((parameter) =>
    makeUniqueIdentifier(sanitizeIdentifier(parameter.name), used),
  );
}

export function formatManifestType(kind) {
  const normalized = String(kind).toLowerCase();
  switch (normalized) {
    case "void":
      return "void";
    case "boolean":
      return "bool";
    case "integer":
      return "int";
    case "string":
      return "string";
    case "hash160":
      return "hash160";
    case "hash256":
      return "hash256";
    case "publickey":
      return "publickey";
    case "bytearray":
      return "bytes";
    case "signature":
      return "signature";
    case "array":
      return "array";
    case "map":
      return "map";
    case "interopinterface":
      return "interop";
    case "any":
      return "any";
    default:
      return String(kind);
  }
}

export function formatManifestParameters(parameters) {
  const names = sanitizeParameterNames(parameters);
  return parameters
    .map((parameter, index) => `${names[index]}: ${formatManifestType(parameter.kind)}`)
    .join(", ");
}