-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
228 lines (177 loc) · 5.3 KB
/
app.js
File metadata and controls
228 lines (177 loc) · 5.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
axios = require("axios");
l = console.log;
crypto = require("crypto");
rand = () => crypto.randomBytes(6).toString("hex");
fs = require("fs");
Opts = {};
require("dotenv").config();
// include db schemes
require("./db");
process.on("unhandledRejection", l);
process.on("uncaughtException", l);
// define merchant node path
if (fs.existsSync("/root/fair/data8002/offchain/pk.json")) {
fair_path = "/root/fair/data8002/offchain";
our_fair_rpc = "http://127.0.0.1:8202/rpc";
} else {
fair_path = "/Users/homakov/work/fair/data8002/offchain";
our_fair_rpc = "http://127.0.0.1:8002/rpc";
}
processUpdates = async () => {
r = await Fair("receivedAndFailed");
if (!r.data.receivedAndFailed) return l("No receivedAndFailed");
for (let obj of r.data.receivedAndFailed) {
//if (obj.asset != 1) return // only FRD accepted
l(obj);
if (!obj.invoice) return;
let uid = parseInt(
Buffer.from(obj.invoice, "hex")
.slice(1)
.toString()
);
if (!Number.isInteger(uid)) return;
let receiver = await User.findById(uid, { include: [{ all: true }] });
// checking if uid is valid
if (receiver) {
l(receiver.id, obj.is_inward ? " receive" : " refund");
let bal = receiver.balances.find(b => b.asset == obj.asset);
// add to existing Balance
if (bal) {
bal.balance += obj.amount;
await bal.save();
} else {
// create new record
await receiver.createBalance({
asset: obj.asset,
balance: obj.amount
});
}
} else {
l("No such user " + uid);
}
}
setTimeout(processUpdates, 1000);
};
Fair = (method, params = {}) => {
return axios.post(our_fair_rpc, {
method: method,
auth_code: auth_code,
params: params
});
};
init = async () => {
await sequelize.sync({ force: false });
if (fs.existsSync(fair_path + "/pk.json")) {
auth_code = JSON.parse(fs.readFileSync(fair_path + "/pk.json")).auth_code;
l("Auth code to local node: " + auth_code);
} else {
l("No local node auth found");
return setTimeout(init, 1000);
}
r = await Fair("getinfo");
if (!r.data.address) {
l("No address");
return setTimeout(init, 1000);
}
Opts.our_address = r.data.address;
// filter for assets you support
let whitelist = [1, 2, 5];
Opts.assets = r.data.assets.filter(a => whitelist.includes(a.id));
l("Our address: " + Opts.our_address);
l("URL: http://127.0.0.1:3010");
processUpdates();
const express = require("express");
const app = express();
const passport = require("passport");
var GoogleStrategy = require("passport-google-oauth").OAuth2Strategy;
passport.authenticate("google");
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: "http://www.example.com/auth/google/callback"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({ googleId: profile.id }, function(err, user) {
return done(err, user);
});
}
)
);
app.use(express.static("public"));
app.use(express.json());
app.post("/rpc", async (req, res) => {
res.status = 200;
let p = req.body;
let respond = json => {
// global vars
json.assets = Opts.assets;
json.our_address = Opts.our_address;
if (json.user) {
json.auth_token = json.user.auth_token.toString("hex");
}
res.end(JSON.stringify(json));
};
if (!p.auth_token) {
let user = await User.create({
auth_token: crypto.randomBytes(32)
});
return respond({ user: user });
}
let user = await User.find({
where: { auth_token: Buffer.from(p.auth_token, "hex") },
include: [{ all: true }]
});
if (!user) return respond({ error: "fail_auth" });
if (p.method == "send") {
let amount = Math.round(parseFloat(p.amount) * 100);
let bal = user.balances.find(b => b.asset == p.asset);
// todo: add transactions
if (!bal || bal.balance < amount) {
l("Not enough balance: ", bal, p.asset);
return false;
}
let [addr, hash] = p.address.split("#");
// if destination is under same custodian, send internally with 0 fee
if (addr == Opts.our_address) {
let dest = parseInt(hash);
if (user.id == dest) {
return respond({ status: "paying_self" });
}
let target = (await Balance.findOrBuild({
where: {
userId: dest,
asset: p.asset
}
}))[0];
target.balance += amount;
await target.save();
bal.balance -= amount;
await bal.save();
} else {
// send through Fair network to external address
bal.balance -= amount;
await bal.save();
r = await Fair("send", {
address: p.address,
amount: amount,
asset: p.asset
});
l(r.data);
}
// if fail, do not withdraw?
respond({ status: "paid" });
} else if (p.method == "load") {
respond({ user: user });
}
});
app.listen(3010, () => {
console.log("web at 3010");
try {
require("../fair/lib/opn")("http://127.0.0.1:3010");
} catch (e) {}
});
};
init();
repl = require("repl").start();