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

RFC-1: Bitcoin Like Server with UTXO based transaction #19

Open
wants to merge 2 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
130 changes: 130 additions & 0 deletions rfc-1/CentralServer/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp
.cache

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
206 changes: 206 additions & 0 deletions rfc-1/CentralServer/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
const express = require('express');
const mongoose = require('mongoose');
const http = require('http');
const WebSocket = require('ws');
const nacl = require('tweetnacl');
const { PublicKey } = require('@solana/web3.js');
const crypto = require('crypto');
const axios = require('axios');
const Mempool = require('./model/mempool');
const Miner = require('./model/miner');
const Block = require("./model/block");
const cors = require('cors');


const app = express();
app.use(cors());
const httpServer = http.createServer(app);
const wss = new WebSocket.Server({ server: httpServer });

mongoose.connect('mongodb://localhost:27017/bitcoin_simulator');

app.use(express.json());

let connectedMiners = {};

function generateMinerId() {
return crypto.randomBytes(16).toString('hex');
}

function generateHash(data) {
return crypto.createHash('sha256').update(data).digest();
}

function verifySignature(message, signatureHex, pubKeyBase58) {
const hash = generateHash(message);
const signature = Buffer.from(signatureHex, 'hex');

try {
const publicKey = new PublicKey(pubKeyBase58);
return nacl.sign.detached.verify(hash, signature, publicKey.toBuffer());
} catch (err) {
console.error('Error verifying signature:', err);
return false;
}
}

async function handleNewTransaction(transaction) {
const { sender_pub_id, receiver_pub_id, amount, timestamp, signature } = transaction;
const message = `${sender_pub_id}${receiver_pub_id}${amount}${timestamp}`;

try {
const isSignatureValid = verifySignature(message, signature, sender_pub_id);

if (isSignatureValid) {
await Mempool.create(transaction);
distributeTransactionToMiner(transaction);
} else {
console.log('Invalid transaction detected.');
}
} catch (err) {
console.error('Error handling new transaction:', err);
}
}

async function distributeTransactionToMiner(transaction) {
const minerIds = Object.keys(connectedMiners);

if (minerIds.length > 0) {
const minerIndex = Math.floor(Math.random() * minerIds.length);
const minerId = minerIds[minerIndex];
wss.clients.forEach((wsClient) => {
if (wsClient.readyState === WebSocket.OPEN && wsClient.minerId === minerId) {
wsClient.send(JSON.stringify({
type: 'NEW_TRANSACTION',
payload: transaction,
}));
}
});

console.log(`Transaction ${transaction.signature} sent to miner ${minerId}`);
} else {
console.log('No miners are currently connected.');
}
}

async function updateMinerStatus(minerId, isConnected) {
if (isConnected) {
connectedMiners[minerId] = true;
} else {
delete connectedMiners[minerId];
}

await Miner.findOneAndUpdate(
{ minerId },
{ isConnected },
{ upsert: true, new: true }
);
}

async function handleNewBlock(blockData) {
try {
const { previousHash, transactions, nonce, timestamp, hash } = blockData;
const lastBlock = await Block.findOne().sort({ _id: -1 });
if (lastBlock && lastBlock.hash !== previousHash) {
console.log('Invalid block: Previous hash does not match');
return;
}

// Verify each transaction in the block
for (const tx of transactions) {
const { sender_pub_id, receiver_pub_id, amount, timestamp, signature } = tx;
const message = `${sender_pub_id}${receiver_pub_id}${amount}${timestamp}`;
const isSignatureValid = verifySignature(message, signature, sender_pub_id);

if (!isSignatureValid) {
console.log(`Invalid transaction in block: ${signature}`);
return;
}

// If valid, call /maketxn to complete the transaction
await axios.post('http://localhost:3002/maketxn', {
amount,
sender_pub_id,
receiver_pub_id,
signature,
timestamp,
});
}

await Block.create(blockData);

// Remove transactions from the mempool after they are added to a block
for (const tx of transactions) {
await Mempool.deleteOne({ signature: tx.signature });
}

console.log('New block added to the blockchain:', blockData);

// Broadcast the new block to all connected clients
wss.clients.forEach((wsClient) => {
if (wsClient.readyState === WebSocket.OPEN) {
wsClient.send(JSON.stringify({
type: 'NEW_BLOCK_BROADCAST',
payload: blockData,
}));
}
});
} catch (err) {
console.error('Error handling new block:', err);
}
}

app.post('/api/submit-transaction', async (req, res) => {
const { signature, sender_pub_id, receiver_pub_id, amount, timestamp } = req.body;

if (!signature || !sender_pub_id || !receiver_pub_id || !amount || !timestamp) {
return res.status(400).json({ msg: 'Missing required fields' });
}

const transaction = { signature, sender_pub_id, receiver_pub_id, amount, timestamp };
try {
await handleNewTransaction(transaction);
res.status(200).json({ msg: 'Transaction received and added to mempool' });
} catch (err) {
res.status(500).json({ msg: 'Internal server error' });
}
});

wss.on('connection', async (ws) => {
const minerId = generateMinerId();
ws.minerId = minerId;
await updateMinerStatus(minerId, true);

console.log(`Miner ${minerId} connected`);

// Send the blockchain immediately after connection
try {
const blockchain = await Block.find().sort({ _id: 1 });
ws.send(JSON.stringify({
type: 'BLOCKCHAIN',
payload: blockchain,
version: '1.0.0',
}));
console.log(`Blockchain sent to miner ${minerId}`);
} catch (err) {
console.error('Error sending blockchain:', err);
}

ws.on('message', async (message) => {
const parsedMessage = JSON.parse(message);
const { type, payload } = parsedMessage;

if (type === 'NEW_BLOCK') {
await handleNewBlock(payload);
}
});

ws.on('close', async () => {
await updateMinerStatus(minerId, false);
});
});

httpServer.listen(3001, () => {
console.log('HTTP server running on http://localhost:3001');
console.log('WebSocket server running on ws://localhost:3001');
});
12 changes: 12 additions & 0 deletions rfc-1/CentralServer/model/block.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const mongoose = require('mongoose');

const blockSchema = new mongoose.Schema({
index: Number,
timestamp: Date,
transactions: Array,
previousHash: String,
hash: String,
nonce: Number
});

module.exports = mongoose.model('Block', blockSchema);
13 changes: 13 additions & 0 deletions rfc-1/CentralServer/model/mempool.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const mongoose = require('mongoose');

const mempoolSchema = new mongoose.Schema({
signature: { type: String, required: true, unique: true },
sender_pub_id: { type: String, required: true },
receiver_pub_id: { type: String, required: true },
amount: { type: Number, required: true },
timestamp: { type: Date, default: Date.now, required: true },
});

const Mempool = mongoose.model('Mempool', mempoolSchema);

module.exports = Mempool;
9 changes: 9 additions & 0 deletions rfc-1/CentralServer/model/miner.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const mongoose = require('mongoose');

const minerSchema = new mongoose.Schema({
minerId: String,
connected: Boolean,
lastSeen: Date
});

module.exports = mongoose.model('Miner', minerSchema);
Loading