Last active
March 14, 2018 00:12
-
-
Save tgoldenberg/db1a37326bc0ecd6b27d3248f49b62e3 to your computer and use it in GitHub Desktop.
Node server that broadcasts messages and connects nodes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* package.json | |
{ | |
"name": "nodecoin", | |
"version": "1.0.0", | |
"description": "Implementation of Bitcoin / cryptocurrency using NodeJS", | |
"main": "index.js", | |
"dependencies": { | |
"body-parser": "^1.18.2", | |
"dotenv": "^5.0.0", | |
"express": "^4.16.2", | |
"pusher": "^1.5.1" | |
}, | |
"scripts": { | |
"start": "node index.js" | |
} | |
} | |
*/ | |
/* index.js */ | |
const Pusher = require('pusher'); | |
const express = require('express'); | |
const bodyParser = require('body-parser'); | |
require('dotenv').config(); // initialize process.env variables | |
const app = express(); | |
app.use(bodyParser.json()); | |
app.use(bodyParser.urlencoded({ extended: false })); | |
const options = { | |
appId: process.env.PUSHER_APP_ID, | |
key: process.env.PUSHER_APP_KEY, | |
secret: process.env.PUSHER_SECRET, | |
cluster: 'us2', | |
encrypted: true | |
}; | |
const socket = new Pusher(options); | |
// keep track of IP addresses connected to network | |
app.post('/pusher/auth', function(req, res) { | |
const auth = socket.authenticate( | |
req.body.socket_id, | |
req.body.channel_name, | |
{ user_id: req.body.ip_addr, port: parseInt(req.body.port) } | |
); | |
res.send(auth); | |
}); | |
// broadcast new transaction | |
app.post('/transactions/new', function(req, res) { | |
socket.trigger('presence-node-coin', 'transaction:new', { tx: req.body.tx }); | |
res.status(200).send({ sent: true }); | |
}); | |
// broadcast new block | |
app.post('/blocks/new', function(req, res) { | |
socket.trigger('presence-node-coin', 'block:new', { block: req.body.block }); | |
res.status(200).send({ sent: true }); | |
}); | |
app.listen(process.env.PORT || 3001, function() { | |
console.log('> Server listening on port: ', process.env.PORT); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment