Repository navigation
Expand file tree
/
Copy pathfaucet.js
More file actions
247 lines (201 loc) · 6.28 KB
/
Copy pathfaucet.js
File metadata and controls
247 lines (201 loc) · 6.28 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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import express from 'express';
import * as path from 'path'
import { exec } from "child_process"
import { StargateClient } from "@cosmjs/stargate";
import conf from './config.js'
import { FrequencyChecker } from './checker.js';
// load config
console.log("loaded config: ", conf)
const app = express()
app.use(express.static(path.resolve('.'), {
setHeaders: (res, p) => {
if (p.endsWith('.mp4')) {
res.type('video/mp4'); // ensure correct MIME
res.set('Accept-Ranges', 'bytes');
}
}
}));
const checker = new FrequencyChecker(conf)
let faucetAddress = null;
(async () => {
try {
const addr = await getAccountAddress()
faucetAddress = addr
} catch (err) {
throw new Error(err)
}
})();
app.get('/', (_, res) => {
res.sendFile(path.resolve('./index.html'));
})
app.get('/config.json', async (_, res) => {
const sample = {}
const chainConf = conf.blockchain
sample[chainConf.name] = faucetAddress
const project = conf.project
project.sample = sample
project.blockchain = conf.blockchain.name
const tokens = []
for (var i = 0; i < conf.blockchain.tx.length; i++) {
tokens.push(conf.blockchain.tx[i].amount)
}
project.tokens = tokens
project.endpoint = conf.blockchain.endpoint
project.prefix = conf.blockchain.addressPrefix
project.currencies = conf.blockchain.currencies
res.send(project);
})
app.get('/balance/:denom', async (req, res) => {
const {denom} = req.params;
let balance = {}
if (!denom) {
res.send({ result: 'denom is required' });
return
}
let index = getIndexByDenom(denom)
if (index == null) {
res.send({ result: 'denom not found' });
return
}
let currencyIndex = getIndexByMinimalDenom(denom)
if (currencyIndex == null) {
res.send({ result: 'currencies denom not found' });
return
}
try{
const chainConf = conf.blockchain
if(chainConf) {
const rpcEndpoint = chainConf.endpoint.rpc;
const client = await StargateClient.connect(rpcEndpoint);
await client.getBalance(faucetAddress, chainConf.tx[index].amount.denom).then(x => {
const dec = conf.blockchain.currencies[currencyIndex].coinDecimals
if (dec != 0) {
x.amount = (parseInt(x.amount) / Math.pow(10, dec)).toFixed(dec)
x.denom = conf.blockchain.currencies[currencyIndex].coinDenom
}
return balance = x
}).catch(e => console.error(e));
}
} catch(err) {
console.log(err)
}
res.send(balance);
})
app.get('/send/:address/:denom', async (req, res) => {
const {denom, address} = req.params;
const ip = req.headers['x-real-ip'] || req.headers['X-Real-IP'] || req.headers['X-Forwarded-For'] || req.ip
console.log('request tokens to ', address, ip, denom)
if (!address) {
res.send({ result: 'address is required' });
return
}
if (!denom) {
res.send({ result: 'denom is required' });
return
}
let index = getIndexByDenom(denom)
if (index == null) {
res.send({ result: 'denom not found' });
return
}
try {
const chainConf = conf.blockchain
if (chainConf && address.startsWith(chainConf.addressPrefix)) {
if( await checker.checkAddress(address) && await checker.checkIp(`${index}${ip}`) ) {
checker.update(`${index}${ip}`) // get ::1 on localhost
sendCosmosTx(address, index).then(ret => {
checker.update(address)
res.send({ result: ret })
}).catch(err => {
res.send({ result: `err: ${err}`})
});
}else {
res.send({ result: "You requested too often" })
}
} else {
res.send({ result: `Address [${address}] is not supported.` })
}
} catch (err) {
console.error(err);
res.send({ result: 'Failed, Please contact to admin.' })
}
})
app.listen(conf.port, () => {
console.log(`Faucet app listening on port ${conf.port}`)
})
function getIndexByDenom(denom) {
const chainConf = conf.blockchain
for ( var i = 0; i < chainConf.tx.length; i++ ) {
if (chainConf.tx[i].amount.denom == denom) {
return i
}
}
return null
}
function getIndexByMinimalDenom(MinimalDenom) {
const chainConf = conf.blockchain
for ( var i = 0; i < chainConf.tx.length; i++ ) {
if (chainConf.currencies[i].coinMinimalDenom == MinimalDenom) {
return i
}
}
return null
}
async function myExec(cmd) {
return new Promise((resolve, reject) => {
exec(cmd, (err, stdout, stderr) => {
if (err) {
return reject(err)
}
if (stderr) {
return reject(stderr)
}
return resolve(stdout.replace("\n", ""))
})
})
}
async function getAccountAddress() {
const chainConf = conf.blockchain
if(!chainConf) {
throw new Error(`Blockchain Config [${chain}] not found`)
}
if (!chainConf.sender.accountName) {
throw new Error(`Sender account name not found`)
}
// if (!chainConf.sender.keyRingPass) {
// throw new Error(`Sender keyring password not found`)
// }
return myExec(`echo '${chainConf.sender.keyRingPass}' | fairyringd keys show ${chainConf.sender.accountName} -a`);
}
async function fairyringdBankSendTx(to, amount) {
const chainConf = conf.blockchain
if(!chainConf) {
throw new Error(`Blockchain Config [${chain}] not found`)
}
if (!chainConf.sender.accountName) {
throw new Error(`Sender account name not found`)
}
if (!chainConf.sender.keyRingPass) {
throw new Error(`Sender keyring password not found`)
}
if (!faucetAddress) {
throw new Error("Faucet address not found")
}
try {
const out = await myExec(`echo ${chainConf.sender.keyRingPass} | fairyringd tx bank send ${faucetAddress} ${to} ${amount} --from ${chainConf.sender.accountName} --node ${chainConf.endpoint.rpc} --chain-id ${chainConf.name} -y -o json`);
const jsonOut = JSON.parse(out)
console.log(`${new Date().toLocaleString()} Sent ${amount} to ${to}, result: ${out}`)
return jsonOut
} catch (err) {
throw new Error(err)
};
};
async function sendCosmosTx(recipient, amountIndex) {
const chainConf = conf.blockchain
if(!chainConf) {
throw new Error(`Blockchain Config [${chain}] not found`)
}
const tx = chainConf.tx[amountIndex];
console.log("Recipient & Amount: ", recipient, `${tx.amount.amount}${tx.amount.denom}`)
return fairyringdBankSendTx(recipient, `${tx.amount.amount}${tx.amount.denom}`)
}