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

RFC1: Bitcoin Server Impl with Consensus Algo #22

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
38 changes: 38 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# Dependencies
node_modules
.pnp
.pnp.js

# Local env files
.env
.env.local
.env.development.local
.env.test.local
.env.production.local

# Testing
coverage

# Turbo
.turbo

# Vercel
.vercel

# Build Outputs
.next/
out/
build
dist


# Debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Misc
.DS_Store
*.pem
Empty file added .npmrc
Empty file.
20 changes: 20 additions & 0 deletions apps/central/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "central",
"version": "1.0.0",
"description": "",
"main": "dist/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "tsc && node dist/index.js"
},
"author": "",
"dependencies": {
"@repo/types": "",
"@repo/typescript-config": "",
"bs58": "^6.0.0",
"ws": "^8.18.0"
},
"devDependencies": {
"@types/ws": "^8.5.12"
}
}
144 changes: 144 additions & 0 deletions apps/central/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
import { WebSocketServer, WebSocket } from "ws";
import url from "url";

const wss = new WebSocketServer({ port: 8080 });
let miners: {
ws: WebSocket;
minerAddress: number;
}[] = [];

wss.on("connection", (ws: WebSocket, req) => {
//@ts-ignore
const minerAddress = url.parse(req.url, true).query["publicKey"] as string;

console.log("Here", minerAddress);

if (!minerAddress) {
console.error("Miner Address Missing");
ws.close();
return;
}

let miner = {
ws,
minerAddress: Date.now(),
};
miners.push(miner);
console.log("New miner connected.");

// Handle incoming messages from miners
ws.on("message", (message: string) => {
handleIncomingMessage(message, miner);
});

// Handle miner disconnect
ws.on("close", () => {
miners = miners.filter((miner) => miner.ws !== ws);
console.log("Miner disconnected.");
});
});

function handleIncomingMessage(
message: string,
miner: {
ws: WebSocket;
minerAddress: number;
},
) {
const data = JSON.parse(message);

switch (data.type) {
case "new_block":
// Broadcast the new block to all miners
console.log("Received new block. Broadcasting to all miners.");
broadcast(message, miner);
break;

case "transaction":
// Broadcast the transaction to all miners
console.log("Received new transaction. Broadcasting to all miners.");
broadcast(message, miner);
break;

case "sync_chain":
console.log("Received sync chain request");
const minersToRequest = miners.filter(m => m.minerAddress !== miner.minerAddress);
const requestSyncFromMiner = (index: number) => {
if (index >= minersToRequest.length) {
console.log("No miners available to fulfill sync request");
return;
}

const targetMiner = minersToRequest[index];
if (!targetMiner) {
console.log("Miner not found. Trying next miner.");
requestSyncFromMiner(index + 1);
return;
}
targetMiner.ws.send(JSON.stringify({
type: 'sync_chain',
blockIndex: data.blockIndex
}));

const responseHandler = (response: string) => {
const parsedResponse = JSON.parse(response);
if (parsedResponse.type === 'sync_chain_response') {
if (parsedResponse.error) {
console.log(`Sync request failed for miner ${targetMiner.minerAddress}. Trying next miner.`);
requestSyncFromMiner(index + 1);
} else {
console.log(`Received sync response from miner ${targetMiner.minerAddress}. Forwarding to requester.`);
miner.ws.send(response);
targetMiner.ws.removeListener('message', responseHandler);
}
}
};

targetMiner.ws.on('message', responseHandler);

// Set a timeout in case the miner doesn't respond
setTimeout(() => {
if (targetMiner.ws.listenerCount('message') > 0) {
console.log(`Sync request timed out for miner ${targetMiner.minerAddress}. Trying next miner.`);
targetMiner.ws.removeListener('message', responseHandler);
requestSyncFromMiner(index + 1);
}
}, 5000); // 5 second timeout
};

requestSyncFromMiner(0);
break;

case "request_missing_blocks":
// Handle the request for missing blocks
handleMissingBlocksRequest(data.latestKnownHash, miner);
break;

default:
console.log("Unknown message type:", data.type);
}
}

console.log("Central WebSocket server running on port 8080.");

function broadcast(
message: string,
fromMiner: {
ws: WebSocket;
minerAddress: number;
},
) {
miners.map((miner) => {
if (miner.minerAddress != fromMiner.minerAddress) {
miner.ws.send(message);
}
});
}

function handleMissingBlocksRequest(
latestKnownHash: string,
miner: {
ws: WebSocket;
minerAddress: number;
},
) {}
9 changes: 9 additions & 0 deletions apps/central/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "@repo/typescript-config/base.json",
"compilerOptions": {
"outDir": "dist",
"rootDir": "src"
},
"include": ["src"],
"exclude": ["node_modules", "dist"]
}
17 changes: 17 additions & 0 deletions apps/miner/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"name": "miner",
"version": "1.0.0",
"description": "",
"main": "dist/index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"dev": "tsc && node dist/index.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"@repo/types": "",
"@repo/typescript-config": "",
"bs58": "^6.0.0"
}
}
47 changes: 47 additions & 0 deletions apps/miner/src/Block.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import Transaction from "@repo/types/transaction"
import * as crypto from 'crypto';

class Block {
timestamp: number;
transactions: Transaction[];
previousHash: string;
hash: string;
nonce: number;
blockIndex: number;

constructor(transactions: Transaction[],previousHash: string,blockIndex: number, timestamp?: number,nonce?: number) {
this.timestamp = timestamp ? timestamp : Date.now();
this.transactions = transactions;
this.previousHash = previousHash;
this.nonce = nonce ? nonce : 0;
this.hash = this.calculateHash();
this.blockIndex = blockIndex;
}

calculateHash(): string {
const data = this.previousHash + this.timestamp + JSON.stringify(this.transactions) + this.nonce;
return crypto.createHash('sha256').update(data).digest('hex');
}

mineBlock(difficulty: number): void {
while(this.hash.substring(0,difficulty) !== Array(difficulty + 1).join("0")) {
this.nonce++;
this.hash = this.calculateHash();
}
console.log(`Block mined: ${this.hash}`);
console.log('')
}

hasValidTransactions(): boolean {
for (const tx of this.transactions) {
if (!tx.isValid()) {
return false;
}
}
return true;
}

}


export default Block;
Loading