Skip to content

Commit

Permalink
Merge pull request #147 from DIG-Network/release/v0.0.1-alpha.163
Browse files Browse the repository at this point in the history
Release/v0.0.1 alpha.163
  • Loading branch information
MichaelTaylor3D authored Oct 7, 2024
2 parents ae4a0fe + 1286bac commit ff517d5
Show file tree
Hide file tree
Showing 5 changed files with 67 additions and 30 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.

### [0.0.1-alpha.163](https://github.com/DIG-Network/dig-chia-sdk/compare/v0.0.1-alpha.162...v0.0.1-alpha.163) (2024-10-07)

### [0.0.1-alpha.162](https://github.com/DIG-Network/dig-chia-sdk/compare/v0.0.1-alpha.161...v0.0.1-alpha.162) (2024-10-07)


Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dignetwork/dig-sdk",
"version": "0.0.1-alpha.162",
"version": "0.0.1-alpha.163",
"description": "",
"type": "commonjs",
"main": "./dist/index.js",
Expand Down
2 changes: 1 addition & 1 deletion src/blockchain/FullNodePeer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export class FullNodePeer {
private static cooldownCache = new NodeCache({ stdTTL: COOLDOWN_DURATION / 1000 });

// Failed DNS hosts cooldown cache
private static failedDNSCache = new NodeCache({ stdTTL: COOLDOWN_DURATION / 1000 });
private static failedDNSCache = new NodeCache({ stdTTL: 86400 });

// Peer reliability weights
private static peerWeights: Map<string, number> = new Map();
Expand Down
87 changes: 61 additions & 26 deletions src/utils/network.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,70 @@
// @ts-ignore
import stun, { STUN_BINDING_REQUEST } from 'node-stun';
import superagent from "superagent";
import { Environment } from "./Environment";

// Get the Coturn server hostname from the environment variable or default to "localhost"
const COTURN_SERVER = process.env.STUN_SERVER || 'coturn'; // "coturn" refers to the Coturn service in Docker Compose
const COTURN_PORT = 3478; // Standard STUN port
const MAX_RETRIES = 5;
const RETRY_DELAY = 2000; // in milliseconds

// Regular expression for validating both IPv4 and IPv6 addresses
const ipv4Regex =
/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
const ipv6Regex =
/^(([0-9a-fA-F]{1,4}:){7}([0-9a-fA-F]{1,4}|:)|(([0-9a-fA-F]{1,7}|:):){1,7}([0-9a-fA-F]{1,4}|:))$/;

// Regular expression for validating hostnames
const hostnameRegex = /^(([a-zA-Z0-9](-*[a-zA-Z0-9])*)\.)*[a-zA-Z]{2,}$/;

// Helper function to validate the IP address or hostname
const isValidHost = (host: string): boolean => {
return ipv4Regex.test(host) || ipv6Regex.test(host) || hostnameRegex.test(host);
};

export const getPublicHost = async (): Promise<string | undefined> => {
return new Promise((resolve, reject) => {
const client = stun.createClient();

client.request(
COTURN_SERVER,
COTURN_PORT,
{ request: STUN_BINDING_REQUEST },
(err: any, response: any) => {
if (err) {
reject(`Failed to connect to Coturn server: ${err.message}`);
return;
}
const publicHost = process.env.PUBLIC_IP;

if (publicHost) {
console.log("Public IP/Hostname from env:", publicHost);

if (isValidHost(publicHost)) {
return publicHost;
}

console.error("Invalid public IP/Hostname in environment variable");
return undefined;
}

// Extract public IP and port from the STUN response
const { address, port } = response.getXorAddress();
if (address && port) {
resolve(address);
} else {
reject('Failed to obtain public IP from Coturn server');
let attempt = 0;

while (attempt < MAX_RETRIES) {
try {
const response = await superagent.get(
"https://api.datalayer.storage/user/v1/get_user_ip"
);

if (response.body && response.body.success) {
const ipAddress = response.body.ip_address;

if (isValidHost(ipAddress)) {
return ipAddress;
}
throw new Error("Invalid IP address or hostname format received");
}
throw new Error("Failed to retrieve public host");
} catch (error: any) {
attempt++;
console.error(
`Error fetching public host (Attempt ${attempt}):`,
error.message
);

if (attempt >= MAX_RETRIES) {
throw new Error(
"Could not retrieve public host after several attempts"
);
}
);
});

await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
}
}
};


Expand All @@ -44,4 +79,4 @@ export const formatHost = (host: string): string => {
}

return host; // Return the host as is (IPv4, hostname, or already bracketed IPv6)
};
};

0 comments on commit ff517d5

Please sign in to comment.