-
Notifications
You must be signed in to change notification settings - Fork 58
created BE and FE for bitcoin blockchain simulator. #13
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
node_modules | ||
.DS_Store | ||
.env |
Large diffs are not rendered by default.
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
{ | ||
"name": "rfc-1", | ||
"version": "0.1.0", | ||
"private": true, | ||
"dependencies": { | ||
"@testing-library/jest-dom": "^5.16.5", | ||
"@testing-library/react": "^13.4.0", | ||
"@testing-library/user-event": "^13.5.0", | ||
"react": "^18.2.0", | ||
"react-dom": "^18.2.0", | ||
"react-icons": "^4.8.0", | ||
"react-scripts": "5.0.1", | ||
"web-vitals": "^2.1.4", | ||
"ws": "^8.18.0" | ||
}, | ||
"scripts": { | ||
"start": "react-scripts start", | ||
"build": "react-scripts build", | ||
"test": "react-scripts test", | ||
"eject": "react-scripts eject", | ||
"server": "node server/start.js", | ||
"dev": "concurrently \"npm run server\" \"npm start\"" | ||
}, | ||
"eslintConfig": { | ||
"extends": [ | ||
"react-app", | ||
"react-app/jest" | ||
] | ||
}, | ||
"browserslist": { | ||
"production": [ | ||
">0.2%", | ||
"not dead", | ||
"not op_mini all" | ||
], | ||
"development": [ | ||
"last 1 chrome version", | ||
"last 1 firefox version", | ||
"last 1 safari version" | ||
] | ||
}, | ||
"devDependencies": { | ||
"concurrently": "^8.2.2" | ||
} | ||
} | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
<!DOCTYPE html> | ||
<html lang="en"> | ||
<head> | ||
<meta charset="utf-8" /> | ||
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> | ||
<meta name="viewport" content="width=device-width, initial-scale=1" /> | ||
<meta name="theme-color" content="#000000" /> | ||
<meta | ||
name="description" | ||
content="Web site created using create-react-app" | ||
/> | ||
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> | ||
<!-- | ||
manifest.json provides metadata used when your web app is installed on a | ||
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/ | ||
--> | ||
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> | ||
<!-- | ||
Notice the use of %PUBLIC_URL% in the tags above. | ||
It will be replaced with the URL of the `public` folder during the build. | ||
Only files inside the `public` folder can be referenced from the HTML. | ||
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will | ||
work correctly both with client-side routing and a non-root public URL. | ||
Learn how to configure a non-root public URL by running `npm run build`. | ||
--> | ||
<title>React App</title> | ||
</head> | ||
<body> | ||
<noscript>You need to enable JavaScript to run this app.</noscript> | ||
<div id="root"></div> | ||
<!-- | ||
This HTML file is a template. | ||
If you open it directly in the browser, you will see an empty page. | ||
You can add webfonts, meta tags, or analytics to this file. | ||
The build step will place the bundled scripts into the <body> tag. | ||
To begin the development, run `npm start` or `yarn start`. | ||
To create a production bundle, use `npm run build` or `yarn build`. | ||
--> | ||
</body> | ||
</html> |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
{ | ||
"short_name": "React App", | ||
"name": "Create React App Sample", | ||
"icons": [ | ||
{ | ||
"src": "favicon.ico", | ||
"sizes": "64x64 32x32 24x24 16x16", | ||
"type": "image/x-icon" | ||
}, | ||
{ | ||
"src": "logo192.png", | ||
"type": "image/png", | ||
"sizes": "192x192" | ||
}, | ||
{ | ||
"src": "logo512.png", | ||
"type": "image/png", | ||
"sizes": "512x512" | ||
} | ||
], | ||
"start_url": ".", | ||
"display": "standalone", | ||
"theme_color": "#000000", | ||
"background_color": "#ffffff" | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# https://www.robotstxt.org/robotstxt.html | ||
User-agent: * | ||
Disallow: |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,139 @@ | ||
const WebSocket = require('ws'); | ||
const crypto = require('crypto'); | ||
|
||
const wss = new WebSocket.Server({ port: 8080 }); | ||
|
||
let blockchain = []; | ||
let pendingTransactions = []; | ||
const clients = new Set(); | ||
const miners = new Set(); | ||
|
||
class Block { | ||
constructor(index, previousHash, timestamp, transactions, nonce = 0) { | ||
this.index = index; | ||
this.previousHash = previousHash; | ||
this.timestamp = timestamp; | ||
this.transactions = transactions; | ||
this.nonce = nonce; | ||
this.hash = this.calculateHash(); | ||
} | ||
|
||
calculateHash() { | ||
return crypto.createHash('sha256').update( | ||
this.index + | ||
this.previousHash + | ||
this.timestamp + | ||
JSON.stringify(this.transactions) + | ||
this.nonce | ||
).digest('hex'); | ||
} | ||
} | ||
|
||
function createGenesisBlock() { | ||
return new Block(0, "0", Date.now(), "Genesis block"); | ||
} | ||
|
||
blockchain.push(createGenesisBlock()); | ||
|
||
function broadcastToAll(message) { | ||
const messageString = JSON.stringify(message); | ||
clients.forEach(client => { | ||
if (client.readyState === WebSocket.OPEN) { | ||
client.send(messageString); | ||
} | ||
}); | ||
miners.forEach(miner => { | ||
if (miner.readyState === WebSocket.OPEN) { | ||
miner.send(messageString); | ||
} | ||
}); | ||
console.log(`[SERVER] Broadcasted: ${message.type}`); | ||
} | ||
|
||
wss.on('connection', (ws) => { | ||
console.log('[SERVER] New connection established'); | ||
|
||
ws.on('message', (message) => { | ||
try { | ||
const data = JSON.parse(message); | ||
console.log(`[SERVER] Received message: ${data.type}`); | ||
|
||
switch (data.type) { | ||
case 'REGISTER': | ||
if (data.role === 'client') { | ||
clients.add(ws); | ||
console.log('[SERVER] New client registered'); | ||
} else if (data.role === 'miner') { | ||
miners.add(ws); | ||
console.log('[SERVER] New miner registered'); | ||
} | ||
console.log(`[SERVER] Sending blockchain with ${blockchain.length} blocks`); | ||
ws.send(JSON.stringify({ | ||
type: 'BLOCKCHAIN', | ||
chain: blockchain.map(block => ({ | ||
index: block.index, | ||
previousHash: block.previousHash, | ||
timestamp: block.timestamp, | ||
transactions: block.transactions, | ||
nonce: block.nonce, | ||
hash: block.hash | ||
})) | ||
})); | ||
break; | ||
|
||
case 'NEW_TRANSACTION': | ||
console.log(`[SERVER] New transaction received: ${JSON.stringify(data.transaction)}`); | ||
pendingTransactions.push(data.transaction); | ||
broadcastToAll({ type: 'PENDING_TRANSACTION', transaction: data.transaction }); | ||
break; | ||
|
||
case 'MINED_BLOCK': | ||
console.log(`[SERVER] Received mined block: ${data.block.hash}`); | ||
const newBlock = new Block( | ||
data.block.index, | ||
data.block.previousHash, | ||
data.block.timestamp, | ||
data.block.transactions, | ||
data.block.nonce | ||
); | ||
console.log(`[SERVER] Validating block: ${newBlock.hash}`); | ||
console.log(`[SERVER] Block index: ${newBlock.index}, Previous hash: ${newBlock.previousHash}`); | ||
console.log(`[SERVER] Block timestamp: ${newBlock.timestamp}, Nonce: ${newBlock.nonce}`); | ||
console.log(`[SERVER] Number of transactions: ${newBlock.transactions.length}`); | ||
|
||
if (newBlock.hash.startsWith('0000') && newBlock.calculateHash() === data.block.hash) { | ||
if (newBlock.index === blockchain.length && newBlock.previousHash === blockchain[blockchain.length - 1].hash) { | ||
blockchain.push(newBlock); | ||
pendingTransactions = pendingTransactions.filter(tx => | ||
!newBlock.transactions.some(minedTx => | ||
minedTx.fromAddress === tx.fromAddress && | ||
minedTx.toAddress === tx.toAddress && | ||
minedTx.amount === tx.amount | ||
) | ||
); | ||
console.log(`[SERVER] Valid block added to blockchain: ${newBlock.hash}`); | ||
broadcastToAll({ type: 'NEW_BLOCK', block: newBlock }); | ||
} else { | ||
console.log(`[SERVER] Block index or previous hash mismatch. Discarding block.`); | ||
} | ||
} else { | ||
console.log('[SERVER] Invalid block hash. Discarding block.'); | ||
} | ||
break; | ||
|
||
default: | ||
console.log(`[SERVER] Unknown message type: ${data.type}`); | ||
} | ||
} catch (error) { | ||
console.error(`[SERVER] Error processing message: ${error.message}`); | ||
} | ||
}); | ||
|
||
ws.on('close', () => { | ||
clients.delete(ws); | ||
miners.delete(ws); | ||
console.log('[SERVER] Connection closed'); | ||
}); | ||
}); | ||
|
||
console.log('[SERVER] Central server started on ws://localhost:8080'); |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,120 @@ | ||
const WebSocket = require('ws'); | ||
const crypto = require('crypto'); | ||
|
||
class Block { | ||
constructor(index, previousHash, timestamp, transactions, nonce = 0) { | ||
this.index = index; | ||
this.previousHash = previousHash; | ||
this.timestamp = timestamp; | ||
this.transactions = transactions; | ||
this.nonce = nonce; | ||
this.hash = this.calculateHash(); | ||
} | ||
|
||
calculateHash() { | ||
return crypto.createHash('sha256').update( | ||
this.index + | ||
this.previousHash + | ||
this.timestamp + | ||
JSON.stringify(this.transactions) + | ||
this.nonce | ||
).digest('hex'); | ||
} | ||
|
||
mineBlock(difficulty) { | ||
while (this.hash.substring(0, difficulty) !== Array(difficulty + 1).join("0")) { | ||
this.nonce++; | ||
this.hash = this.calculateHash(); | ||
} | ||
console.log(`[MINER] Block mined: ${this.hash}`); | ||
} | ||
} | ||
|
||
class Miner { | ||
constructor() { | ||
this.blockchain = []; | ||
this.pendingTransactions = []; | ||
this.difficulty = 4; | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. keeping a fixed difficulty number will make managing average block-times impossible There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The difficulty should not be fixed |
||
this.ws = new WebSocket('ws://localhost:8080'); | ||
|
||
this.ws.on('open', () => { | ||
console.log('[MINER] Connected to central server'); | ||
this.ws.send(JSON.stringify({ type: 'REGISTER', role: 'miner' })); | ||
}); | ||
|
||
this.ws.on('message', (data) => { | ||
try { | ||
const message = JSON.parse(data); | ||
console.log(`[MINER] Received message: ${message.type}`); | ||
|
||
switch (message.type) { | ||
case 'BLOCKCHAIN': | ||
this.blockchain = message.chain.map(blockData => new Block( | ||
blockData.index, | ||
blockData.previousHash, | ||
blockData.timestamp, | ||
blockData.transactions, | ||
blockData.nonce | ||
)); | ||
console.log(`[MINER] Received blockchain with ${this.blockchain.length} blocks`); | ||
break; | ||
case 'PENDING_TRANSACTION': | ||
console.log(`[MINER] Received new pending transaction: ${JSON.stringify(message.transaction)}`); | ||
this.pendingTransactions.push(message.transaction); | ||
this.mineBlock(); | ||
break; | ||
case 'NEW_BLOCK': | ||
console.log(`[MINER] Received new block from another miner: ${message.block.hash}`); | ||
this.blockchain.push(new Block( | ||
message.block.index, | ||
message.block.previousHash, | ||
message.block.timestamp, | ||
message.block.transactions, | ||
message.block.nonce | ||
)); | ||
this.pendingTransactions = this.pendingTransactions.filter(tx => | ||
!message.block.transactions.some(minedTx => | ||
minedTx.fromAddress === tx.fromAddress && | ||
minedTx.toAddress === tx.toAddress && | ||
minedTx.amount === tx.amount | ||
) | ||
); | ||
break; | ||
} | ||
} catch (error) { | ||
console.error(`[MINER] Error processing message: ${error.message}`); | ||
} | ||
}); | ||
} | ||
|
||
mineBlock() { | ||
if (this.pendingTransactions.length === 0) { | ||
console.log('[MINER] No pending transactions to mine'); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. A blockchain always , mines a block even if there are no txns to mine |
||
return; | ||
} | ||
|
||
console.log('[MINER] Starting to mine a new block'); | ||
const previousBlock = this.blockchain.length > 0 ? this.blockchain[this.blockchain.length - 1] : null; | ||
const newBlock = new Block( | ||
this.blockchain.length, | ||
previousBlock ? previousBlock.hash : "0", | ||
Date.now(), | ||
this.pendingTransactions | ||
); | ||
|
||
console.log(`[MINER] Mining block with ${this.pendingTransactions.length} transactions`); | ||
newBlock.mineBlock(this.difficulty); | ||
console.log(`[MINER] Block successfully mined: ${newBlock.hash}`); | ||
|
||
this.ws.send(JSON.stringify({ | ||
type: 'MINED_BLOCK', | ||
block: newBlock | ||
})); | ||
console.log('[MINER] Sent mined block to central server'); | ||
|
||
this.pendingTransactions = []; | ||
} | ||
} | ||
|
||
const miner = new Miner(); | ||
console.log('[MINER] Miner started'); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Make sure to handle and verify signature while accepting TXNS