Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Release/v0.0.1 alpha.41 #38

Merged
merged 3 commits into from
Sep 19, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,15 @@

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.41](https://github.com/DIG-Network/dig-chia-sdk/compare/v0.0.1-alpha.40...v0.0.1-alpha.41) (2024-09-19)


### Bug Fixes

* findPeerWithStoreKey ([8d6d509](https://github.com/DIG-Network/dig-chia-sdk/commit/8d6d509f9f2071d9ad4004f083e208b67c34aea2))

### [0.0.1-alpha.40](https://github.com/DIG-Network/dig-chia-sdk/compare/v0.0.1-alpha.39...v0.0.1-alpha.40) (2024-09-19)

### [0.0.1-alpha.39](https://github.com/DIG-Network/dig-chia-sdk/compare/v0.0.1-alpha.38...v0.0.1-alpha.39) (2024-09-19)


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.39",
"version": "0.0.1-alpha.41",
"description": "",
"type": "commonjs",
"main": "./dist/index.js",
Expand Down
76 changes: 42 additions & 34 deletions src/DigNetwork/DigNetwork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ import { getFilePathFromSha256 } from "../utils/hashUtils";
import { DataStore, ServerCoin } from "../blockchain";
import { DIG_FOLDER_PATH } from "../utils/config";
import { RootHistoryItem } from "../types";
import { promisify } from 'util';

const rename = promisify(fs.rename);
const unlink = promisify(fs.unlink);

export class DigNetwork {
private dataStore: DataStore;
Expand Down Expand Up @@ -224,7 +228,7 @@ export class DigNetwork {
);
}

await this.downloadHeightFile(forceDownload);
await this.downloadHeightFile(true);

const rootHistorySorted = rootHistory
.filter((item) => item.timestamp !== undefined)
Expand Down Expand Up @@ -265,7 +269,7 @@ export class DigNetwork {
`Downloading file with sha256: ${file.sha256}...`
);
await this.downloadFileFromPeers(
file.sha256.match(/.{1,2}/g)!.join("/"),
`data/${file.sha256.match(/.{1,2}/g)!.join("/")}`,
filePath,
forceDownload
);
Expand Down Expand Up @@ -314,77 +318,81 @@ export class DigNetwork {
forceDownload
);
}

private async downloadFileFromPeers(
dataPath: string,
filePath: string,
overwrite: boolean
): Promise<void> {
let digPeers = await this.fetchAvailablePeers();

const tempFilePath = `${filePath}.tmp`;

while (true) {
if (!overwrite && fs.existsSync(filePath)) return;

const blacklist = this.peerBlacklist.get(dataPath) || new Set<string>();

for (const digPeer of digPeers) {
if (blacklist.has(digPeer.IpAddress)) continue;

try {
// Create directory if it doesn't exist
const directory = path.dirname(filePath);
const directory = path.dirname(tempFilePath);
if (!fs.existsSync(directory)) {
fs.mkdirSync(directory, { recursive: true });
}

// Stream the file data directly to the file system
const fileStream = fs.createWriteStream(filePath);

// Stream the file data to a temporary file
const fileStream = fs.createWriteStream(tempFilePath);
// Start streaming the data from the peer
const peerStream = await digPeer.propagationServer.streamStoreData(
dataPath
);

// Pipe the peer stream directly to the file system
const peerStream = await digPeer.propagationServer.streamStoreData(dataPath);

// Pipe the peer stream to the temp file
await new Promise<void>((resolve, reject) => {
peerStream.pipe(fileStream);

peerStream.on("end", resolve);
peerStream.on("error", reject);
fileStream.on("error", reject);
peerStream.on('end', resolve);
peerStream.on('error', reject);
fileStream.on('error', reject);
});

if (process.env.DIG_DEBUG === "1") {

// Rename the temp file to the final file path after successful download
await rename(tempFilePath, filePath);

if (process.env.DIG_DEBUG === '1') {
console.log(`Downloaded ${dataPath} from ${digPeer.IpAddress}`);
}

return; // Exit the method if download succeeds
} catch (error) {
console.warn(
`Failed to download ${dataPath} from ${digPeer.IpAddress}, blacklisting peer and trying next...`
);
blacklist.add(digPeer.IpAddress);

// Clean up the temp file in case of failure
if (fs.existsSync(tempFilePath)) {
await unlink(tempFilePath);
}
}
}

this.peerBlacklist.set(dataPath, blacklist);

if (blacklist.size >= digPeers.length) {
if (process.env.DIG_DEBUG === "1") {
console.warn(
`All peers blacklisted for ${dataPath}. Refreshing peers...`
);
if (process.env.DIG_DEBUG === '1') {
console.warn(`All peers blacklisted for ${dataPath}. Refreshing peers...`);
}

digPeers = await this.fetchAvailablePeers();
if (!digPeers.length) {
throw new Error(
`Failed to download ${dataPath}: no peers available.`
);
throw new Error(`Failed to download ${dataPath}: no peers available.`);
}
}
}
}


private async runProgressBar(
total: number,
Expand Down
Loading