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.45 #41

Merged
merged 4 commits into from
Sep 20, 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.45](https://github.com/DIG-Network/dig-chia-sdk/compare/v0.0.1-alpha.44...v0.0.1-alpha.45) (2024-09-20)

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


### Features

* temp disable ssl on content server driver while ssl bug figured out ([28a3b3d](https://github.com/DIG-Network/dig-chia-sdk/commit/28a3b3d6ea9d7355e2b4260ba2547d57f0c7fd3c))

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


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.43",
"version": "0.0.1-alpha.45",
"description": "",
"type": "commonjs",
"main": "./dist/index.js",
Expand Down
114 changes: 65 additions & 49 deletions src/DigNetwork/DigNetwork.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ 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';
import { promisify } from "util";

const rename = promisify(fs.rename);
const unlink = promisify(fs.unlink);
Expand Down Expand Up @@ -178,7 +178,7 @@ export class DigNetwork {

const peerIp = digPeers[0];
const digPeer = new DigPeer(peerIp, storeId);
const storeResponse = await digPeer.propagationServer.headStore({
const storeResponse = await digPeer.contentServer.headStore({
hasRootHash: rootHash,
});

Expand Down Expand Up @@ -260,32 +260,37 @@ export class DigNetwork {
`${rootInfo.root_hash}.dat`
);

fs.writeFileSync(`${this.storeDir}/${rootInfo.root_hash}.dat`, rootResponse);
fs.writeFileSync(
`${this.storeDir}/${rootInfo.root_hash}.dat`,
rootResponse
);

const root = JSON.parse(rootResponse);

if (!skipData) {
// Use Object.entries() to iterate over the map (root.files)
await Promise.all(
Object.entries(root.files).map(
async ([storeKey, file]: [string, any]) => {
const filePath = getFilePathFromSha256(
file.sha256,
`${this.storeDir}/data`
);
if (!fs.existsSync(filePath) || forceDownload) {
console.log(
`Downloading file with sha256: ${file.sha256}...`
);
await this.downloadFileFromPeers(
`data/${file.sha256.match(/.{1,2}/g)!.join("/")}`,
filePath,
forceDownload
);
}
}
)
);
// Explicitly define the type for file entries
interface FileEntry {
sha256: string;
}

// Sequential file download
for (const [storeKey, file] of Object.entries<FileEntry>(
root.files
)) {
const filePath = getFilePathFromSha256(
file.sha256,
`${this.storeDir}/data`
);

if (!fs.existsSync(filePath) || forceDownload) {
console.log(`Downloading file with sha256: ${file.sha256}...`);
await this.downloadFileFromPeers(
`data/${file.sha256.match(/.{1,2}/g)!.join("/")}`,
filePath,
forceDownload
);
}
}
}
}

Expand Down Expand Up @@ -327,81 +332,92 @@ 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;


const response = await digPeer.propagationServer.headStore();

if (!response.success) {
continue;
}

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

// 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);

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);
});

// Rename the temp file to the final file path after successful download
await rename(tempFilePath, filePath);
if (process.env.DIG_DEBUG === '1') {

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
2 changes: 1 addition & 1 deletion src/blockchain/FullNodePeer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ export class FullNodePeer {

FullNodePeer.cachedPeer = { peer: bestPeer, timestamp: now };

console.log(`Using Peer: ${peerIPs[bestPeerIndex]}`);
console.log(`Using Fullnode Peer: ${peerIPs[bestPeerIndex]}`);

return bestPeer;
}
Expand Down
Loading