Skip to content

Commit

Permalink
REFACTOR: Employ optional struct to control which server identifier (…
Browse files Browse the repository at this point in the history
…hostname or IP address) gets returned from applicable methods
  • Loading branch information
NagaOuroboros committed Mar 8, 2025
1 parent e4f1b3b commit 52e7d11
Show file tree
Hide file tree
Showing 15 changed files with 148 additions and 146 deletions.
20 changes: 20 additions & 0 deletions markdown/bitburner.hostreturnoptions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [bitburner](./bitburner.md) &gt; [HostReturnOptions](./bitburner.hostreturnoptions.md)

## HostReturnOptions interface

Options to control how a server identifier (hostname or IP address) is returned. Affects the behavior of [scan](./bitburner.ns.scan.md)<!-- -->, [getPurchasedServers](./bitburner.ns.getpurchasedservers.md)<!-- -->, and [getCurrentServer](./bitburner.singularity.getcurrentserver.md)

**Signature:**

```typescript
interface HostReturnOptions
```

## Properties

| Property | Modifiers | Type | Description |
| --- | --- | --- | --- |
| [returnByIP?](./bitburner.hostreturnoptions.returnbyip.md) | | boolean | _(Optional)_ If set to <code>true</code>, returns IP addresses instead of hostnames. Defaults to <code>false</code>. |

13 changes: 13 additions & 0 deletions markdown/bitburner.hostreturnoptions.returnbyip.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [bitburner](./bitburner.md) &gt; [HostReturnOptions](./bitburner.hostreturnoptions.md) &gt; [returnByIP](./bitburner.hostreturnoptions.returnbyip.md)

## HostReturnOptions.returnByIP property

If set to `true`<!-- -->, returns IP addresses instead of hostnames. Defaults to `false`<!-- -->.

**Signature:**

```typescript
returnByIP?: boolean;
```
1 change: 1 addition & 0 deletions markdown/bitburner.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
| [HacknetRAMRequirement](./bitburner.hacknetramrequirement.md) | Player's Hacknet devices must have at least this much total RAM. |
| [HacknetServerConstants](./bitburner.hacknetserverconstants.md) | Hacknet server related constants |
| [HacknetServersFormulas](./bitburner.hacknetserversformulas.md) | Hacknet Server formulas |
| [HostReturnOptions](./bitburner.hostreturnoptions.md) | Options to control how a server identifier (hostname or IP address) is returned. Affects the behavior of [scan](./bitburner.ns.scan.md)<!-- -->, [getPurchasedServers](./bitburner.ns.getpurchasedservers.md)<!-- -->, and [getCurrentServer](./bitburner.singularity.getcurrentserver.md) |
| [HP](./bitburner.hp.md) | |
| [ILocation](./bitburner.ilocation.md) | |
| [IndustryData](./bitburner.industrydata.md) | Corporation industry information |
Expand Down
13 changes: 10 additions & 3 deletions markdown/bitburner.ns.getpurchasedservers.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,25 @@

## NS.getPurchasedServers() method

Returns an array with the hostnames of all of the servers you have purchased.
Returns an array with the hostnames or IP addresses of all of the servers you have purchased. Returns hostnames by default.

**Signature:**

```typescript
getPurchasedServers(): string[];
getPurchasedServers(returnOpts?: HostReturnOptions): string[];
```

## Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| returnOpts | [HostReturnOptions](./bitburner.hostreturnoptions.md) | _(Optional)_ Optional. Controls whether the function returns IPs |

**Returns:**

string\[\]

Returns an array with the hostnames of all of the servers you have purchased.
Returns an array with the hostnames or IP addresses of all of the servers you have purchased.

## Remarks

Expand Down
23 changes: 0 additions & 23 deletions markdown/bitburner.ns.getpurchasedserversbyip.md

This file was deleted.

6 changes: 2 additions & 4 deletions markdown/bitburner.ns.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,7 @@ export async function main(ns) {
| [getPurchasedServerCost(ram)](./bitburner.ns.getpurchasedservercost.md) | Get cost of purchasing a server. |
| [getPurchasedServerLimit()](./bitburner.ns.getpurchasedserverlimit.md) | Returns the maximum number of servers you can purchase. |
| [getPurchasedServerMaxRam()](./bitburner.ns.getpurchasedservermaxram.md) | Returns the maximum RAM that a purchased server can have. |
| [getPurchasedServers()](./bitburner.ns.getpurchasedservers.md) | Returns an array with the hostnames of all of the servers you have purchased. |
| [getPurchasedServersByIP()](./bitburner.ns.getpurchasedserversbyip.md) | Returns an array with the IP addresses of all of the servers you have purchased. |
| [getPurchasedServers(returnOpts)](./bitburner.ns.getpurchasedservers.md) | Returns an array with the hostnames or IP addresses of all of the servers you have purchased. Returns hostnames by default. |
| [getPurchasedServerUpgradeCost(host, ram)](./bitburner.ns.getpurchasedserverupgradecost.md) | Get cost of upgrading a purchased server to the given ram. |
| [getRecentScripts()](./bitburner.ns.getrecentscripts.md) | Get an array of recently killed scripts across all servers. |
| [getResetInfo()](./bitburner.ns.getresetinfo.md) | Get information about resets. |
Expand Down Expand Up @@ -154,8 +153,7 @@ export async function main(ns) {
| [resizeTail(width, height, pid)](./bitburner.ns.resizetail.md) | Resize a tail window. This function is deprecated and will be removed in a later version. |
| [rm(name, host)](./bitburner.ns.rm.md) | Delete a file. |
| [run(script, threadOrOptions, args)](./bitburner.ns.run.md) | Start another script on the current server. |
| [scan(host)](./bitburner.ns.scan.md) | Get the list of hostnames connected to a server. |
| [scanByIP(host)](./bitburner.ns.scanbyip.md) | Get the list of IPs connected to a server. |
| [scan(host, returnOpts)](./bitburner.ns.scan.md) | Get the list of hostnames or IP addresses connected to a server. |
| [scp(files, destination, source)](./bitburner.ns.scp.md) | Copy file between servers. |
| [scriptKill(script, host)](./bitburner.ns.scriptkill.md) | Kill all scripts with a filename. |
| [scriptRunning(script, host)](./bitburner.ns.scriptrunning.md) | Check if any script with a filename is running. |
Expand Down
13 changes: 10 additions & 3 deletions markdown/bitburner.ns.scan.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,20 @@

## NS.scan() method

Get the list of hostnames connected to a server.
Get the list of hostnames or IP addresses connected to a server.

**Signature:**

```typescript
scan(host?: string): string[];
scan(host?: string, returnOpts?: HostReturnOptions): string[];
```

## Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| host | string | _(Optional)_ Optional. Hostname/IP of the server to scan, default to current server. |
| returnOpts | [HostReturnOptions](./bitburner.hostreturnoptions.md) | _(Optional)_ Optional. Controls whether the function returns IPs. |

**Returns:**

Expand All @@ -28,7 +29,7 @@ Returns an array of hostnames.

RAM cost: 0.2 GB

Returns an array containing the hostnames of all servers that are one node way from the specified target server. The hostnames in the returned array are strings.
Returns an array containing the hostnames or IP addresses of all servers that are one node way from the specified target server. The hostnames/IPs in the returned array are strings. Returns hostnames by default.

The server network is a tree graph with the home server at the root. The parent node is always the first item of the returned array.

Expand Down Expand Up @@ -63,6 +64,12 @@ let neighbor = ns.scan();
for (let i = 0; i < neighbor.length; i++) {
ns.tprint(neighbor[i]);
}
// All servers that are one hop from the current server, but by IP address.
ns.tprint("IPs of current server's neighbors.");
let neighbor = ns.scan(null, { returnByIP: true });
for (let i = 0; i < neighbor.length; i++) {
ns.tprint(neighbor[i]);
}
// All neighbors of n00dles.
const target = "n00dles";
neighbor = ns.scan(target);
Expand Down
34 changes: 0 additions & 34 deletions markdown/bitburner.ns.scanbyip.md

This file was deleted.

13 changes: 10 additions & 3 deletions markdown/bitburner.singularity.getcurrentserver.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,25 @@

## Singularity.getCurrentServer() method

Get the current server.
Get the current server. Returns the hostname by default.

**Signature:**

```typescript
getCurrentServer(): string;
getCurrentServer(returnOpts?: HostReturnOptions): string;
```

## Parameters

| Parameter | Type | Description |
| --- | --- | --- |
| returnOpts | [HostReturnOptions](./bitburner.hostreturnoptions.md) | _(Optional)_ Optional. Controls whether the function returns an IP. |

**Returns:**

string

Name of the current server.
Hostname or IP address of the current server.

## Remarks

Expand Down
2 changes: 1 addition & 1 deletion markdown/bitburner.singularity.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ This API requires Source-File 4 to use. The RAM cost of all these functions is m
| [getCompanyRep(companyName)](./bitburner.singularity.getcompanyrep.md) | Get company reputation. |
| [getCrimeChance(crime)](./bitburner.singularity.getcrimechance.md) | Get chance to successfully commit a crime. |
| [getCrimeStats(crime)](./bitburner.singularity.getcrimestats.md) | Get stats related to a crime. |
| [getCurrentServer()](./bitburner.singularity.getcurrentserver.md) | Get the current server. |
| [getCurrentServer(returnOpts)](./bitburner.singularity.getcurrentserver.md) | Get the current server. Returns the hostname by default. |
| [getCurrentWork()](./bitburner.singularity.getcurrentwork.md) | Get the current work the player is doing. |
| [getDarkwebProgramCost(programName)](./bitburner.singularity.getdarkwebprogramcost.md) | Check the price of an exploit on the dark web |
| [getDarkwebPrograms()](./bitburner.singularity.getdarkwebprograms.md) | Get a list of programs offered on the dark web. |
Expand Down
21 changes: 21 additions & 0 deletions src/Netscript/NetscriptHelpers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,8 @@ export const helpers = {
scriptArgs,
runOptions,
spawnOptions,
hostReturnOptions,
returnServerID,
argsToString,
basicErrorMessage,
errorMessage,
Expand Down Expand Up @@ -120,6 +122,10 @@ export interface CompleteHGWOptions {
stock: boolean;
additionalMsec: number;
}
/** HostReturnOptions with non-optional, type-validated members, for passing between internal functions */
export interface CompleteHostReturnOptions {
returnByIP: boolean;
}

/** Convert a provided value v for argument argName to string. If it wasn't originally a string or number, throw. */
function string(ctx: NetscriptContext, argName: string, v: unknown): string {
Expand Down Expand Up @@ -230,6 +236,21 @@ function spawnOptions(ctx: NetscriptContext, threadOrOption: unknown): CompleteS
return result;
}

function hostReturnOptions(returnOpts: unknown): CompleteHostReturnOptions {
const result: CompleteHostReturnOptions = { returnByIP: false };
if (typeof returnOpts !== "object" || !returnOpts) return result;
// Safe assertion since threadOrOption type has been narrowed to a non-null object
const { returnByIP } = returnOpts as Unknownify<CompleteHostReturnOptions>;
result.returnByIP = !!returnByIP;
return result;
}

/** Returns a servers hostname or IP based on the `returnByIP` field of HostReturnOptions */
function returnServerID(server: BaseServer, returnOpts: CompleteHostReturnOptions): string {
const { returnByIP } = hostReturnOptions(returnOpts);
return returnByIP ? server.ip : server.hostname;
}

function mapToString(map: Map<unknown, unknown>): string {
const formattedMap = [...map]
.map((m) => {
Expand Down
2 changes: 0 additions & 2 deletions src/Netscript/RamCostGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -498,7 +498,6 @@ export const RamCosts: RamCostTree<NSFull> = {
sprintf: 0,
vsprintf: 0,
scan: RamCostConstants.Scan,
scanByIP: RamCostConstants.Scan,
hack: RamCostConstants.Hack,
hackAnalyzeThreads: RamCostConstants.HackAnalyze,
hackAnalyze: RamCostConstants.HackAnalyze,
Expand Down Expand Up @@ -568,7 +567,6 @@ export const RamCosts: RamCostTree<NSFull> = {
getPurchasedServerCost: RamCostConstants.GetPurchaseServer,
getPurchasedServerUpgradeCost: 0.1,
getPurchasedServers: 1.05,
getPurchasedServersByIP: 1.05,
upgradePurchasedServer: 0.25,
renamePurchasedServer: 0,
purchaseServer: RamCostConstants.PurchaseServer,
Expand Down
58 changes: 23 additions & 35 deletions src/NetscriptFunctions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,32 +161,23 @@ export const ns: InternalAPI<NSFull> = {
}
return vsprintf(format, _args);
},
scan: (ctx) => (_host) => {
scan: (ctx) => (_host, _returnOpts) => {
const host = _host ? helpers.string(ctx, "host", _host) : ctx.workerScript.hostname;
const returnOpts = helpers.hostReturnOptions(_returnOpts);
const server = helpers.getServer(ctx, host);
const out: string[] = [];
for (let i = 0; i < server.serversOnNetwork.length; i++) {
const s = getServerOnNetwork(server, i);
if (s === null) continue;
const entry = s.hostname;
const entry = helpers.returnServerID(s, returnOpts);
if (entry === null) continue;
out.push(entry);
}
helpers.log(ctx, () => `returned ${server.serversOnNetwork.length} connections for ${server.hostname}`);
return out;
},
scanByIP: (ctx) => (_host) => {
const host = _host ? helpers.string(ctx, "host", _host) : ctx.workerScript.hostname;
const server = helpers.getServer(ctx, host);
const out: string[] = [];
for (let i = 0; i < server.serversOnNetwork.length; i++) {
const s = getServerOnNetwork(server, i);
if (s === null) continue;
const entry = s.ip;
if (entry === null) continue;
out.push(entry);
}
helpers.log(ctx, () => `returned ${server.serversOnNetwork.length} connections for ${server.ip}`);
helpers.log(
ctx,
() =>
`returned ${server.serversOnNetwork.length} connections for ${isIPAddress(host) ? server.ip : server.hostname}`,
);
return out;
},
hasTorRouter: () => () => Player.hasTorRouter(),
Expand Down Expand Up @@ -1157,9 +1148,9 @@ export const ns: InternalAPI<NSFull> = {
return server.ramUsed;
},
dnsLookup: (ctx) => (_host) => {
const identifier = helpers.string(ctx, "host", _host);
const server = helpers.getServer(ctx, identifier);
return isIPAddress(identifier) ? server.hostname : server.ip;
const host = helpers.string(ctx, "host", _host);
const server = helpers.getServer(ctx, host);
return isIPAddress(host) ? server.hostname : server.ip;
},
serverExists: (ctx) => (_host) => {
const host = helpers.string(ctx, "host", _host);
Expand Down Expand Up @@ -1370,21 +1361,18 @@ export const ns: InternalAPI<NSFull> = {
helpers.log(ctx, () => `Could not find server ${hostname} as a purchased server. This is a bug. Report to dev.`);
return false;
},
getPurchasedServers: () => (): string[] => {
const res: string[] = [];
Player.purchasedServers.forEach(function (hostname) {
res.push(hostname);
});
return res;
},
getPurchasedServersByIP: (ctx) => (): string[] => {
const res: string[] = [];
Player.purchasedServers.forEach(function (hostname) {
const server = helpers.getServer(ctx, hostname);
res.push(server.ip);
});
return res;
},
getPurchasedServers:
(ctx) =>
(_returnOpts): string[] => {
const returnOpts = helpers.hostReturnOptions(_returnOpts);
const res: string[] = [];
Player.purchasedServers.forEach(function (hostname) {
const server = helpers.getServer(ctx, hostname);
const id = helpers.returnServerID(server, returnOpts);
res.push(id);
});
return res;
},
writePort: (ctx) => (_portNumber, data) => {
const portNumber = helpers.portNumber(ctx, _portNumber);
return writePort(portNumber, data);
Expand Down
Loading

0 comments on commit 52e7d11

Please sign in to comment.