workerscript log takes a function now, hopefully this will increase performance.

This commit is contained in:
Olivier Gagnon
2021-11-26 18:30:58 -05:00
parent fe3aa5a357
commit c05518e162
14 changed files with 376 additions and 316 deletions

View File

@@ -213,7 +213,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
*/
const failOnHacknetServer = function (server: any, callingFn: any = ""): boolean {
if (server instanceof HacknetServer) {
workerScript.log(callingFn, `Does not work on Hacknet Servers`);
workerScript.log(callingFn, () => `Does not work on Hacknet Servers`);
return true;
} else {
return false;
@@ -282,7 +282,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
userstack.push(`${filename}:L${call.line}@${call.func}`);
}
workerScript.log(caller, msg);
workerScript.log(caller, () => msg);
let rejectMsg = `${caller}: ${msg}`;
if (userstack.length !== 0) rejectMsg += `<br><br>Stack:<br>${userstack.join("<br>")}`;
return makeRuntimeRejectMsg(workerScript, rejectMsg);
@@ -317,10 +317,11 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
workerScript.log(
"hack",
`Executing ${hostname} in ${convertTimeMsToTimeElapsedString(
hackingTime * 1000,
true,
)} (t=${numeralWrapper.formatThreads(threads)})`,
() =>
`Executing ${hostname} in ${convertTimeMsToTimeElapsedString(
hackingTime * 1000,
true,
)} (t=${numeralWrapper.formatThreads(threads)})`,
);
return netscriptDelay(hackingTime * 1000, workerScript).then(function () {
@@ -366,9 +367,10 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
workerScript.scriptRef.onlineExpGained += expGainedOnSuccess;
workerScript.log(
"hack",
`Successfully hacked '${server.hostname}' for ${numeralWrapper.formatMoney(
moneyGained,
)} and ${numeralWrapper.formatExp(expGainedOnSuccess)} exp (t=${numeralWrapper.formatThreads(threads)})`,
() =>
`Successfully hacked '${server.hostname}' for ${numeralWrapper.formatMoney(
moneyGained,
)} and ${numeralWrapper.formatExp(expGainedOnSuccess)} exp (t=${numeralWrapper.formatThreads(threads)})`,
);
server.fortify(CONSTANTS.ServerFortifyAmount * Math.min(threads, maxThreadNeeded));
if (stock) {
@@ -384,9 +386,10 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
workerScript.scriptRef.onlineExpGained += expGainedOnFailure;
workerScript.log(
"hack",
`Failed to hack '${server.hostname}'. Gained ${numeralWrapper.formatExp(
expGainedOnFailure,
)} exp (t=${numeralWrapper.formatThreads(threads)})`,
() =>
`Failed to hack '${server.hostname}'. Gained ${numeralWrapper.formatExp(
expGainedOnFailure,
)} exp (t=${numeralWrapper.formatThreads(threads)})`,
);
return Promise.resolve(0);
}
@@ -460,7 +463,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (entry === null) continue;
out.push(entry);
}
workerScript.log("scan", `returned ${server.serversOnNetwork.length} connections for ${server.hostname}`);
workerScript.log("scan", () => `returned ${server.serversOnNetwork.length} connections for ${server.hostname}`);
return out;
},
hack: function (hostname: any, { threads: requestedThreads, stock }: any = {}): any {
@@ -473,7 +476,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
// Check argument validity
const server = safeGetServer(hostname, "hackAnalyzeThreads");
if (!(server instanceof Server)) {
workerScript.log("hackAnalyzeThreads", "Cannot be executed on this server.");
workerScript.log("hackAnalyzeThreads", () => "Cannot be executed on this server.");
return -1;
}
if (isNaN(hackAmount)) {
@@ -496,7 +499,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
const server = safeGetServer(hostname, "hackAnalyze");
if (!(server instanceof Server)) {
workerScript.log("hackAnalyze", "Cannot be executed on this server.");
workerScript.log("hackAnalyze", () => "Cannot be executed on this server.");
return false;
}
@@ -510,7 +513,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
const server = safeGetServer(hostname, "hackAnalyzeChance");
if (!(server instanceof Server)) {
workerScript.log("hackAnalyzeChance", "Cannot be executed on this server.");
workerScript.log("hackAnalyzeChance", () => "Cannot be executed on this server.");
return false;
}
@@ -520,7 +523,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (time === undefined) {
throw makeRuntimeErrorMsg("sleep", "Takes 1 argument.");
}
workerScript.log("sleep", `Sleeping for ${time} milliseconds`);
workerScript.log("sleep", () => `Sleeping for ${time} milliseconds`);
return netscriptDelay(time, workerScript).then(function () {
return Promise.resolve(true);
});
@@ -529,7 +532,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (time === undefined) {
throw makeRuntimeErrorMsg("asleep", "Takes 1 argument.");
}
workerScript.log("asleep", `Sleeping for ${time} milliseconds`);
workerScript.log("asleep", () => `Sleeping for ${time} milliseconds`);
return netscriptDelay(time, workerScript).then(function () {
return Promise.resolve(true);
});
@@ -542,7 +545,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
const server = safeGetServer(hostname, "grow");
if (!(server instanceof Server)) {
workerScript.log("grow", "Cannot be executed on this server.");
workerScript.log("grow", () => "Cannot be executed on this server.");
return false;
}
@@ -560,10 +563,11 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
const growTime = calculateGrowTime(server, Player);
workerScript.log(
"grow",
`Executing on '${server.hostname}' in ${convertTimeMsToTimeElapsedString(
growTime * 1000,
true,
)} (t=${numeralWrapper.formatThreads(threads)}).`,
() =>
`Executing on '${server.hostname}' in ${convertTimeMsToTimeElapsedString(
growTime * 1000,
true,
)} (t=${numeralWrapper.formatThreads(threads)}).`,
);
return netscriptDelay(growTime * 1000, workerScript).then(function () {
if (workerScript.env.stopFlag) {
@@ -577,10 +581,11 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
const logGrowPercent = moneyAfter / moneyBefore - 1;
workerScript.log(
"grow",
`Available money on '${server.hostname}' grown by ${numeralWrapper.formatPercentage(
logGrowPercent,
6,
)}. Gained ${numeralWrapper.formatExp(expGain)} hacking exp (t=${numeralWrapper.formatThreads(threads)}).`,
() =>
`Available money on '${server.hostname}' grown by ${numeralWrapper.formatPercentage(
logGrowPercent,
6,
)}. Gained ${numeralWrapper.formatExp(expGain)} hacking exp (t=${numeralWrapper.formatThreads(threads)}).`,
);
workerScript.scriptRef.onlineExpGained += expGain;
Player.gainHackingExp(expGain);
@@ -596,7 +601,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
// Check argument validity
const server = safeGetServer(hostname, "growthAnalyze");
if (!(server instanceof Server)) {
workerScript.log("growthAnalyze", "Cannot be executed on this server.");
workerScript.log("growthAnalyze", () => "Cannot be executed on this server.");
return false;
}
if (typeof growth !== "number" || isNaN(growth) || growth < 1 || !isFinite(growth)) {
@@ -616,7 +621,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
const server = safeGetServer(hostname, "weaken");
if (!(server instanceof Server)) {
workerScript.log("weaken", "Cannot be executed on this server.");
workerScript.log("weaken", () => "Cannot be executed on this server.");
return false;
}
@@ -629,16 +634,17 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
const weakenTime = calculateWeakenTime(server, Player);
workerScript.log(
"weaken",
`Executing on '${server.hostname}' in ${convertTimeMsToTimeElapsedString(
weakenTime * 1000,
true,
)} (t=${numeralWrapper.formatThreads(threads)})`,
() =>
`Executing on '${server.hostname}' in ${convertTimeMsToTimeElapsedString(
weakenTime * 1000,
true,
)} (t=${numeralWrapper.formatThreads(threads)})`,
);
return netscriptDelay(weakenTime * 1000, workerScript).then(function () {
if (workerScript.env.stopFlag) return Promise.reject(workerScript);
const host = GetServer(workerScript.hostname);
if (host === null) {
workerScript.log("weaken", "Server is null, did it die?");
workerScript.log("weaken", () => "Server is null, did it die?");
return Promise.resolve(0);
}
const coreBonus = 1 + (host.cpuCores - 1) / 16;
@@ -647,9 +653,10 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
const expGain = calculateHackingExpGain(server, Player) * threads;
workerScript.log(
"weaken",
`'${server.hostname}' security level weakened to ${server.hackDifficulty}. Gained ${numeralWrapper.formatExp(
expGain,
)} hacking exp (t=${numeralWrapper.formatThreads(threads)})`,
() =>
`'${server.hostname}' security level weakened to ${
server.hackDifficulty
}. Gained ${numeralWrapper.formatExp(expGain)} hacking exp (t=${numeralWrapper.formatThreads(threads)})`,
);
workerScript.scriptRef.onlineExpGained += expGain;
Player.gainHackingExp(expGain);
@@ -721,12 +728,12 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
for (fn in possibleLogs) {
workerScript.disableLogs[fn] = true;
}
workerScript.log("disableLog", `Disabled logging for all functions`);
workerScript.log("disableLog", () => `Disabled logging for all functions`);
} else if (possibleLogs[fn] === undefined) {
throw makeRuntimeErrorMsg("disableLog", `Invalid argument: ${fn}.`);
} else {
workerScript.disableLogs[fn] = true;
workerScript.log("disableLog", `Disabled logging for ${fn}`);
workerScript.log("disableLog", () => `Disabled logging for ${fn}`);
}
},
enableLog: function (fn: any): any {
@@ -734,7 +741,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
throw makeRuntimeErrorMsg("enableLog", `Invalid argument: ${fn}.`);
}
delete workerScript.disableLogs[fn];
workerScript.log("enableLog", `Enabled logging for ${fn}`);
workerScript.log("enableLog", () => `Enabled logging for ${fn}`);
},
isLogEnabled: function (fn: any): any {
if (possibleLogs[fn] === undefined) {
@@ -745,7 +752,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
getScriptLogs: function (fn: any, hostname: any, ...scriptArgs: any): any {
const runningScriptObj = getRunningScript(fn, hostname, "getScriptLogs", scriptArgs);
if (runningScriptObj == null) {
workerScript.log("getScriptLogs", getCannotFindRunningScriptErrorMessage(fn, hostname, scriptArgs));
workerScript.log("getScriptLogs", () => getCannotFindRunningScriptErrorMessage(fn, hostname, scriptArgs));
return "";
}
@@ -761,7 +768,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
runningScriptObj = getRunningScript(fn, hostname, "tail", scriptArgs);
}
if (runningScriptObj == null) {
workerScript.log("tail", getCannotFindRunningScriptErrorMessage(fn, hostname, scriptArgs));
workerScript.log("tail", () => getCannotFindRunningScriptErrorMessage(fn, hostname, scriptArgs));
return;
}
@@ -774,7 +781,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
const server = safeGetServer(hostname, "nuke");
if (!(server instanceof Server)) {
workerScript.log("nuke", "Cannot be executed on this server.");
workerScript.log("nuke", () => "Cannot be executed on this server.");
return false;
}
if (!Player.hasProgram(Programs.NukeProgram.name)) {
@@ -784,10 +791,10 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
throw makeRuntimeErrorMsg("nuke", "Not enough ports opened to use NUKE.exe virus.");
}
if (server.hasAdminRights) {
workerScript.log("nuke", `Already have root access to '${server.hostname}'.`);
workerScript.log("nuke", () => `Already have root access to '${server.hostname}'.`);
} else {
server.hasAdminRights = true;
workerScript.log("nuke", `Executed NUKE.exe virus on '${server.hostname}' to gain root access.`);
workerScript.log("nuke", () => `Executed NUKE.exe virus on '${server.hostname}' to gain root access.`);
}
return true;
},
@@ -798,18 +805,18 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
const server = safeGetServer(hostname, "brutessh");
if (!(server instanceof Server)) {
workerScript.log("brutessh", "Cannot be executed on this server.");
workerScript.log("brutessh", () => "Cannot be executed on this server.");
return false;
}
if (!Player.hasProgram(Programs.BruteSSHProgram.name)) {
throw makeRuntimeErrorMsg("brutessh", "You do not have the BruteSSH.exe program!");
}
if (!server.sshPortOpen) {
workerScript.log("brutessh", `Executed BruteSSH.exe on '${server.hostname}' to open SSH port (22).`);
workerScript.log("brutessh", () => `Executed BruteSSH.exe on '${server.hostname}' to open SSH port (22).`);
server.sshPortOpen = true;
++server.openPortCount;
} else {
workerScript.log("brutessh", `SSH Port (22) already opened on '${server.hostname}'.`);
workerScript.log("brutessh", () => `SSH Port (22) already opened on '${server.hostname}'.`);
}
return true;
},
@@ -820,18 +827,18 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
const server = safeGetServer(hostname, "ftpcrack");
if (!(server instanceof Server)) {
workerScript.log("ftpcrack", "Cannot be executed on this server.");
workerScript.log("ftpcrack", () => "Cannot be executed on this server.");
return false;
}
if (!Player.hasProgram(Programs.FTPCrackProgram.name)) {
throw makeRuntimeErrorMsg("ftpcrack", "You do not have the FTPCrack.exe program!");
}
if (!server.ftpPortOpen) {
workerScript.log("ftpcrack", `Executed FTPCrack.exe on '${server.hostname}' to open FTP port (21).`);
workerScript.log("ftpcrack", () => `Executed FTPCrack.exe on '${server.hostname}' to open FTP port (21).`);
server.ftpPortOpen = true;
++server.openPortCount;
} else {
workerScript.log("ftpcrack", `FTP Port (21) already opened on '${server.hostname}'.`);
workerScript.log("ftpcrack", () => `FTP Port (21) already opened on '${server.hostname}'.`);
}
return true;
},
@@ -842,18 +849,18 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
const server = safeGetServer(hostname, "relaysmtp");
if (!(server instanceof Server)) {
workerScript.log("relaysmtp", "Cannot be executed on this server.");
workerScript.log("relaysmtp", () => "Cannot be executed on this server.");
return false;
}
if (!Player.hasProgram(Programs.RelaySMTPProgram.name)) {
throw makeRuntimeErrorMsg("relaysmtp", "You do not have the relaySMTP.exe program!");
}
if (!server.smtpPortOpen) {
workerScript.log("relaysmtp", `Executed relaySMTP.exe on '${server.hostname}' to open SMTP port (25).`);
workerScript.log("relaysmtp", () => `Executed relaySMTP.exe on '${server.hostname}' to open SMTP port (25).`);
server.smtpPortOpen = true;
++server.openPortCount;
} else {
workerScript.log("relaysmtp", `SMTP Port (25) already opened on '${server.hostname}'.`);
workerScript.log("relaysmtp", () => `SMTP Port (25) already opened on '${server.hostname}'.`);
}
return true;
},
@@ -864,18 +871,18 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
const server = safeGetServer(hostname, "httpworm");
if (!(server instanceof Server)) {
workerScript.log("httpworm", "Cannot be executed on this server.");
workerScript.log("httpworm", () => "Cannot be executed on this server.");
return false;
}
if (!Player.hasProgram(Programs.HTTPWormProgram.name)) {
throw makeRuntimeErrorMsg("httpworm", "You do not have the HTTPWorm.exe program!");
}
if (!server.httpPortOpen) {
workerScript.log("httpworm", `Executed HTTPWorm.exe on '${server.hostname}' to open HTTP port (80).`);
workerScript.log("httpworm", () => `Executed HTTPWorm.exe on '${server.hostname}' to open HTTP port (80).`);
server.httpPortOpen = true;
++server.openPortCount;
} else {
workerScript.log("httpworm", `HTTP Port (80) already opened on '${server.hostname}'.`);
workerScript.log("httpworm", () => `HTTP Port (80) already opened on '${server.hostname}'.`);
}
return true;
},
@@ -886,18 +893,18 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
const server = safeGetServer(hostname, "sqlinject");
if (!(server instanceof Server)) {
workerScript.log("sqlinject", "Cannot be executed on this server.");
workerScript.log("sqlinject", () => "Cannot be executed on this server.");
return false;
}
if (!Player.hasProgram(Programs.SQLInjectProgram.name)) {
throw makeRuntimeErrorMsg("sqlinject", "You do not have the SQLInject.exe program!");
}
if (!server.sqlPortOpen) {
workerScript.log("sqlinject", `Executed SQLInject.exe on '${server.hostname}' to open SQL port (1433).`);
workerScript.log("sqlinject", () => `Executed SQLInject.exe on '${server.hostname}' to open SQL port (1433).`);
server.sqlPortOpen = true;
++server.openPortCount;
} else {
workerScript.log("sqlinject", `SQL Port (1433) already opened on '${server.hostname}'.`);
workerScript.log("sqlinject", () => `SQL Port (1433) already opened on '${server.hostname}'.`);
}
return true;
},
@@ -946,11 +953,11 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
return runScriptFromScript("spawn", scriptServer, scriptname, args, workerScript, threads);
}, spawnDelay * 1e3);
workerScript.log("spawn", `Will execute '${scriptname}' in ${spawnDelay} seconds`);
workerScript.log("spawn", () => `Will execute '${scriptname}' in ${spawnDelay} seconds`);
workerScript.running = false; // Prevent workerScript from "finishing execution naturally"
if (killWorkerScript(workerScript)) {
workerScript.log("spawn", "Exiting...");
workerScript.log("spawn", () => "Exiting...");
}
},
kill: function (filename: any, hostname: any, ...scriptArgs: any): any {
@@ -970,7 +977,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
const server = safeGetServer(hostname, "kill");
const runningScriptObj = getRunningScript(filename, hostname, "kill", scriptArgs);
if (runningScriptObj == null) {
workerScript.log("kill", getCannotFindRunningScriptErrorMessage(filename, hostname, scriptArgs));
workerScript.log("kill", () => getCannotFindRunningScriptErrorMessage(filename, hostname, scriptArgs));
return false;
}
@@ -979,18 +986,21 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (res) {
if (killByPid) {
workerScript.log("kill", `Killing script with PID ${filename}`);
workerScript.log("kill", () => `Killing script with PID ${filename}`);
} else {
workerScript.log("kill", `Killing '${filename}' on '${hostname}' with args: ${arrayToString(scriptArgs)}.`);
workerScript.log(
"kill",
() => `Killing '${filename}' on '${hostname}' with args: ${arrayToString(scriptArgs)}.`,
);
}
return true;
} else {
if (killByPid) {
workerScript.log("kill", `No script with PID ${filename}`);
workerScript.log("kill", () => `No script with PID ${filename}`);
} else {
workerScript.log(
"kill",
`No such script '${filename}' on '${hostname}' with args: ${arrayToString(scriptArgs)}`,
() => `No such script '${filename}' on '${hostname}' with args: ${arrayToString(scriptArgs)}`,
);
}
return false;
@@ -1009,7 +1019,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
WorkerScriptStartStopEventEmitter.emit();
workerScript.log(
"killall",
`Killing all scripts on '${server.hostname}'. May take a few minutes for the scripts to die.`,
() => `Killing all scripts on '${server.hostname}'. May take a few minutes for the scripts to die.`,
);
return scriptsRunning;
@@ -1017,9 +1027,9 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
exit: function (): any {
workerScript.running = false; // Prevent workerScript from "finishing execution naturally"
if (killWorkerScript(workerScript)) {
workerScript.log("exit", "Exiting...");
workerScript.log("exit", () => "Exiting...");
} else {
workerScript.log("exit", "Failed. This is a bug. Report to dev.");
workerScript.log("exit", () => "Failed. This is a bug. Report to dev.");
}
},
scp: async function (scriptname: any, hostname1: any, hostname2: any): Promise<boolean> {
@@ -1086,18 +1096,18 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
if (!found) {
workerScript.log("scp", `File '${scriptname}' does not exist.`);
workerScript.log("scp", () => `File '${scriptname}' does not exist.`);
return Promise.resolve(false);
}
for (let i = 0; i < destServer.messages.length; ++i) {
if (destServer.messages[i] === scriptname) {
workerScript.log("scp", `File '${scriptname}' copied over to '${destServer.hostname}'.`);
workerScript.log("scp", () => `File '${scriptname}' copied over to '${destServer?.hostname}'.`);
return Promise.resolve(true); // Already exists
}
}
destServer.messages.push(scriptname);
workerScript.log("scp", `File '${scriptname}' copied over to '${destServer.hostname}'.`);
workerScript.log("scp", () => `File '${scriptname}' copied over to '${destServer?.hostname}'.`);
return Promise.resolve(true);
}
@@ -1111,7 +1121,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
}
if (txtFile === undefined) {
workerScript.log("scp", `File '${scriptname}' does not exist.`);
workerScript.log("scp", () => `File '${scriptname}' does not exist.`);
return Promise.resolve(false);
}
@@ -1119,13 +1129,13 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (destServer.textFiles[i].fn === scriptname) {
// Overwrite
destServer.textFiles[i].text = txtFile.text;
workerScript.log("scp", `File '${scriptname}' copied over to '${destServer.hostname}'.`);
workerScript.log("scp", () => `File '${scriptname}' copied over to '${destServer?.hostname}'.`);
return Promise.resolve(true);
}
}
const newFile = new TextFile(txtFile.fn, txtFile.text);
destServer.textFiles.push(newFile);
workerScript.log("scp", `File '${scriptname}' copied over to '${destServer.hostname}'.`);
workerScript.log("scp", () => `File '${scriptname}' copied over to '${destServer?.hostname}'.`);
return Promise.resolve(true);
}
@@ -1138,14 +1148,14 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
}
if (sourceScript == null) {
workerScript.log("scp", `File '${scriptname}' does not exist.`);
workerScript.log("scp", () => `File '${scriptname}' does not exist.`);
return Promise.resolve(false);
}
// Overwrite script if it already exists
for (let i = 0; i < destServer.scripts.length; ++i) {
if (scriptname == destServer.scripts[i].filename) {
workerScript.log("scp", `WARNING: File '${scriptname}' overwritten on '${destServer.hostname}'`);
workerScript.log("scp", () => `WARNING: File '${scriptname}' overwritten on '${destServer?.hostname}'`);
const oldScript = destServer.scripts[i];
// If it's the exact same file don't actually perform the
// copy to avoid recompiling uselessly. Players tend to scp
@@ -1164,7 +1174,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
newScript.ramUsage = sourceScript.ramUsage;
newScript.server = destServer.hostname;
destServer.scripts.push(newScript);
workerScript.log("scp", `File '${scriptname}' copied over to '${destServer.hostname}'.`);
workerScript.log("scp", () => `File '${scriptname}' copied over to '${destServer?.hostname}'.`);
return new Promise((resolve) => {
if (destServer === null) {
resolve(false);
@@ -1274,7 +1284,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
getHackingLevel: function (): any {
updateDynamicRam("getHackingLevel", getRamCost("getHackingLevel"));
Player.updateSkillLevels();
workerScript.log("getHackingLevel", `returned ${Player.hacking}`);
workerScript.log("getHackingLevel", () => `returned ${Player.hacking}`);
return Player.hacking;
},
getHackingMultipliers: function (): any {
@@ -1322,7 +1332,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
updateDynamicRam("getServerMoneyAvailable", getRamCost("getServerMoneyAvailable"));
const server = safeGetServer(hostname, "getServerMoneyAvailable");
if (!(server instanceof Server)) {
workerScript.log("getServerMoneyAvailable", "Cannot be executed on this server.");
workerScript.log("getServerMoneyAvailable", () => "Cannot be executed on this server.");
return 0;
}
if (failOnHacknetServer(server, "getServerMoneyAvailable")) {
@@ -1332,13 +1342,13 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
// Return player's money
workerScript.log(
"getServerMoneyAvailable",
`returned player's money: ${numeralWrapper.formatMoney(Player.money)}`,
() => `returned player's money: ${numeralWrapper.formatMoney(Player.money)}`,
);
return Player.money;
}
workerScript.log(
"getServerMoneyAvailable",
`returned ${numeralWrapper.formatMoney(server.moneyAvailable)} for '${server.hostname}'`,
() => `returned ${numeralWrapper.formatMoney(server.moneyAvailable)} for '${server.hostname}'`,
);
return server.moneyAvailable;
},
@@ -1346,7 +1356,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
updateDynamicRam("getServerSecurityLevel", getRamCost("getServerSecurityLevel"));
const server = safeGetServer(hostname, "getServerSecurityLevel");
if (!(server instanceof Server)) {
workerScript.log("getServerSecurityLevel", "Cannot be executed on this server.");
workerScript.log("getServerSecurityLevel", () => "Cannot be executed on this server.");
return 1;
}
if (failOnHacknetServer(server, "getServerSecurityLevel")) {
@@ -1354,7 +1364,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
workerScript.log(
"getServerSecurityLevel",
`returned ${numeralWrapper.formatServerSecurity(server.hackDifficulty)} for '${server.hostname}'`,
() => `returned ${numeralWrapper.formatServerSecurity(server.hackDifficulty)} for '${server.hostname}'`,
);
return server.hackDifficulty;
},
@@ -1362,11 +1372,11 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
updateDynamicRam("getServerBaseSecurityLevel", getRamCost("getServerBaseSecurityLevel"));
workerScript.log(
"getServerBaseSecurityLevel",
`getServerBaseSecurityLevel is deprecated because it's not useful.`,
() => `getServerBaseSecurityLevel is deprecated because it's not useful.`,
);
const server = safeGetServer(hostname, "getServerBaseSecurityLevel");
if (!(server instanceof Server)) {
workerScript.log("getServerBaseSecurityLevel", "Cannot be executed on this server.");
workerScript.log("getServerBaseSecurityLevel", () => "Cannot be executed on this server.");
return 1;
}
if (failOnHacknetServer(server, "getServerBaseSecurityLevel")) {
@@ -1374,7 +1384,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
workerScript.log(
"getServerBaseSecurityLevel",
`returned ${numeralWrapper.formatServerSecurity(server.baseDifficulty)} for '${server.hostname}'`,
() => `returned ${numeralWrapper.formatServerSecurity(server.baseDifficulty)} for '${server.hostname}'`,
);
return server.baseDifficulty;
},
@@ -1382,7 +1392,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
updateDynamicRam("getServerMinSecurityLevel", getRamCost("getServerMinSecurityLevel"));
const server = safeGetServer(hostname, "getServerMinSecurityLevel");
if (!(server instanceof Server)) {
workerScript.log("getServerMinSecurityLevel", "Cannot be executed on this server.");
workerScript.log("getServerMinSecurityLevel", () => "Cannot be executed on this server.");
return 1;
}
if (failOnHacknetServer(server, "getServerMinSecurityLevel")) {
@@ -1390,7 +1400,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
workerScript.log(
"getServerMinSecurityLevel",
`returned ${numeralWrapper.formatServerSecurity(server.minDifficulty)} for ${server.hostname}`,
() => `returned ${numeralWrapper.formatServerSecurity(server.minDifficulty)} for ${server.hostname}`,
);
return server.minDifficulty;
},
@@ -1398,7 +1408,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
updateDynamicRam("getServerRequiredHackingLevel", getRamCost("getServerRequiredHackingLevel"));
const server = safeGetServer(hostname, "getServerRequiredHackingLevel");
if (!(server instanceof Server)) {
workerScript.log("getServerRequiredHackingLevel", "Cannot be executed on this server.");
workerScript.log("getServerRequiredHackingLevel", () => "Cannot be executed on this server.");
return 1;
}
if (failOnHacknetServer(server, "getServerRequiredHackingLevel")) {
@@ -1406,7 +1416,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
workerScript.log(
"getServerRequiredHackingLevel",
`returned ${numeralWrapper.formatSkill(server.requiredHackingSkill)} for '${server.hostname}'`,
() => `returned ${numeralWrapper.formatSkill(server.requiredHackingSkill)} for '${server.hostname}'`,
);
return server.requiredHackingSkill;
},
@@ -1414,7 +1424,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
updateDynamicRam("getServerMaxMoney", getRamCost("getServerMaxMoney"));
const server = safeGetServer(hostname, "getServerMaxMoney");
if (!(server instanceof Server)) {
workerScript.log("getServerMaxMoney", "Cannot be executed on this server.");
workerScript.log("getServerMaxMoney", () => "Cannot be executed on this server.");
return 0;
}
if (failOnHacknetServer(server, "getServerMaxMoney")) {
@@ -1422,7 +1432,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
}
workerScript.log(
"getServerMaxMoney",
`returned ${numeralWrapper.formatMoney(server.moneyMax)} for '${server.hostname}'`,
() => `returned ${numeralWrapper.formatMoney(server.moneyMax)} for '${server.hostname}'`,
);
return server.moneyMax;
},
@@ -1430,48 +1440,54 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
updateDynamicRam("getServerGrowth", getRamCost("getServerGrowth"));
const server = safeGetServer(hostname, "getServerGrowth");
if (!(server instanceof Server)) {
workerScript.log("getServerGrowth", "Cannot be executed on this server.");
workerScript.log("getServerGrowth", () => "Cannot be executed on this server.");
return 1;
}
if (failOnHacknetServer(server, "getServerGrowth")) {
return 1;
}
workerScript.log("getServerGrowth", `returned ${server.serverGrowth} for '${server.hostname}'`);
workerScript.log("getServerGrowth", () => `returned ${server.serverGrowth} for '${server.hostname}'`);
return server.serverGrowth;
},
getServerNumPortsRequired: function (hostname: any): any {
updateDynamicRam("getServerNumPortsRequired", getRamCost("getServerNumPortsRequired"));
const server = safeGetServer(hostname, "getServerNumPortsRequired");
if (!(server instanceof Server)) {
workerScript.log("getServerNumPortsRequired", "Cannot be executed on this server.");
workerScript.log("getServerNumPortsRequired", () => "Cannot be executed on this server.");
return 5;
}
if (failOnHacknetServer(server, "getServerNumPortsRequired")) {
return 5;
}
workerScript.log("getServerNumPortsRequired", `returned ${server.numOpenPortsRequired} for '${server.hostname}'`);
workerScript.log(
"getServerNumPortsRequired",
() => `returned ${server.numOpenPortsRequired} for '${server.hostname}'`,
);
return server.numOpenPortsRequired;
},
getServerRam: function (hostname: any): any {
updateDynamicRam("getServerRam", getRamCost("getServerRam"));
workerScript.log("getServerRam", `getServerRam is deprecated in favor of getServerMaxRam / getServerUsedRam`);
workerScript.log(
"getServerRam",
() => `getServerRam is deprecated in favor of getServerMaxRam / getServerUsedRam`,
);
const server = safeGetServer(hostname, "getServerRam");
workerScript.log(
"getServerRam",
`returned [${numeralWrapper.formatRAM(server.maxRam)}, ${numeralWrapper.formatRAM(server.ramUsed)}]`,
() => `returned [${numeralWrapper.formatRAM(server.maxRam)}, ${numeralWrapper.formatRAM(server.ramUsed)}]`,
);
return [server.maxRam, server.ramUsed];
},
getServerMaxRam: function (hostname: any): any {
updateDynamicRam("getServerMaxRam", getRamCost("getServerMaxRam"));
const server = safeGetServer(hostname, "getServerMaxRam");
workerScript.log("getServerMaxRam", `returned ${numeralWrapper.formatRAM(server.maxRam)}`);
workerScript.log("getServerMaxRam", () => `returned ${numeralWrapper.formatRAM(server.maxRam)}`);
return server.maxRam;
},
getServerUsedRam: function (hostname: any): any {
updateDynamicRam("getServerUsedRam", getRamCost("getServerUsedRam"));
const server = safeGetServer(hostname, "getServerUsedRam");
workerScript.log("getServerUsedRam", `returned ${numeralWrapper.formatRAM(server.ramUsed)}`);
workerScript.log("getServerUsedRam", () => `returned ${numeralWrapper.formatRAM(server.ramUsed)}`);
return server.ramUsed;
},
serverExists: function (hostname: any): any {
@@ -1531,7 +1547,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
const cost = getPurchaseServerCost(ram);
if (cost === Infinity) {
workerScript.log("getPurchasedServerCost", `Invalid argument: ram='${ram}'`);
workerScript.log("getPurchasedServerCost", () => `Invalid argument: ram='${ram}'`);
return Infinity;
}
@@ -1542,28 +1558,29 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
let hostnameStr = String(name);
hostnameStr = hostnameStr.replace(/\s+/g, "");
if (hostnameStr == "") {
workerScript.log("purchaseServer", `Invalid argument: hostname='${hostnameStr}'`);
workerScript.log("purchaseServer", () => `Invalid argument: hostname='${hostnameStr}'`);
return "";
}
if (Player.purchasedServers.length >= getPurchaseServerLimit()) {
workerScript.log(
"purchaseServer",
`You have reached the maximum limit of ${getPurchaseServerLimit()} servers. You cannot purchase any more.`,
() =>
`You have reached the maximum limit of ${getPurchaseServerLimit()} servers. You cannot purchase any more.`,
);
return "";
}
const cost = getPurchaseServerCost(ram);
if (cost === Infinity) {
workerScript.log("purchaseServer", `Invalid argument: ram='${ram}'`);
workerScript.log("purchaseServer", () => `Invalid argument: ram='${ram}'`);
return "";
}
if (Player.money < cost) {
workerScript.log(
"purchaseServer",
`Not enough money to purchase server. Need ${numeralWrapper.formatMoney(cost)}`,
() => `Not enough money to purchase server. Need ${numeralWrapper.formatMoney(cost)}`,
);
return "";
}
@@ -1585,7 +1602,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
Player.loseMoney(cost, "servers");
workerScript.log(
"purchaseServer",
`Purchased new server with hostname '${newServ.hostname}' for ${numeralWrapper.formatMoney(cost)}`,
() => `Purchased new server with hostname '${newServ.hostname}' for ${numeralWrapper.formatMoney(cost)}`,
);
return newServ.hostname;
},
@@ -1595,12 +1612,12 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
hostnameStr = hostnameStr.replace(/\s\s+/g, "");
const server = GetServer(hostnameStr);
if (!(server instanceof Server)) {
workerScript.log("deleteServer", `Invalid argument: hostname='${hostnameStr}'`);
workerScript.log("deleteServer", () => `Invalid argument: hostname='${hostnameStr}'`);
return false;
}
if (!server.purchasedByPlayer || server.hostname === "home") {
workerScript.log("deleteServer", "Cannot delete non-purchased server.");
workerScript.log("deleteServer", () => "Cannot delete non-purchased server.");
return false;
}
@@ -1608,19 +1625,22 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
// Can't delete server you're currently connected to
if (server.isConnectedTo) {
workerScript.log("deleteServer", "You are currently connected to the server you are trying to delete.");
workerScript.log("deleteServer", () => "You are currently connected to the server you are trying to delete.");
return false;
}
// A server cannot delete itself
if (hostname === workerScript.hostname) {
workerScript.log("deleteServer", "Cannot delete the server this script is running on.");
workerScript.log("deleteServer", () => "Cannot delete the server this script is running on.");
return false;
}
// Delete all scripts running on server
if (server.runningScripts.length > 0) {
workerScript.log("deleteServer", `Cannot delete server '${hostname}' because it still has scripts running.`);
workerScript.log(
"deleteServer",
() => `Cannot delete server '${hostname}' because it still has scripts running.`,
);
return false;
}
@@ -1637,7 +1657,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (!found) {
workerScript.log(
"deleteServer",
`Could not identify server ${hostname} as a purchased server. This is a bug. Report to dev.`,
() => `Could not identify server ${hostname} as a purchased server. This is a bug. Report to dev.`,
);
return false;
}
@@ -1651,14 +1671,14 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
for (let i = 0; i < homeComputer.serversOnNetwork.length; ++i) {
if (hostname == homeComputer.serversOnNetwork[i]) {
homeComputer.serversOnNetwork.splice(i, 1);
workerScript.log("deleteServer", `Deleted server '${hostnameStr}`);
workerScript.log("deleteServer", () => `Deleted server '${hostnameStr}`);
return true;
}
}
// Wasn't found on home computer
workerScript.log(
"deleteServer",
`Could not find server ${hostname} as a purchased server. This is a bug. Report to dev.`,
() => `Could not find server ${hostname} as a purchased server. This is a bug. Report to dev.`,
);
return false;
},
@@ -1896,7 +1916,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
const status = s.removeFile(fn);
if (!status.res) {
workerScript.log("rm", status.msg + "");
workerScript.log("rm", () => status.msg + "");
}
return status.res;
@@ -1973,7 +1993,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
updateDynamicRam("getHackTime", getRamCost("getHackTime"));
const server = safeGetServer(hostname, "getHackTime");
if (!(server instanceof Server)) {
workerScript.log("getHackTime", "invalid for this kind of server");
workerScript.log("getHackTime", () => "invalid for this kind of server");
return Infinity;
}
if (failOnHacknetServer(server, "getHackTime")) {
@@ -1986,7 +2006,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
updateDynamicRam("getGrowTime", getRamCost("getGrowTime"));
const server = safeGetServer(hostname, "getGrowTime");
if (!(server instanceof Server)) {
workerScript.log("getGrowTime", "invalid for this kind of server");
workerScript.log("getGrowTime", () => "invalid for this kind of server");
return Infinity;
}
if (failOnHacknetServer(server, "getGrowTime")) {
@@ -1999,7 +2019,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
updateDynamicRam("getWeakenTime", getRamCost("getWeakenTime"));
const server = safeGetServer(hostname, "getWeakenTime");
if (!(server instanceof Server)) {
workerScript.log("getWeakenTime", "invalid for this kind of server");
workerScript.log("getWeakenTime", () => "invalid for this kind of server");
return Infinity;
}
if (failOnHacknetServer(server, "getWeakenTime")) {
@@ -2030,7 +2050,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (runningScriptObj == null) {
workerScript.log(
"getScriptIncome",
`No such script '${scriptname}' on '${server.hostname}' with args: ${arrayToString(args)}`,
() => `No such script '${scriptname}' on '${server.hostname}' with args: ${arrayToString(args)}`,
);
return -1;
}
@@ -2052,7 +2072,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
if (runningScriptObj == null) {
workerScript.log(
"getScriptExpGain",
`No such script '${scriptname}' on '${server.hostname}' with args: ${arrayToString(args)}`,
() => `No such script '${scriptname}' on '${server.hostname}' with args: ${arrayToString(args)}`,
);
return -1;
}
@@ -2095,7 +2115,7 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
},
wget: async function (url: any, target: any, hostname: any = workerScript.hostname): Promise<boolean> {
if (!isScriptFilename(target) && !target.endsWith(".txt")) {
workerScript.log("wget", `Invalid target file: '${target}'. Must be a script or text file.`);
workerScript.log("wget", () => `Invalid target file: '${target}'. Must be a script or text file.`);
return Promise.resolve(false);
}
const s = safeGetServer(hostname, "wget");
@@ -2110,19 +2130,22 @@ export function NetscriptFunctions(workerScript: WorkerScript): NS {
res = s.writeToTextFile(target, data);
}
if (!res.success) {
workerScript.log("wget", "Failed.");
workerScript.log("wget", () => "Failed.");
return resolve(false);
}
if (res.overwritten) {
workerScript.log("wget", `Successfully retrieved content and overwrote '${target}' on '${hostname}'`);
workerScript.log(
"wget",
() => `Successfully retrieved content and overwrote '${target}' on '${hostname}'`,
);
return resolve(true);
}
workerScript.log("wget", `Successfully retrieved content to new file '${target}' on '${hostname}'`);
workerScript.log("wget", () => `Successfully retrieved content to new file '${target}' on '${hostname}'`);
return resolve(true);
},
"text",
).fail(function (e) {
workerScript.log("wget", JSON.stringify(e));
workerScript.log("wget", () => JSON.stringify(e));
return resolve(false);
});
});