Skip to content
Snippets Groups Projects
Commit 04c265ac authored by Otto Zaiser's avatar Otto Zaiser
Browse files

Merge branch 'develop' of gitlab.bfa.ar:blockchain/tsa2 into develop

parents 5a4788be c24d7316
No related branches found
No related tags found
No related merge requests found
import 'dotenv/config' import 'dotenv/config'
import Web3 from 'web3' import Web3 from 'web3'
import express from 'express' import express from 'express'
import cors from 'cors' import cors from 'cors'
import bodyParser from 'body-parser' import bodyParser from 'body-parser'
import basicAuth from 'express-basic-auth' import basicAuth from 'express-basic-auth'
import Stamper from './StamperWrapper' import Stamper from './StamperWrapper'
import fs from 'fs' import fs from 'fs'
/***************************************************/ /***************************************************/
// Conexión al provider // Conexión al provider
/***************************************************/ /***************************************************/
const providerHost = process.env.GETH_HOST || 'http://localhost:7545' const providerHost = process.env.GETH_HOST || 'http://localhost:8545'
// const providerHost = process.env.GETH_HOST || 'http://localhost:8545' const accountIsSet = process.env.GETH_ACCOUNT_JSON || false
const accountIsSet = process.env.GETH_ACCOUNT_JSON || false
var web3 = web3 var web3 = web3
if (typeof web3 !== 'undefined') { if (typeof web3 !== 'undefined') {
console.log('Cargando web3 provider desde el entorno') console.log('Cargando web3 provider desde el entorno')
// Use Mist/MetaMask's provider // Use Mist/MetaMask's provider
...@@ -26,41 +25,41 @@ if (typeof web3 !== 'undefined') { ...@@ -26,41 +25,41 @@ if (typeof web3 !== 'undefined') {
setupWeb3() setupWeb3()
} }
let contractAbi; let contractAbi;
let contractAddress; let contractAddress;
let walletAccount; let walletAccount;
async function setupWeb3() { async function setupWeb3() {
try { try {
let netIsListening = await web3.eth.net.isListening() let netIsListening = await web3.eth.net.isListening()
let netId = await web3.eth.net.getId() let netId = await web3.eth.net.getId()
if (accountIsSet) { if (accountIsSet) {
let rawKeyJsonV3 = fs.readFileSync(process.env.GETH_ACCOUNT_JSON) let rawKeyJsonV3 = fs.readFileSync(process.env.GETH_ACCOUNT_JSON)
let keyJsonV3 = JSON.parse(rawKeyJsonV3) let keyJsonV3 = JSON.parse(rawKeyJsonV3)
let key = web3.eth.accounts.decrypt(keyJsonV3, process.env.GETH_ACCOUNT_PASSWORD) let key = web3.eth.accounts.decrypt(keyJsonV3, process.env.GETH_ACCOUNT_PASSWORD)
walletAccount = web3.eth.accounts.wallet.add(key) walletAccount = web3.eth.accounts.wallet.add(key)
web3.eth.defaultAccount = (await web3.eth.getAccounts())[0] web3.eth.defaultAccount = (await web3.eth.getAccounts())[0]
} else { } else {
// se trata de utilizar una que haya abierta // se trata de utilizar una que haya abierta
web3.eth.defaultAccount = (await web3.eth.getAccounts())[0] web3.eth.defaultAccount = (await web3.eth.getAccounts())[0]
} }
/***************************************************/ /***************************************************/
// Carga de contrato // Carga de contrato
/***************************************************/ /***************************************************/
if (process.env.CONTRACT_ABI_PATH) { if (process.env.CONTRACT_ABI_PATH) {
contractAbi = require(process.env.CONTRACT_ABI_PATH) contractAbi = require(process.env.CONTRACT_ABI_PATH)
if (!process.env.CONTRACT_ADDRESS) { if ( ! process.env.CONTRACT_ADDRESS ) {
console.error('Si se especifica el path de un abi, debe proveerse un address con la env CONTRACT_ADDRESS') console.error('Si se especifica el path de un abi, debe proveerse un address con la env CONTRACT_ADDRESS')
process.exit(1) process.exit(1)
} }
contractAddress = process.env.CONTRACT_ADDRESS contractAddress = process.env.CONTRACT_ADDRESS
} else { } else {
let path = '../../contract/build/contracts/Stamper.json' let path = '../../contract/build/contracts/Stamper.json'
console.log(`Intentando cargar ${path} netId: ${netId}`) console.log(`Intentando cargar ${path} netId: ${netId}`)
let data = require(path) let data = require(path)
contractAbi = data.abi contractAbi = data.abi
contractAddress = data.networks[netId].address contractAddress = data.networks[netId].address
} }
console.log(`Conectado exitosamente: console.log(`Conectado exitosamente:
...@@ -79,17 +78,17 @@ async function setupWeb3() { ...@@ -79,17 +78,17 @@ async function setupWeb3() {
/***************************************************/ /***************************************************/
// Setup CORS y Auth // Setup CORS y Auth
/***************************************************/ /***************************************************/
const app = express() const app = express()
// USE_CORS=0 para disablear // USE_CORS=0 para disablear
const useCors = process.env.USE_CORS || 1 const useCors = process.env.USE_CORS || 1
if (useCors) app.use(cors()) if (useCors)
app.use(cors())
app.use(bodyParser.json()) app.use(bodyParser.json())
if (process.env.API_USER && process.env.API_PASS) { if ( process.env.API_USER && process.env.API_PASS ) {
var users = {} var users = {}
users[process.env.API_USER] = process.env.API_PASS users[process.env.API_USER] = process.env.API_PASS
app.use(basicAuth({ app.use(basicAuth({
users: users, users: users,
...@@ -103,14 +102,14 @@ if (process.env.API_USER && process.env.API_PASS) { ...@@ -103,14 +102,14 @@ if (process.env.API_USER && process.env.API_PASS) {
// API Endpoints // API Endpoints
/***************************************************/ /***************************************************/
app.get('/wait1block', async (req, res) => { app.get('/wait1block', async (req, res) => {
let ss = new Stamper(web3, contractAbi, contractAddress) let ss = new Stamper(web3, contractAbi, contractAddress)
try { try {
let blockno = await ss.wait1block() let blockno = await ss.wait1block()
return res.json( return res.json(
{ {
success: true, success: true,
blocknumber: blockno blocknumber: blockno
} }
) )
} catch (e) { } catch (e) {
...@@ -120,32 +119,36 @@ app.get('/wait1block', async (req, res) => { ...@@ -120,32 +119,36 @@ app.get('/wait1block', async (req, res) => {
} }
}) })
app.post('/stamp', async (req, res) => { app.post('/stamp', async (req, res) => {
let ss = new Stamper(web3, contractAbi, contractAddress) let ss = new Stamper(web3, contractAbi, contractAddress)
if (!("hashes" in req.body)) { if ( ! ("hashes" in req.body) )
{
res.status(422) res.status(422)
res.send('No se incluyó la clave hashes en el cuerpo del POST') res.send('No se incluyó la clave hashes en el cuerpo del POST')
return return
} }
let hashes = req.body.hashes let hashes = req.body.hashes
if (! Array.isArray(hashes)) { if ( ! Array.isArray(hashes))
{
res.status(422) res.status(422)
res.send('La clave hashes debe ser un array') res.send('La clave hashes debe ser un array')
return return
} }
for (let i=0; i < hashes.length; i++) { for ( let i=0; i < hashes.length; i++ )
let hash = hashes[i] {
if (! hash.startsWith('0x')) { let hash = hashes[i]
hash = '0x' + hash if ( ! hash.startsWith('0x') ) {
hash = '0x' + hash
} }
hashes[i] = hash hashes[i] = hash
} }
try { try
let txHash = await ss.stamp(hashes, walletAccount) {
//let fullUrl = req.protocol + '://' + req.get('host') let txHash = await ss.stamp(hashes, walletAccount)
//let fullUrl = req.protocol + '://' + req.get('host')
res.status(200).send('success') res.status(200).send('success')
} catch (e) { } catch (e) {
console.error(e) console.error(e)
...@@ -155,15 +158,14 @@ app.post('/stamp', async (req, res) => { ...@@ -155,15 +158,14 @@ app.post('/stamp', async (req, res) => {
}) })
app.get('/verify/:hash', async (req, res) => { app.get('/verify/:hash', async (req, res) => {
let ss = new Stamper(web3, contractAbi, contractAddress) let ss = new Stamper(web3, contractAbi, contractAddress)
var value = req.params.hash var value = req.params.hash
if (! value.startsWith('0x')) { if ( ! value.startsWith('0x') )
value = '0x' + value value = '0x' + value
}
try { try {
let info = await ss.verify(value) let info = await ss.verify(value)
return res.json(info) return res.json(info)
} catch (e) { } catch (e) {
console.error(e) console.error(e)
...@@ -186,7 +188,7 @@ app.get('/verify/:hash', async (req, res) => { ...@@ -186,7 +188,7 @@ app.get('/verify/:hash', async (req, res) => {
// }) // })
let port = (process.env.PORT) ? process.env.PORT : 3000 let port = (process.env.PORT) ? process.env.PORT : 3000
app.listen(port, () => app.listen(port, () =>
console.log(`TSA Api corriendo en ${port}!`), console.log(`TSA Api corriendo en ${port}!`),
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment