Skip to content

Commit

Permalink
Merge pull request #152 from DIG-Network/release/v0.0.1-alpha.168
Browse files Browse the repository at this point in the history
Release/v0.0.1 alpha.168
  • Loading branch information
MichaelTaylor3D authored Oct 10, 2024
2 parents 5583db6 + 17c0401 commit d223616
Show file tree
Hide file tree
Showing 6 changed files with 134 additions and 30 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,13 @@

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.168](https://github.com/DIG-Network/dig-chia-sdk/compare/v0.0.1-alpha.167...v0.0.1-alpha.168) (2024-10-10)


### Bug Fixes

* waitForConfirmation fix ([829f5cc](https://github.com/DIG-Network/dig-chia-sdk/commit/829f5cc91e69d0cface3a70d11aacb23e689469f))

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


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.167",
"version": "0.0.1-alpha.168",
"description": "",
"type": "commonjs",
"main": "./dist/index.js",
Expand Down
2 changes: 1 addition & 1 deletion src/DigNetwork/PropagationServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ export class PropagationServer {

// If not cached, proceed with the HTTP request
const spinner = createSpinner(
`Checking if store ${this.storeId} exists...`
`Checking if store ${this.storeId} exists on peer: ${this.ipAddress}`
).start();

try {
Expand Down
64 changes: 38 additions & 26 deletions src/blockchain/FullNodePeer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,16 +307,25 @@ export class FullNodePeer {
* @returns {string} The selected peer IP.
*/
private static selectPeerRoundRobin(): string {
const peers = Array.from(FullNodePeer.peerWeights.keys()).filter(
(ip) => !FullNodePeer.cooldownCache.has(ip)
const availablePrioritizedPeers = FullNodePeer.prioritizedPeers.filter(
(ip) => !FullNodePeer.cooldownCache.has(ip) && FullNodePeer.peerWeights.has(ip)
);

if (peers.length === 0) {
throw new Error("All fullnode peers are in cooldown.");

if (availablePrioritizedPeers.length > 0) {
// Select the first available prioritized peer
return availablePrioritizedPeers[0];
}

// Round-robin selection
const selectedPeer = peers[FullNodePeer.roundRobinIndex % peers.length];

// If no prioritized peers are available, proceed with round-robin among other peers
const regularPeers = Array.from(FullNodePeer.peerWeights.keys()).filter(
(ip) => !FullNodePeer.prioritizedPeers.includes(ip) && !FullNodePeer.cooldownCache.has(ip)
);

if (regularPeers.length === 0) {
throw new Error("No available peers to connect.");
}

const selectedPeer = regularPeers[FullNodePeer.roundRobinIndex % regularPeers.length];
FullNodePeer.roundRobinIndex += 1;
return selectedPeer;
}
Expand Down Expand Up @@ -447,12 +456,14 @@ export class FullNodePeer {

return result;
} catch (error: any) {
FullNodePeer.handlePeerDisconnection(peerIP);

// If the error is WebSocket-related or timeout, reset the peer
if (
error.message.includes("WebSocket") ||
error.message.includes("Operation timed out")
) {
FullNodePeer.handlePeerDisconnection(peerIP);

const newPeer = await this.getBestPeer();
return (newPeer as any)[prop](...args);
}
Expand Down Expand Up @@ -486,10 +497,6 @@ export class FullNodePeer {

// Remove the limiter
FullNodePeer.peerLimiters.delete(peerIP);

console.warn(
`Fullnode Peer ${peerIP} has been marked as disconnected and is in cooldown.`
);
}

/**
Expand All @@ -516,20 +523,25 @@ export class FullNodePeer {
): Promise<boolean> {
const spinner = createSpinner("Waiting for confirmation...").start();
const peer = await FullNodePeer.connect();
while (true) {
try {
await peer.waitForCoinToBeSpent(
parentCoinInfo,
MIN_HEIGHT,
Buffer.from(MIN_HEIGHT_HEADER_HASH, "hex")
);

try {
await peer.waitForCoinToBeSpent(
parentCoinInfo,
MIN_HEIGHT,
Buffer.from(MIN_HEIGHT_HEADER_HASH, "hex")
);

spinner.success({ text: "Coin confirmed!" });
return true;
} catch (error: any) {
spinner.error({ text: "Error while waiting for confirmation." });
console.error(`waitForConfirmation error: ${error.message}`);
throw error;
spinner.success({ text: "Coin confirmed!" });
return true;
} catch (error: any) {
if (error.message.includes("UnknownCoin")) {
await new Promise((resolve) => setTimeout(resolve, 1000));
} else {
spinner.error({ text: "Error while waiting for confirmation." });
console.error(`waitForConfirmation error: ${error.message}`);
throw error;
}
}
}
}
}
85 changes: 85 additions & 0 deletions src/utils/directoryUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,3 +105,88 @@ export const calculateFolderSize = (folderPath: string): bigint => {

return totalSize;
};

/**
* Represents the result of listing files.
* - If `groupSize` is not provided, returns an array of relative file paths.
* - If `groupSize` is provided, returns an array of arrays, each containing up to `groupSize` file paths.
*/
type ListFilesResult = string[] | string[][];

/**
* Recursively lists all files in a directory, excluding specified folders and respecting `.gitignore` rules.
* Optionally groups the list into batches of a specified size.
*
* @param {string} baseDir - The base directory path to start listing files from.
* @param {number} [groupSize] - Optional. The number of files per group. If provided, the result will be an array of arrays.
* @returns {ListFilesResult} - A flat list of relative file paths or grouped lists based on `groupSize`.
*/
function listFilesRecursively(
baseDir: string,
groupSize?: number
): ListFilesResult {
// Initialize the ignore instance
const ig = ignore();

// Path to .gitignore
const gitignorePath = path.join(baseDir, ".gitignore");

// Load and parse .gitignore if it exists
if (fs.existsSync(gitignorePath)) {
const gitignoreContent = fs.readFileSync(gitignorePath, "utf-8");
ig.add(gitignoreContent);
}

// Initialize result containers
const allFiles: string[] = [];
let groupedFiles: string[][] = [];

/**
* Recursively traverses directories to collect files.
*
* @param {string} currentDir - The current directory path being traversed.
*/
function traverseDirectory(currentDir: string): void {
let entries: fs.Dirent[];

try {
entries = fs.readdirSync(currentDir, { withFileTypes: true });
} catch (err) {
console.error(`Failed to read directory: ${currentDir}. Error: ${(err as Error).message}`);
return;
}

for (const entry of entries) {
const entryName = entry.name;
const fullPath = path.join(currentDir, entryName);
const relativePath = path.relative(baseDir, fullPath).replace(/\\/g, "/"); // Normalize to forward slashes

// Skip .git and .dig directories and any ignored paths
if (entryName === ".git" || entryName === ".dig" || ig.ignores(relativePath)) {
continue;
}

if (entry.isDirectory()) {
traverseDirectory(fullPath); // Recurse into subdirectory
} else if (entry.isFile()) {
allFiles.push(relativePath);
}
// Optionally handle symbolic links or other types if needed
}
}

// Start traversal from the base directory
traverseDirectory(baseDir);

// If groupSize is provided and valid, group the files accordingly
if (groupSize && Number.isInteger(groupSize) && groupSize > 0) {
groupedFiles = [];
for (let i = 0; i < allFiles.length; i += groupSize) {
groupedFiles.push(allFiles.slice(i, i + groupSize));
}
return groupedFiles;
}

// Return the flat list of files if grouping is not required
return allFiles;
}

0 comments on commit d223616

Please sign in to comment.