/
NetscriptFunctions.ts
2552 lines (2388 loc) · 96.9 KB
/
NetscriptFunctions.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import $ from "jquery";
import { vsprintf, sprintf } from "sprintf-js";
import { WorkerScriptStartStopEventEmitter } from "./Netscript/WorkerScriptStartStopEventEmitter";
import { BitNodeMultipliers } from "./BitNode/BitNodeMultipliers";
import { CONSTANTS } from "./Constants";
import {
calculateHackingChance,
calculateHackingExpGain,
calculatePercentMoneyHacked,
calculateHackingTime,
calculateGrowTime,
calculateWeakenTime,
} from "./Hacking";
import { netscriptCanGrow, netscriptCanHack, netscriptCanWeaken } from "./Hacking/netscriptCanHack";
import { HacknetServer } from "./Hacknet/HacknetServer";
import { Terminal } from "./Terminal";
import { Player } from "./Player";
import { Programs } from "./Programs/Programs";
import { Script } from "./Script/Script";
import { findRunningScript, findRunningScriptByPid } from "./Script/ScriptHelpers";
import { isScriptFilename } from "./Script/isScriptFilename";
import { PromptEvent } from "./ui/React/PromptManager";
import { GetServer, GetAllServers, DeleteServer, AddToAllServers, createUniqueRandomIp } from "./Server/AllServers";
import { RunningScript } from "./Script/RunningScript";
import {
getServerOnNetwork,
numCycleForGrowth,
numCycleForGrowthCorrected,
processSingleServerGrowth,
safetlyCreateUniqueServer,
} from "./Server/ServerHelpers";
import { getPurchaseServerCost, getPurchaseServerLimit, getPurchaseServerMaxRam } from "./Server/ServerPurchases";
import { Server } from "./Server/Server";
import { influenceStockThroughServerHack, influenceStockThroughServerGrow } from "./StockMarket/PlayerInfluencing";
import { isValidFilePath, removeLeadingSlash } from "./Terminal/DirectoryHelpers";
import { TextFile, getTextFile, createTextFile } from "./TextFile";
import { NetscriptPorts, runScriptFromScript } from "./NetscriptWorker";
import { killWorkerScript } from "./Netscript/killWorkerScript";
import { workerScripts } from "./Netscript/WorkerScripts";
import { WorkerScript } from "./Netscript/WorkerScript";
import { makeRuntimeRejectMsg, netscriptDelay, resolveNetscriptRequestedThreads } from "./NetscriptEvaluator";
import { numeralWrapper } from "./ui/numeralFormat";
import { convertTimeMsToTimeElapsedString } from "./utils/StringHelperFunctions";
import { LogBoxEvents, LogBoxCloserEvents } from "./ui/React/LogBoxManager";
import { arrayToString } from "./utils/helpers/arrayToString";
import { isString } from "./utils/helpers/isString";
import { BaseServer } from "./Server/BaseServer";
import { NetscriptGang } from "./NetscriptFunctions/Gang";
import { NetscriptSleeve } from "./NetscriptFunctions/Sleeve";
import { NetscriptExtra } from "./NetscriptFunctions/Extra";
import { NetscriptHacknet } from "./NetscriptFunctions/Hacknet";
import { NetscriptStanek } from "./NetscriptFunctions/Stanek";
import { NetscriptInfiltration } from "./NetscriptFunctions/Infiltration";
import { NetscriptUserInterface } from "./NetscriptFunctions/UserInterface";
import { NetscriptBladeburner } from "./NetscriptFunctions/Bladeburner";
import { NetscriptCodingContract } from "./NetscriptFunctions/CodingContract";
import { NetscriptCorporation } from "./NetscriptFunctions/Corporation";
import { NetscriptFormulas } from "./NetscriptFunctions/Formulas";
import { NetscriptStockMarket } from "./NetscriptFunctions/StockMarket";
import { NetscriptGrafting } from "./NetscriptFunctions/Grafting";
import { IPort } from "./NetscriptPort";
import {
NS as INS,
Player as INetscriptPlayer,
Gang as IGang,
Bladeburner as IBladeburner,
Stanek as IStanek,
Infiltration as IInfiltration,
RunningScript as IRunningScript,
RecentScript as IRecentScript,
SourceFileLvl,
BasicHGWOptions,
ProcessInfo,
HackingMultipliers,
HacknetMultipliers,
BitNodeMultipliers as IBNMults,
Server as IServerDef,
RunningScript as IRunningScriptDef,
// ToastVariant,
} from "./ScriptEditor/NetscriptDefinitions";
import { NetscriptSingularity } from "./NetscriptFunctions/Singularity";
import { toNative } from "./NetscriptFunctions/toNative";
import { dialogBoxCreate } from "./ui/React/DialogBox";
import { SnackbarEvents, ToastVariant } from "./ui/React/Snackbar";
import { checkEnum } from "./utils/helpers/checkEnum";
import { Flags } from "./NetscriptFunctions/Flags";
import { calculateIntelligenceBonus } from "./PersonObjects/formulas/intelligence";
import { CalculateShareMult, StartSharing } from "./NetworkShare/Share";
import { recentScripts } from "./Netscript/RecentScripts";
import { CityName } from "./Locations/data/CityNames";
import { InternalAPI, NetscriptContext, wrapAPI } from "./Netscript/APIWrapper";
import { INetscriptHelper } from "./NetscriptFunctions/INetscriptHelper";
interface NS extends INS {
[key: string]: any;
gang: IGang;
bladeburner: IBladeburner;
stanek: IStanek;
infiltration: IInfiltration;
}
export function NetscriptFunctions(workerScript: WorkerScript): NS {
const updateDynamicRam = function (fnName: string, ramCost: number): void {
if (workerScript.dynamicLoadedFns[fnName]) {
return;
}
workerScript.dynamicLoadedFns[fnName] = true;
let threads = workerScript.scriptRef.threads;
if (typeof threads !== "number") {
console.warn(`WorkerScript detected NaN for threadcount for ${workerScript.name} on ${workerScript.hostname}`);
threads = 1;
}
workerScript.dynamicRamUsage += ramCost;
if (workerScript.dynamicRamUsage > 1.01 * workerScript.ramUsage) {
throw makeRuntimeRejectMsg(
workerScript,
`Dynamic RAM usage calculated to be greater than initial RAM usage on fn: ${fnName}.
This is probably because you somehow circumvented the static RAM calculation.
Threads: ${threads}
Dynamic RAM Usage: ${numeralWrapper.formatRAM(workerScript.dynamicRamUsage)}
Static RAM Usage: ${numeralWrapper.formatRAM(workerScript.ramUsage)}
One of these could be the reason:
* Using eval() to get a reference to a ns function
const myScan = eval('ns.scan');
* Using map access to do the same
const myScan = ns['scan'];
Sorry :(`,
);
}
};
/**
* Gets the Server for a specific hostname/ip, throwing an error
* if the server doesn't exist.
* @param {string} hostname - Hostname or IP of the server
* @param {string} callingFnName - Name of calling function. For logging purposes
* @returns {BaseServer} The specified server as a BaseServer
*/
const safeGetServer = function (hostname: string, ctx: NetscriptContext): BaseServer {
const server = GetServer(hostname);
if (server == null) {
throw ctx.makeRuntimeErrorMsg(`Invalid hostname: ${hostname}`);
}
return server;
};
/**
* Searches for and returns the RunningScript object for the specified script.
* If the 'fn' argument is not specified, this returns the current RunningScript.
* @param {string} fn - Filename of script
* @param {string} hostname - Hostname/ip of the server on which the script resides
* @param {any[]} scriptArgs - Running script's arguments
* @returns {RunningScript}
* Running script identified by the parameters, or null if no such script
* exists, or the current running script if the first argument 'fn'
* is not specified.
*/
const getRunningScript = function (
ctx: NetscriptContext,
fn: string,
hostname: string,
scriptArgs: any,
): RunningScript | null {
if (!Array.isArray(scriptArgs)) {
throw makeRuntimeRejectMsg(
workerScript,
`Invalid scriptArgs argument passed into getRunningScript() from ${ctx.function}(). ` +
`This is probably a bug. Please report to game developer`,
);
}
if (fn != null && typeof fn === "string") {
// Get Logs of another script
if (hostname == null) {
hostname = workerScript.hostname;
}
const server = safeGetServer(hostname, ctx);
return findRunningScript(fn, scriptArgs, server);
}
// If no arguments are specified, return the current RunningScript
return workerScript.scriptRef;
};
const getRunningScriptByPid = function (pid: number): RunningScript | null {
for (const server of GetAllServers()) {
const runningScript = findRunningScriptByPid(pid, server);
if (runningScript) return runningScript;
}
return null;
};
/**
* Sanitizes a `RunningScript` to remove sensitive information, making it suitable for
* return through an NS function.
* @see NS.getRecentScripts
* @see NS.getRunningScript
* @param runningScript Existing, internal RunningScript
* @returns A sanitized, NS-facing copy of the RunningScript
*/
const createPublicRunningScript = function (runningScript: RunningScript): IRunningScript {
return {
args: runningScript.args.slice(),
filename: runningScript.filename,
logs: runningScript.logs.slice(),
offlineExpGained: runningScript.offlineExpGained,
offlineMoneyMade: runningScript.offlineMoneyMade,
offlineRunningTime: runningScript.offlineRunningTime,
onlineExpGained: runningScript.onlineExpGained,
onlineMoneyMade: runningScript.onlineMoneyMade,
onlineRunningTime: runningScript.onlineRunningTime,
pid: runningScript.pid,
ramUsage: runningScript.ramUsage,
server: runningScript.server,
threads: runningScript.threads,
};
};
/**
* Helper function for getting the error log message when the user specifies
* a nonexistent running script
* @param {string} fn - Filename of script
* @param {string} hostname - Hostname/ip of the server on which the script resides
* @param {any[]} scriptArgs - Running script's arguments
* @returns {string} Error message to print to logs
*/
const getCannotFindRunningScriptErrorMessage = function (fn: string, hostname: string, scriptArgs: any): string {
if (!Array.isArray(scriptArgs)) {
scriptArgs = [];
}
return `Cannot find running script ${fn} on server ${hostname} with args: ${arrayToString(scriptArgs)}`;
};
/**
* Used to fail a function if the function's target is a Hacknet Server.
* This is used for functions that should run on normal Servers, but not Hacknet Servers
* @param {Server} server - Target server
* @param {string} callingFn - Name of calling function. For logging purposes
* @returns {boolean} True if the server is a Hacknet Server, false otherwise
*/
const failOnHacknetServer = function (server: BaseServer, callingFn = ""): boolean {
if (server instanceof HacknetServer) {
workerScript.log(callingFn, () => `Does not work on Hacknet Servers`);
return true;
} else {
return false;
}
};
const makeRuntimeErrorMsg = function (caller: string, msg: string): string {
const errstack = new Error().stack;
if (errstack === undefined) throw new Error("how did we not throw an error?");
const stack = errstack.split("\n").slice(1);
const scripts = workerScript.getServer().scripts;
const userstack = [];
for (const stackline of stack) {
let filename;
for (const script of scripts) {
if (script.url && stackline.includes(script.url)) {
filename = script.filename;
}
for (const dependency of script.dependencies) {
if (stackline.includes(dependency.url)) {
filename = dependency.filename;
}
}
}
if (!filename) continue;
interface ILine {
line: string;
func: string;
}
function parseChromeStackline(line: string): ILine | null {
const lineRe = /.*:(\d+):\d+.*/;
const funcRe = /.*at (.+) \(.*/;
const lineMatch = line.match(lineRe);
const funcMatch = line.match(funcRe);
if (lineMatch && funcMatch) {
return { line: lineMatch[1], func: funcMatch[1] };
}
return null;
}
let call = { line: "-1", func: "unknown" };
const chromeCall = parseChromeStackline(stackline);
if (chromeCall) {
call = chromeCall;
}
function parseFirefoxStackline(line: string): ILine | null {
const lineRe = /.*:(\d+):\d+$/;
const lineMatch = line.match(lineRe);
const lio = line.lastIndexOf("@");
if (lineMatch && lio !== -1) {
return { line: lineMatch[1], func: line.slice(0, lio) };
}
return null;
}
const firefoxCall = parseFirefoxStackline(stackline);
if (firefoxCall) {
call = firefoxCall;
}
userstack.push(`${filename}:L${call.line}@${call.func}`);
}
workerScript.log(caller, () => msg);
let rejectMsg = `${caller}: ${msg}`;
if (userstack.length !== 0) rejectMsg += `<br><br>Stack:<br>${userstack.join("<br>")}`;
return makeRuntimeRejectMsg(workerScript, rejectMsg);
};
const checkSingularityAccess = function (func: string): void {
if (Player.bitNodeN !== 4) {
if (Player.sourceFileLvl(4) === 0) {
throw makeRuntimeErrorMsg(
func,
`This singularity function requires Source-File 4 to run. A power up you obtain later in the game. It will be very obvious when and how you can obtain it.`,
);
}
}
};
const hack = async function (
ctx: NetscriptContext,
hostname: string,
manual: boolean,
{ threads: requestedThreads, stock }: any = {},
): Promise<number> {
if (hostname === undefined) {
throw ctx.makeRuntimeErrorMsg("Takes 1 argument.");
}
const threads = resolveNetscriptRequestedThreads(ctx, requestedThreads);
const server = safeGetServer(hostname, ctx);
if (!(server instanceof Server)) {
throw ctx.makeRuntimeErrorMsg("Cannot be executed on this server.");
}
// Calculate the hacking time
const hackingTime = calculateHackingTime(server, Player); // This is in seconds
// No root access or skill level too low
const canHack = netscriptCanHack(server, Player);
if (!canHack.res) {
throw ctx.makeRuntimeErrorMsg(canHack.msg || "");
}
ctx.log(
() =>
`Executing on '${server.hostname}' in ${convertTimeMsToTimeElapsedString(
hackingTime * 1000,
true,
)} (t=${numeralWrapper.formatThreads(threads)})`,
);
return netscriptDelay(hackingTime * 1000, workerScript).then(function () {
const hackChance = calculateHackingChance(server, Player);
const rand = Math.random();
let expGainedOnSuccess = calculateHackingExpGain(server, Player) * threads;
const expGainedOnFailure = expGainedOnSuccess / 4;
if (rand < hackChance) {
// Success!
const percentHacked = calculatePercentMoneyHacked(server, Player);
let maxThreadNeeded = Math.ceil(1 / percentHacked);
if (isNaN(maxThreadNeeded)) {
// Server has a 'max money' of 0 (probably). We'll set this to an arbitrarily large value
maxThreadNeeded = 1e6;
}
let moneyDrained = Math.floor(server.moneyAvailable * percentHacked) * threads;
// Over-the-top safety checks
if (moneyDrained <= 0) {
moneyDrained = 0;
expGainedOnSuccess = expGainedOnFailure;
}
if (moneyDrained > server.moneyAvailable) {
moneyDrained = server.moneyAvailable;
}
server.moneyAvailable -= moneyDrained;
if (server.moneyAvailable < 0) {
server.moneyAvailable = 0;
}
let moneyGained = moneyDrained * BitNodeMultipliers.ScriptHackMoneyGain;
if (manual) {
moneyGained = moneyDrained * BitNodeMultipliers.ManualHackMoney;
}
Player.gainMoney(moneyGained, "hacking");
workerScript.scriptRef.onlineMoneyMade += moneyGained;
Player.scriptProdSinceLastAug += moneyGained;
workerScript.scriptRef.recordHack(server.hostname, moneyGained, threads);
Player.gainHackingExp(expGainedOnSuccess);
if (manual) Player.gainIntelligenceExp(0.005);
workerScript.scriptRef.onlineExpGained += expGainedOnSuccess;
ctx.log(
() =>
`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) {
influenceStockThroughServerHack(server, moneyDrained);
}
if (manual) {
server.backdoorInstalled = true;
}
return Promise.resolve(moneyGained);
} else {
// Player only gains 25% exp for failure?
Player.gainHackingExp(expGainedOnFailure);
workerScript.scriptRef.onlineExpGained += expGainedOnFailure;
ctx.log(
() =>
`Failed to hack '${server.hostname}'. Gained ${numeralWrapper.formatExp(
expGainedOnFailure,
)} exp (t=${numeralWrapper.formatThreads(threads)})`,
);
return Promise.resolve(0);
}
});
};
const argsToString = function (args: any[]): string {
let out = "";
for (let arg of args) {
arg = toNative(arg);
out += typeof arg === "object" ? JSON.stringify(arg) : `${arg}`;
}
return out;
};
const helper: INetscriptHelper = {
updateDynamicRam: updateDynamicRam,
makeRuntimeErrorMsg: makeRuntimeErrorMsg,
string: (funcName: string, argName: string, v: unknown): string => {
if (typeof v === "string") return v;
if (typeof v === "number") return v + ""; // cast to string;
throw makeRuntimeErrorMsg(funcName, `${argName} should be a string.`);
},
number: (funcName: string, argName: string, v: unknown): number => {
if (typeof v === "string") {
const x = parseFloat(v);
if (!isNaN(x)) return x; // otherwise it wasn't even a string representing a number.
} else if (typeof v === "number") {
if (isNaN(v)) throw makeRuntimeErrorMsg(funcName, `${argName} is NaN.`);
return v;
}
throw makeRuntimeErrorMsg(funcName, `${argName} should be a number.`);
},
boolean: (v: unknown): boolean => {
return !!v; // Just convert it to boolean.
},
city: (funcName: string, argName: string, v: unknown): CityName => {
if (typeof v !== "string") throw makeRuntimeErrorMsg(funcName, `${argName} should be a city name.`);
const s = v as CityName;
if (!Object.values(CityName).includes(s))
throw makeRuntimeErrorMsg(funcName, `${argName} should be a city name.`);
return s;
},
getServer: safeGetServer,
checkSingularityAccess: checkSingularityAccess,
hack: hack,
getValidPort: (funcName: string, port: number): IPort => {
if (isNaN(port)) {
throw makeRuntimeErrorMsg(
funcName,
`Invalid argument. Must be a port number between 1 and ${CONSTANTS.NumNetscriptPorts}, is ${port}`,
);
}
port = Math.round(port);
if (port < 1 || port > CONSTANTS.NumNetscriptPorts) {
throw makeRuntimeErrorMsg(
funcName,
`Trying to use an invalid port: ${port}. Only ports 1-${CONSTANTS.NumNetscriptPorts} are valid.`,
);
}
const iport = NetscriptPorts[port - 1];
if (iport == null || !(iport instanceof Object)) {
throw makeRuntimeErrorMsg(funcName, `Could not find port: ${port}. This is a bug. Report to dev.`);
}
return iport;
},
};
const singularity = NetscriptSingularity(Player, workerScript);
const base: InternalAPI<INS> = {
...singularity,
args: workerScript.args as unknown as any,
enums: {
toast: ToastVariant,
} as unknown as any,
singularity: singularity,
gang: NetscriptGang(Player, workerScript),
bladeburner: NetscriptBladeburner(Player, workerScript),
codingcontract: NetscriptCodingContract(Player, workerScript),
sleeve: NetscriptSleeve(Player),
corporation: NetscriptCorporation(Player, workerScript),
stanek: NetscriptStanek(Player, workerScript, helper),
infiltration: NetscriptInfiltration(Player),
ui: NetscriptUserInterface(),
formulas: NetscriptFormulas(Player, helper),
stock: NetscriptStockMarket(Player, workerScript),
grafting: NetscriptGrafting(Player),
hacknet: NetscriptHacknet(Player, workerScript),
sprintf: () => sprintf,
vsprintf: () => vsprintf,
scan:
(ctx: NetscriptContext) =>
(_hostname: unknown = workerScript.hostname): string[] => {
const hostname = ctx.helper.string("hostname", _hostname);
const server = safeGetServer(hostname, ctx);
const out = [];
for (let i = 0; i < server.serversOnNetwork.length; i++) {
const s = getServerOnNetwork(server, i);
if (s === null) continue;
const entry = s.hostname;
if (entry === null) continue;
out.push(entry);
}
ctx.log(() => `returned ${server.serversOnNetwork.length} connections for ${server.hostname}`);
return out;
},
hack:
(ctx: NetscriptContext) =>
(_hostname: unknown, { threads: requestedThreads, stock }: BasicHGWOptions = {}): Promise<number> => {
const hostname = ctx.helper.string("hostname", _hostname);
return hack(ctx, hostname, false, { threads: requestedThreads, stock: stock });
},
hackAnalyzeThreads:
(ctx: NetscriptContext) =>
(_hostname: unknown, _hackAmount: unknown): number => {
const hostname = ctx.helper.string("hostname", _hostname);
const hackAmount = ctx.helper.number("hackAmount", _hackAmount);
// Check argument validity
const server = safeGetServer(hostname, ctx);
if (!(server instanceof Server)) {
ctx.log(() => "Cannot be executed on this server.");
return -1;
}
if (isNaN(hackAmount)) {
throw ctx.makeRuntimeErrorMsg(
`Invalid hackAmount argument passed into hackAnalyzeThreads: ${hackAmount}. Must be numeric.`,
);
}
if (hackAmount < 0 || hackAmount > server.moneyAvailable) {
return -1;
} else if (hackAmount === 0) {
return 0;
}
const percentHacked = calculatePercentMoneyHacked(server, Player);
if (percentHacked === 0 || server.moneyAvailable === 0) {
return 0; // To prevent returning infinity below
}
return hackAmount / Math.floor(server.moneyAvailable * percentHacked);
},
hackAnalyze:
(ctx: NetscriptContext) =>
(_hostname: unknown): number => {
const hostname = ctx.helper.string("hostname", _hostname);
const server = safeGetServer(hostname, ctx);
if (!(server instanceof Server)) {
ctx.log(() => "Cannot be executed on this server.");
return 0;
}
return calculatePercentMoneyHacked(server, Player);
},
hackAnalyzeSecurity:
(ctx: NetscriptContext) =>
(_threads: unknown, _hostname?: unknown): number => {
let threads = ctx.helper.number("threads", _threads);
if (_hostname) {
const hostname = ctx.helper.string("hostname", _hostname);
const server = safeGetServer(hostname, ctx);
if (!(server instanceof Server)) {
ctx.log(() => "Cannot be executed on this server.");
return 0;
}
const percentHacked = calculatePercentMoneyHacked(server, Player);
if (percentHacked > 0) {
// thread count is limited to the maximum number of threads needed
threads = Math.min(threads, Math.ceil(1 / percentHacked));
}
}
return CONSTANTS.ServerFortifyAmount * threads;
},
hackAnalyzeChance:
(ctx: NetscriptContext) =>
(_hostname: unknown): number => {
const hostname = ctx.helper.string("hostname", _hostname);
const server = safeGetServer(hostname, ctx);
if (!(server instanceof Server)) {
ctx.log(() => "Cannot be executed on this server.");
return 0;
}
return calculateHackingChance(server, Player);
},
sleep:
(ctx: NetscriptContext) =>
async (_time: unknown = 0): Promise<true> => {
const time = ctx.helper.number("time", _time);
if (time === undefined) {
throw ctx.makeRuntimeErrorMsg("Takes 1 argument.");
}
ctx.log(() => `Sleeping for ${time} milliseconds`);
return netscriptDelay(time, workerScript).then(function () {
return Promise.resolve(true);
});
},
asleep: (ctx: NetscriptContext) =>
function (_time: unknown = 0): Promise<true> {
const time = ctx.helper.number("time", _time);
ctx.log(() => `Sleeping for ${time} milliseconds`);
return new Promise((resolve) => setTimeout(() => resolve(true), time));
},
grow:
(ctx: NetscriptContext) =>
async (_hostname: unknown, { threads: requestedThreads, stock }: BasicHGWOptions = {}): Promise<number> => {
const hostname = ctx.helper.string("hostname", _hostname);
const threads = resolveNetscriptRequestedThreads(ctx, requestedThreads ?? workerScript.scriptRef.threads);
const server = safeGetServer(hostname, ctx);
if (!(server instanceof Server)) {
ctx.log(() => "Cannot be executed on this server.");
return Promise.resolve(0);
}
const host = GetServer(workerScript.hostname);
if (host === null) {
throw new Error("Workerscript host is null");
}
// No root access or skill level too low
const canHack = netscriptCanGrow(server);
if (!canHack.res) {
throw ctx.makeRuntimeErrorMsg(canHack.msg || "");
}
const growTime = calculateGrowTime(server, Player);
ctx.log(
() =>
`Executing on '${server.hostname}' in ${convertTimeMsToTimeElapsedString(
growTime * 1000,
true,
)} (t=${numeralWrapper.formatThreads(threads)}).`,
);
return netscriptDelay(growTime * 1000, workerScript).then(function () {
const moneyBefore = server.moneyAvailable <= 0 ? 1 : server.moneyAvailable;
processSingleServerGrowth(server, threads, Player, host.cpuCores);
const moneyAfter = server.moneyAvailable;
workerScript.scriptRef.recordGrow(server.hostname, threads);
const expGain = calculateHackingExpGain(server, Player) * threads;
const logGrowPercent = moneyAfter / moneyBefore - 1;
ctx.log(
() =>
`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);
if (stock) {
influenceStockThroughServerGrow(server, moneyAfter - moneyBefore);
}
return Promise.resolve(moneyAfter / moneyBefore);
});
},
growthAnalyze:
(ctx: NetscriptContext) =>
(_hostname: unknown, _growth: unknown, _cores: unknown = 1): number => {
const hostname = ctx.helper.string("hostname", _hostname);
const growth = ctx.helper.number("growth", _growth);
const cores = ctx.helper.number("cores", _cores);
// Check argument validity
const server = safeGetServer(hostname, ctx);
if (!(server instanceof Server)) {
ctx.log(() => "Cannot be executed on this server.");
return 0;
}
if (typeof growth !== "number" || isNaN(growth) || growth < 1 || !isFinite(growth)) {
throw ctx.makeRuntimeErrorMsg(`Invalid argument: growth must be numeric and >= 1, is ${growth}.`);
}
return numCycleForGrowth(server, Number(growth), Player, cores);
},
growthAnalyzeSecurity:
(ctx: NetscriptContext) =>
(_threads: unknown, _hostname?: unknown, _cores?: unknown): number => {
let threads = ctx.helper.number("threads", _threads);
if (_hostname) {
const cores = ctx.helper.number("cores", _cores) || 1;
const hostname = ctx.helper.string("hostname", _hostname);
const server = safeGetServer(hostname, ctx);
if (!(server instanceof Server)) {
ctx.log(() => "Cannot be executed on this server.");
return 0;
}
const maxThreadsNeeded = Math.ceil(
numCycleForGrowthCorrected(server, server.moneyMax, server.moneyAvailable, Player, cores),
);
threads = Math.min(threads, maxThreadsNeeded);
}
return 2 * CONSTANTS.ServerFortifyAmount * threads;
},
weaken:
(ctx: NetscriptContext) =>
async (_hostname: unknown, { threads: requestedThreads }: BasicHGWOptions = {}): Promise<number> => {
const hostname = ctx.helper.string("hostname", _hostname);
const threads = resolveNetscriptRequestedThreads(ctx, requestedThreads ?? workerScript.scriptRef.threads);
if (hostname === undefined) {
throw ctx.makeRuntimeErrorMsg("Takes 1 argument.");
}
const server = safeGetServer(hostname, ctx);
if (!(server instanceof Server)) {
ctx.log(() => "Cannot be executed on this server.");
return Promise.resolve(0);
}
// No root access or skill level too low
const canHack = netscriptCanWeaken(server);
if (!canHack.res) {
throw ctx.makeRuntimeErrorMsg(canHack.msg || "");
}
const weakenTime = calculateWeakenTime(server, Player);
ctx.log(
() =>
`Executing on '${server.hostname}' in ${convertTimeMsToTimeElapsedString(
weakenTime * 1000,
true,
)} (t=${numeralWrapper.formatThreads(threads)})`,
);
return netscriptDelay(weakenTime * 1000, workerScript).then(function () {
const host = GetServer(workerScript.hostname);
if (host === null) {
ctx.log(() => "Server is null, did it die?");
return Promise.resolve(0);
}
const coreBonus = 1 + (host.cpuCores - 1) / 16;
server.weaken(CONSTANTS.ServerWeakenAmount * threads * coreBonus);
workerScript.scriptRef.recordWeaken(server.hostname, threads);
const expGain = calculateHackingExpGain(server, Player) * threads;
ctx.log(
() =>
`'${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);
return Promise.resolve(CONSTANTS.ServerWeakenAmount * threads * coreBonus);
});
},
weakenAnalyze:
(ctx: NetscriptContext) =>
(_threads: unknown, _cores: unknown = 1): number => {
const threads = ctx.helper.number("threads", _threads);
const cores = ctx.helper.number("cores", _cores);
const coreBonus = 1 + (cores - 1) / 16;
return CONSTANTS.ServerWeakenAmount * threads * coreBonus * BitNodeMultipliers.ServerWeakenRate;
},
share: (ctx: NetscriptContext) => async (): Promise<void> => {
ctx.log(() => "Sharing this computer.");
const end = StartSharing(workerScript.scriptRef.threads * calculateIntelligenceBonus(Player.intelligence, 2));
return netscriptDelay(10000, workerScript).finally(function () {
ctx.log(() => "Finished sharing this computer.");
end();
});
},
getSharePower: () => (): number => {
return CalculateShareMult();
},
print:
(ctx: NetscriptContext) =>
(...args: any[]): void => {
if (args.length === 0) {
throw ctx.makeRuntimeErrorMsg("Takes at least 1 argument.");
}
workerScript.print(argsToString(args));
},
printf:
(ctx: NetscriptContext) =>
(_format: unknown, ...args: any[]): void => {
const format = ctx.helper.string("format", _format);
if (typeof format !== "string") {
throw ctx.makeRuntimeErrorMsg("First argument must be string for the format.");
}
workerScript.print(vsprintf(format, args));
},
tprint:
(ctx: NetscriptContext) =>
(...args: any[]): void => {
if (args.length === 0) {
throw ctx.makeRuntimeErrorMsg("Takes at least 1 argument.");
}
const str = argsToString(args);
if (str.startsWith("ERROR") || str.startsWith("FAIL")) {
Terminal.error(`${workerScript.scriptRef.filename}: ${str}`);
return;
}
if (str.startsWith("SUCCESS")) {
Terminal.success(`${workerScript.scriptRef.filename}: ${str}`);
return;
}
if (str.startsWith("WARN")) {
Terminal.warn(`${workerScript.scriptRef.filename}: ${str}`);
return;
}
if (str.startsWith("INFO")) {
Terminal.info(`${workerScript.scriptRef.filename}: ${str}`);
return;
}
Terminal.print(`${workerScript.scriptRef.filename}: ${str}`);
},
tprintf:
(ctx: NetscriptContext) =>
(_format: unknown, ...args: any[]): void => {
const format = ctx.helper.string("format", _format);
const str = vsprintf(format, args);
if (str.startsWith("ERROR") || str.startsWith("FAIL")) {
Terminal.error(`${str}`);
return;
}
if (str.startsWith("SUCCESS")) {
Terminal.success(`${str}`);
return;
}
if (str.startsWith("WARN")) {
Terminal.warn(`${str}`);
return;
}
if (str.startsWith("INFO")) {
Terminal.info(`${str}`);
return;
}
Terminal.print(`${str}`);
},
clearLog: () => (): void => {
workerScript.scriptRef.clearLog();
},
disableLog:
(ctx: NetscriptContext) =>
(_fn: unknown): void => {
const fn = ctx.helper.string("fn", _fn);
if (fn === "ALL") {
for (const fn of Object.keys(possibleLogs)) {
workerScript.disableLogs[fn] = true;
}
ctx.log(() => `Disabled logging for all functions`);
} else if (possibleLogs[fn] === undefined) {
throw ctx.makeRuntimeErrorMsg(`Invalid argument: ${fn}.`);
} else {
workerScript.disableLogs[fn] = true;
ctx.log(() => `Disabled logging for ${fn}`);
}
},
enableLog:
(ctx: NetscriptContext) =>
(_fn: unknown): void => {
const fn = ctx.helper.string("fn", _fn);
if (fn === "ALL") {
for (const fn of Object.keys(possibleLogs)) {
delete workerScript.disableLogs[fn];
}
ctx.log(() => `Enabled logging for all functions`);
} else if (possibleLogs[fn] === undefined) {
throw ctx.makeRuntimeErrorMsg(`Invalid argument: ${fn}.`);
}
delete workerScript.disableLogs[fn];
ctx.log(() => `Enabled logging for ${fn}`);
},
isLogEnabled:
(ctx: NetscriptContext) =>
(_fn: unknown): boolean => {
const fn = ctx.helper.string("fn", _fn);
if (possibleLogs[fn] === undefined) {
throw ctx.makeRuntimeErrorMsg(`Invalid argument: ${fn}.`);
}
return !workerScript.disableLogs[fn];
},
getScriptLogs:
(ctx: NetscriptContext) =>
(fn: any, hostname: any, ...scriptArgs: any[]): string[] => {
const runningScriptObj = getRunningScript(ctx, fn, hostname, scriptArgs);
if (runningScriptObj == null) {
ctx.log(() => getCannotFindRunningScriptErrorMessage(fn, hostname, scriptArgs));
return [];
}
return runningScriptObj.logs.slice();
},
tail:
(ctx: NetscriptContext) =>
(fn: any, hostname: any = workerScript.hostname, ...scriptArgs: any[]): void => {
let runningScriptObj;
if (fn === undefined) {
runningScriptObj = workerScript.scriptRef;
} else if (typeof fn === "number") {
runningScriptObj = getRunningScriptByPid(fn);
} else {
runningScriptObj = getRunningScript(ctx, fn, hostname, scriptArgs);
}
if (runningScriptObj == null) {
ctx.log(() => getCannotFindRunningScriptErrorMessage(fn, hostname, scriptArgs));
return;
}
LogBoxEvents.emit(runningScriptObj);
},
closeTail:
(ctx: NetscriptContext) =>
(_pid: unknown = workerScript.scriptRef.pid): void => {
const pid = ctx.helper.number("pid", _pid);
//Emit an event to tell the game to close the tail window if it exists
LogBoxCloserEvents.emit(pid);
},
nuke:
(ctx: NetscriptContext) =>
(_hostname: unknown): boolean => {
const hostname = ctx.helper.string("hostname", _hostname);
const server = safeGetServer(hostname, ctx);
if (!(server instanceof Server)) {
ctx.log(() => "Cannot be executed on this server.");
return false;
}
if (server.hasAdminRights) {
ctx.log(() => `Already have root access to '${server.hostname}'.`);
return true;
}
if (!Player.hasProgram(Programs.NukeProgram.name)) {
throw ctx.makeRuntimeErrorMsg("You do not have the NUKE.exe virus!");
}
if (server.openPortCount < server.numOpenPortsRequired) {
throw ctx.makeRuntimeErrorMsg("Not enough ports opened to use NUKE.exe virus.");
}
server.hasAdminRights = true;
ctx.log(() => `Executed NUKE.exe virus on '${server.hostname}' to gain root access.`);
return true;
},
brutessh:
(ctx: NetscriptContext) =>
(_hostname: unknown): boolean => {