app.ts 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227
  1. import 'dotenv/config'
  2. import grpc from "grpc"
  3. import express from "express"
  4. import bodyParser from "body-parser"
  5. import basicAuth from "express-basic-auth"
  6. import {
  7. CommandService_v1Client as CommandService,
  8. QueryService_v1Client as QueryService
  9. } from 'iroha-helpers/lib/proto/endpoint_grpc_pb'
  10. import { queries } from 'iroha-helpers'
  11. import util from 'util'
  12. import { exec } from 'child_process'
  13. import cors from 'cors'
  14. import * as sql from 'sqlite3'
  15. import fs from 'fs'
  16. const app = express();
  17. app.use(bodyParser.json());
  18. //TODO is cors package necesary? basic middleware could suffice
  19. app.use(cors()); //TODO: set only safe origins
  20. app.use(basicAuth({
  21. users: { admin: 'superPasswd' }
  22. }));
  23. const asyncExec = util.promisify(exec);
  24. const IROHA_ADMIN_PRIV = "f101537e319568c765b2cc89698325604991dca57b9716b58016b253506cab70";
  25. const IROHA_ADMIN = "admin@test";
  26. const IROHA_ADDRESS = process.env.IROHA_ADDRESS || "localhost:50051";
  27. const queryService = new QueryService(IROHA_ADDRESS, grpc.credentials.createInsecure());
  28. const CHAIN4ALL_RASTER_CLIP_SCRIPT_PATH = process.env.CHAIN4ALL_RASTER_CLIP_SCRIPT_PATH || '/home/kunickyd/Documents/chain4all/chain4all_raster_clip.sh';
  29. const CHAIN4ALL_SERVICE_PORT = process.env.CHAIN4ALL_SERVICE_PORT || 3000;
  30. const PRICE_MODIFIER: number = parseFloat(process.env.PRICE_MODIFIER || "0.5");
  31. const DB_FILE_NAME: string = "data/transfers.db";
  32. app.get("/", (req, res) => {
  33. res.send("Chain4All Blockchain service");
  34. });
  35. app.get("/transfers/:userId", async (req, res, next) => {
  36. let db = await getDbConnection();
  37. db.all(
  38. "SELECT hash " +
  39. "FROM transfers " +
  40. "WHERE user=? " +
  41. "ORDER BY id DESC " +
  42. "LIMIT 10;",
  43. [req.params.userId],
  44. (err, rows) => {
  45. if (err) {
  46. next(err);
  47. return;
  48. }
  49. res.send(rows);
  50. }
  51. );
  52. db.close();
  53. });
  54. app.post("/transfer", async (req, res, next) => {
  55. try {
  56. if (!req.body) {
  57. res.status(400);
  58. throw Error(JSON.stringify({ error: { name: "Error, request has no body!" } }));
  59. }
  60. if (!req.body.txHash) {
  61. res.status(400);
  62. throw Error(JSON.stringify({ error: { name: "Error, request body has no \"txHash\" property!" } }));
  63. }
  64. if (!req.body.user) {
  65. res.status(400);
  66. throw Error(JSON.stringify({ error: { name: "Error, request body has no \"user\" property!" } }));
  67. }
  68. let db = await getDbConnection();
  69. db.run(
  70. "INSERT INTO transfers (hash, user)" +
  71. "VALUES (?, ?);",
  72. [req.body.txHash, req.body.user],
  73. (err) => {
  74. if (err) {
  75. next(err);
  76. return;
  77. }
  78. res.status(201);
  79. res.send();
  80. }
  81. );
  82. db.close();
  83. }
  84. catch (err) {
  85. next(err);
  86. }
  87. });
  88. app.post("/price", (req, res) => { //add caching of same requests
  89. if (req.body && req.body.area) {
  90. res.send({ price: getPrice(req.body.area) });
  91. }
  92. else {
  93. res.status(400);
  94. throw Error(JSON.stringify({ error: { name: "Error, request has no body with \"area\" property!" } }));
  95. }
  96. });
  97. app.post("/buy", async (req, res, next) => {
  98. try {
  99. if (!req.body) {
  100. res.status(400);
  101. throw Error(JSON.stringify({ error: { name: "Error, request has no body!" } }));
  102. }
  103. if (!req.body.txHash) {
  104. res.status(400);
  105. throw Error(JSON.stringify({ error: { name: "Error, request body has no \"txHash\" property!" } }));
  106. }
  107. //TODO load from http headers, or something like that??
  108. if (!req.body.user) {
  109. res.status(400);
  110. throw Error(JSON.stringify({ error: { name: "Error, request body has no \"user\" property!" } }));
  111. }
  112. //TODO validate this properly
  113. let txDetail = await getTransactionDetail(req.body.txHash, req.body.user);
  114. let extent: number[] = JSON.parse(txDetail.description).extent as number[];
  115. let dataFileId: string = Date.now().toString();
  116. let dataCommand = CHAIN4ALL_RASTER_CLIP_SCRIPT_PATH + ' ' + extent[0] + ' ' + extent[1] + ' ' + extent[2] + ' ' + extent[3] + ' ' + dataFileId;
  117. console.debug(dataCommand);
  118. const { stdout, stderr } = await asyncExec(dataCommand);
  119. console.debug(stdout);
  120. if (stderr) {
  121. console.warn(stderr);
  122. }
  123. res.send({ dataUrl: "https://gis.lesprojekt.cz/chain4all/raster_" + dataFileId + ".tif" });
  124. }
  125. catch (err) {
  126. next(err);
  127. }
  128. });
  129. function getDbConnection(): Promise<sql.Database> {
  130. return new Promise<sql.Database>((resolve, reject) => {
  131. if(!fs.existsSync("./data")){
  132. fs.mkdirSync("data");
  133. };
  134. let db = new sql.Database(DB_FILE_NAME);
  135. db.run(
  136. "CREATE TABLE IF NOT EXISTS transfers( " +
  137. "id INTEGER PRIMARY KEY, " +
  138. "hash TEXT NOT NULL, " +
  139. "user TEXT NOT NULL " +
  140. ");",
  141. (err) => {
  142. if (err) {
  143. reject(err);
  144. }
  145. else{
  146. resolve(db);
  147. }
  148. }
  149. );
  150. });
  151. }
  152. async function getTransactionDetail(txHash: string, user: string) {
  153. let quer: any = await queries.getAccountTransactions({
  154. privateKey: IROHA_ADMIN_PRIV,
  155. creatorAccountId: IROHA_ADMIN,
  156. queryService,
  157. timeoutLimit: 5000
  158. }, {
  159. accountId: user,
  160. pageSize: 10,
  161. firstTxHash: txHash,
  162. ordering: {
  163. field: undefined,
  164. direction: undefined
  165. },
  166. firstTxTime: undefined,
  167. lastTxTime: undefined,
  168. firstTxHeight: 1,
  169. lastTxHeight: 3
  170. });
  171. //TODO find better way to look for transferAssets command in transaction
  172. return quer.transactionsList[0].payload.reducedPayload.commandsList[0].transferAsset;
  173. }
  174. function getPrice(area: number): number {
  175. return area * PRICE_MODIFIER;
  176. }
  177. function errorMiddleware(err: any, req: any, res: any, next: any): void { //TODO: add custom Exception class
  178. console.log(err);
  179. res.status(500);
  180. res.send(err);
  181. }
  182. app.use(errorMiddleware);
  183. app.listen(CHAIN4ALL_SERVICE_PORT, () => {
  184. console.log(`Listening at http://localhost:${CHAIN4ALL_SERVICE_PORT}`)
  185. });