zgo/backend/app.js

541 lines
14 KiB
JavaScript
Raw Normal View History

2021-10-15 19:14:49 +00:00
const express = require('express');
const app = express();
2021-11-08 19:09:16 +00:00
const bodyparser = require('body-parser');
2021-11-09 18:39:16 +00:00
const cors = require('cors');
2021-11-11 15:18:38 +00:00
const crypto = require('crypto');
2021-10-15 19:14:49 +00:00
const postmodel = require('./models/post');
const usermodel = require('./models/user');
2021-10-20 20:51:14 +00:00
const ownermodel = require('./models/owner');
const itemmodel = require('./models/item');
const ordermodel = require('./models/order');
2021-11-02 21:13:24 +00:00
const pricemodel = require('./models/price');
const txmodel = require('./models/tx');
2021-11-18 22:38:25 +00:00
const zecTxModel = require('./models/zectxs.js');
2021-10-15 19:14:49 +00:00
const mongoose = require('mongoose');
const stdrpc = require('stdrpc');
const CoinGecko = require('coingecko-api');
2021-11-11 15:18:38 +00:00
var URLSafeBase64 = require('urlsafe-base64');
var Buffer = require('buffer/').Buffer;
2021-10-15 19:14:49 +00:00
var db = require('./config/db');
2021-11-04 18:10:56 +00:00
mongoose.connect('mongodb://'+db.user+':'+db.password+'@'+db.server+'/'+db.database).then(() => {
console.log("connecting-- ", db.database);
2021-10-15 19:14:49 +00:00
}).catch(() => {
console.log("connection failed!");
});
var fullnode = require('./config/fullnode');
const rpc = stdrpc({
url: fullnode.url,
username: fullnode.username,
password: fullnode.password
});
2021-11-04 12:49:09 +00:00
var async = require('async');
const CoinGeckoClient = new CoinGecko();
2021-11-02 21:13:24 +00:00
var intervalObject = setInterval( function() {
CoinGeckoClient.simple.price({
ids: ['zcash'],
vs_currencies: ['usd', 'gbp', 'eur', 'cad', 'aud']
}).then((data) => {
pricemodel.findOneAndUpdate({currency: 'usd'}, { price: data.data.zcash.usd, timestamp: Date.now()}, {new:true, upsert:true}, function(err,docs) {
if(err) {
console.log(err);
}
});
pricemodel.findOneAndUpdate({currency: 'gbp'}, { price: data.data.zcash.gbp, timestamp: Date.now()}, {new:true, upsert:true}, function(err,docs) {
if(err) {
console.log(err);
}
});
pricemodel.findOneAndUpdate({currency: 'eur'}, { price: data.data.zcash.eur, timestamp: Date.now()}, {new:true, upsert:true}, function(err,docs) {
if(err) {
console.log(err);
}
});
pricemodel.findOneAndUpdate({currency: 'cad'}, { price: data.data.zcash.cad, timestamp: Date.now()}, {new:true, upsert:true}, function(err,docs) {
if(err) {
console.log(err);
}
});
pricemodel.findOneAndUpdate({currency: 'aud'}, { price: data.data.zcash.aud, timestamp: Date.now()}, {new:true, upsert:true}, function(err,docs) {
if(err) {
console.log(err);
}
});
}).catch((err) => {
console.log(err);
});
}, 90000);
2021-11-04 12:49:09 +00:00
function hexToString(hexString) {
var str = '';
for (var n=0; n < hexString.length; n +=2) {
str += String.fromCharCode(parseInt(hexString.substr(n, 2), 16));
}
return str;
}
2021-11-11 15:18:38 +00:00
function sendPin(pin, address) {
//var memo = URLSafeBase64.encode(Buffer.from('ZGO pin: '.concat(pin)));
var memo = Buffer.from('ZGO pin: '.concat(pin)).toString('hex');
//console.log(typeof(memo));
var amounts = [
{
address: address,
amount: 0.00000001,
memo: memo
}
];
rpc.z_sendmany(fullnode.addr, amounts).catch((err) => {
console.log('Sendmany', err);
});
}
2021-11-04 12:49:09 +00:00
var blockInterval = setInterval( function() {
console.log('Node periodic Zcash scan');
rpc.z_listreceivedbyaddress(fullnode.addr, 1).then(txs => {
2021-11-04 12:49:09 +00:00
var re = /.*ZGO::(.*)\sReply-To:\s(z\w+)/;
async.each (txs, function(txData, callback) {
var memo = hexToString(txData.memo).replace(/\0/g, '');
2021-11-22 20:37:45 +00:00
if (!txData.change) {
zecTxModel.updateOne({txid: txData.txid}, { txid: txData.txid, confirmations: txData.confirmations, amount:txData.amount, memo: memo}, {new:true, upsert:true}, function(err,docs) {
if (err) {
console.log(err);
}
});
}
if (re.test(memo) && txData.confirmations < 100) {
2021-11-04 12:49:09 +00:00
//console.log('Processing tx:', memo);
var match = re.exec(memo);
if (match != null) {
var address = match[2];
var session = match[1];
var blocktime = txData.blocktime;
2021-11-11 15:18:38 +00:00
var amount = txData.amount;
var expiration = blocktime;
2021-11-04 12:49:09 +00:00
//console.log(' ', session, blocktime);
2021-11-18 22:38:25 +00:00
txmodel.updateOne({txid: txData.txid}, { txid: txData.txid, address: address, session: session, confirmations: txData.confirmations, amount:txData.amount, memo: memo}, {new:true, upsert:true}, function(err,docs) {
if (err) {
console.log(err);
}
});
if (txData.confirmations >= 6 ) {
usermodel.findOne({address: address, session: session, blocktime: blocktime}).then(function(doc){
2021-11-18 22:38:25 +00:00
if (doc == null){
2021-11-11 15:18:38 +00:00
console.log('User not found', session, blocktime, amount);
if (amount >= 0.001 && amount < 0.005){
expiration = blocktime + 3600;
} else if (amount >= 0.005){
expiration = blocktime + 24*3600;
}
console.log('exp', expiration);
const n = crypto.randomInt(0, 10000000);
const pin = n.toString().padStart(6, '0');
sendPin(pin, address);
var user = new usermodel({
address: address,
session: session,
2021-11-11 15:18:38 +00:00
blocktime: blocktime,
expiration: expiration,
pin: pin,
validated: false
});
user.save(function(error) {
if (error) {
console.log(error);
}
console.log('User saved');
});
}
});
ownermodel.findOne({address: address}).then(function (oDoc) {
2021-11-18 22:38:25 +00:00
if (oDoc == null) {
console.log('Owner not found', session);
var owner = new ownermodel({
address: address,
name: 'Z-Go-'.concat(address.substring(0,5))
});
owner.save().then(function(err) {
if (err) {
console.log(err);
}
console.log('Owner saved!');
}).catch(() => {
console.log('Owner exists');
});
}
}).catch((err) => {
console.log(err);
});
}
2021-11-04 12:49:09 +00:00
}
}
}, function (err) {
if (err) {
console.log(err);
}
console.log('Txs synced');
});
});
2021-11-22 20:37:45 +00:00
}, 75000);
2021-11-04 12:49:09 +00:00
2021-11-09 18:39:16 +00:00
app.use(cors());
app.options('*', cors());
2021-10-15 19:14:49 +00:00
app.use(bodyparser.json());
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PATCH, DELETE, OPTIONS");
next();
});
2021-11-09 18:39:16 +00:00
app.use((req, res, next) => {
if (req.headers.authorization !== 'Le2adeic8Thah4Aeng4daem6i' ) {
return res.status(401).send('Authorization required.');
} else {
next();
}
});
2021-10-15 19:14:49 +00:00
2021-11-11 15:18:38 +00:00
app.get('/api/test', (req, res, next) => {
sendPin('12345678', 'zs1w6nkameazc5gujm69350syl5w8tgvyaphums3pw8eytzy5ym08x7dvskmykkatmwrucmgv3er8e');
res.status(200).send('Endpoint triggered');
});
2021-10-15 19:14:49 +00:00
app.get('/api/users', (req, res, next) => {
2021-10-20 20:51:14 +00:00
console.log('Get: /api/users');
2021-10-15 19:14:49 +00:00
usermodel.find({'address': req.query.address, 'session': req.query.session}).
then((documents) => {
2021-11-04 12:49:09 +00:00
if (documents != null) {
res.status(200).json({
message: 'Users found successfully',
users: documents
});
} else {
res.status(204).json({
message: 'User not found',
users: null
});
}
2021-10-15 19:14:49 +00:00
});
});
app.get('/api/pending', (req, res, next) => {
console.log('Get: /api/pending', req.query.session);
txmodel.find({'session': req.query.session, 'confirmations': {$lt: 10}}).
then((documents) => {
if (documents.length > 0) {
//console.log('pending', documents);
res.status(200).json({
message: 'Found pending txs',
txs: documents
});
} else {
//console.log('pending not found', documents);
res.status(204).json({
message: 'No txs found',
txs: null
});
}
});
});
2021-10-15 19:14:49 +00:00
app.get('/api/getuser', (req, res, next) => {
2021-10-20 20:51:14 +00:00
console.log('Get: /api/getuser/', req.query.session);
2021-11-04 12:49:09 +00:00
var today = new Date().getTime() / 1000;
2021-11-11 15:18:38 +00:00
usermodel.find({'session': req.query.session, 'expiration': { $gt: today }}).
2021-10-15 19:14:49 +00:00
then((documents) => {
if(documents.length > 0){
//console.log(documents);
2021-11-04 12:49:09 +00:00
console.log(' found user');
2021-10-15 19:14:49 +00:00
res.status(200).json({
message: 'User found!',
user: documents
});
} else {
2021-11-04 12:49:09 +00:00
console.log(' did not find user');
2021-10-15 19:14:49 +00:00
res.status(204).json({
message: 'User not found!',
user: null
});
}
});
});
app.get('/api/blockheight', (req, res, next) => {
2021-10-20 20:51:14 +00:00
console.log('Get: /api/blockheight');
2021-10-15 19:14:49 +00:00
rpc.getblock("-1", 1).then(block => {
res.status(200).json({
message: 'Found block',
height: block.height
});
});
});
app.get('/api/txs', (req, res, next) => {
2021-10-20 20:51:14 +00:00
console.log('Get: /api/txs');
2021-11-04 12:49:09 +00:00
rpc.z_listreceivedbyaddress(fullnode.addr, 10).then(txs => {
2021-10-15 19:14:49 +00:00
res.status(200).json({
message: 'Transactions found',
txs: txs
});
});
});
app.get('/api/getaddr', (req, res, next) => {
2021-10-20 20:51:14 +00:00
console.log('Get: /api/getaddr');
2021-10-15 19:14:49 +00:00
res.status(200).json({
message: 'Sending address',
addr: fullnode.addr
});
});
2021-10-20 20:51:14 +00:00
app.get('/api/getowner', (req, res, next) => {
console.log('Get: /api/getowner');
ownermodel.find({'address': req.query.address}).then((documents) => {
if(documents.length > 0){
//console.log(documents);
res.status(200).json({
message: 'Owner found!',
owner: documents
});
} else {
res.status(204).json({
message: 'Owner not found!',
owner: null
});
}
});
});
app.post('/api/addowner', (req, res, next) => {
console.log('Post: /api/addowner');
const owner = new ownermodel(req.body);
owner.save();
res.status(201).json({
message: 'Owner added successfully'
});
});
2021-11-11 15:18:38 +00:00
app.post('/api/validateuser', (req, res, next) => {
console.log('Post: /api/validateuser');
usermodel.findByIdAndUpdate(req.body.user._id, req.body.user,
function(err, docs) {
if (err) {
console.log(err);
} else {
res.status(201).json({
message: 'User Validated',
user: docs
});
}
});
});
2021-10-28 20:34:48 +00:00
app.post('/api/updateowner', (req, res, next) => {
console.log('Post: /api/updateowner');
ownermodel.findByIdAndUpdate(req.body.owner._id, req.body.owner,
function(err, docs) {
if (err) {
console.log(err);
} else {
2021-11-22 20:37:45 +00:00
console.log(docs);
2021-10-28 20:34:48 +00:00
res.status(201).json({
message: 'Owner updated',
owner: docs
});
}
});
2021-10-20 20:51:14 +00:00
});
2021-10-21 21:23:33 +00:00
app.get('/api/getitems', (req, res, next) => {
console.log('Get: /api/getitems');
//console.log('getitems', req.query.address);
if (req.query.address.length > 0 ) {
const items = itemmodel.find({user: req.query.address}).then((documents) => {
if(documents.length > 0){
//console.log(documents);
res.status(200).json({
message: 'items found!',
items: documents
});
} else {
res.status(204).json({
message: 'items not found!',
items: []
});
}
});
} else {
res.status(204).json({
message: 'no address',
items: []
});
}
2021-10-21 21:23:33 +00:00
});
app.post('/api/item', (req, res, next) => {
2021-10-26 20:07:10 +00:00
console.log('Post: /api/item', req.body.item);
if ( req.body.item._id == null ) {
2021-10-26 15:09:34 +00:00
const item = new itemmodel(req.body.item);
item.save();
res.status(201).json({
message: 'Item added'
});
} else {
console.log('Editing', req.body.item._id);
itemmodel.findByIdAndUpdate(req.body.item._id, {'name': req.body.item.name, 'description': req.body.item.description, 'cost': req.body.item.cost},
function(err, docs) {
if (err) {
console.log(err);
} else {
res.status(201).json({
message: 'Item updated'
});
}
});
}
});
2021-10-26 18:34:52 +00:00
app.delete('/api/item/:id', (req, res, next) => {
console.log('delete endpoint', req.params.id);
itemmodel.findByIdAndDelete(req.params.id, function (err, docs) {
if (err) {
console.log(err);
} else {
res.status(200).json({
message: 'Item deleted'
});
}
});
});
app.get('/api/price', (req, res, next) => {
console.log('Get /api/price');
2021-11-22 20:37:45 +00:00
const price = pricemodel.findOne({currency: req.query.currency}).then((document) => {
2021-11-02 21:13:24 +00:00
if (document != null) {
res.status(200).json({
message: 'price found!',
2021-11-02 21:13:24 +00:00
price: document
});
2021-11-02 21:13:24 +00:00
} else {
res.status(204).json({
message: 'no price found!',
order: null
});
}
});
});
app.get('/api/allorders', (req, res, next) => {
console.log('Get /api/allorders');
if (req.query.address.length > 0) {
const orders = ordermodel.find({address: req.query.address, closed: true}).then((documents) => {
if (documents != null) {
res.status(200).json({
message: 'orders found!',
orders: documents
});
} else {
res.status(204).json({
message: 'no orders found',
orders: null
});
}
});
}
});
app.get('/api/order', (req, res, next) => {
console.log('Get /api/order');
if (req.query.session.length > 0) {
const order = ordermodel.findOne({session: req.query.session, closed: false}).then((documents) => {
if (documents != null) {
2021-10-27 12:59:43 +00:00
console.log(documents);
res.status(200).json({
message: 'order found!',
2021-10-27 12:59:43 +00:00
order: documents
});
} else {
res.status(204).json({
message: 'no order found!',
order: null
});
}
});
} else {
res.status(204).json({
message: 'no session received',
order: null
});
}
});
2021-10-27 12:59:43 +00:00
app.post('/api/order', (req, res, next) => {
console.log('Post /api/order', req.body);
2021-11-02 15:35:22 +00:00
if(req.body.order._id == null) {
const order = new ordermodel(req.body.order);
order.save();
res.status(200).json({
message: 'Order added',
order: order
});
} else {
ordermodel.findByIdAndUpdate(req.body.order._id, {
address: req.body.order.address,
session: req.body.order.session,
2021-11-05 14:30:35 +00:00
price: req.body.order.price,
total: req.body.order.total,
2021-11-22 20:37:45 +00:00
currency: req.body.order.currency,
2021-11-05 14:30:35 +00:00
totalZec: req.body.order.totalZec,
2021-11-02 15:35:22 +00:00
closed: req.body.order.closed
}, function(err, docs) {
if(err) {
console.log(err);
} else {
res.status(200).json({
message: 'Order updated'
});
}
});
}
});
app.post('/api/lineitem', (req, res, next) => {
console.log('Post /api/lineitem');
ordermodel.findByIdAndUpdate(req.body.order_id, { $push: {lines: req.body.line}}, function(err,docs) {
if (err) {
console.log(err);
} else {
res.status(200).json({
message: 'Item added to order'
});
}
});
});
app.delete('/api/order/:id', (req, res, next) => {
console.log('delete order endpoint', req.params.id);
ordermodel.findByIdAndDelete(req.params.id, function (err, docs) {
if (err) {
console.log(err);
} else {
console.log(docs);
res.status(200).json({
message: 'Order deleted'
});
}
2021-10-27 12:59:43 +00:00
});
});
2021-10-15 19:14:49 +00:00
module.exports = app;