-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
340 lines (269 loc) · 9.05 KB
/
index.js
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
// pebas
// Public endpoint for the Marscoin blockchain as an api service.
//
//! @author Kenneth Shortrede https://github.com/kshortrede
//! @author Sebastian Fabara https://github.com/sfabara
import { createRequire } from "module";
import fetch from "node-fetch";
import { Marscoin } from "./networks.js";
//Allow both imports and requires
const require = createRequire(import.meta.url);
const express = require("express");
//const jwt = require('njwt');
const app = express();
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const cors = require("cors");
const util = require("util");
const { request, response } = require("express");
//Security
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
const cryptojs = require("crypto-js");
const crypto = require("crypto");
//Bitcoin
const bitcoinController = require("bitcoinjs-lib");
// const bip44 = require("bip44");
const coinSelect = require("coinselect");
const ElectrumClient = require("electrum-client");
const peers = require("electrum-host-parse")
.getDefaultPeers("BitcoinSegwit")
.filter((v) => v.ssl);
const getRandomPeer = () => peers[(peers.length * Math.random()) | 0];
//app.use(bodyParser.urlencoded({extended: true}));
app.use(cors({ origin: "*", methods: ['GET','POST','DELETE','UPDATE','PUT','PATCH']}));
app.use(express.json());
app.use(cookieParser());
app.listen(3001, () => {
console.log("Running on port 3001 🚀");
});
// Electrum Clients Connection
const marsecl = new ElectrumClient("50002", "147.182.177.23", "ssl");
async function connectElectrumClient(client, maxRetries = 5, delay = 1000) {
let retries = 0;
async function attemptConnection() {
try {
await client.connect();
console.log("Successfully connected to Mars Electrum server.");
client.on('close', () => {
console.log("Connection to Mars Electrum server lost. Attempting to reconnect...");
setTimeout(reconnect, delay);
});
} catch (error) {
if (retries < maxRetries) {
retries++;
console.log(`Connection failed, retrying... (${retries}/${maxRetries})`);
setTimeout(attemptConnection, retries * delay);
} else {
console.log("Failed to connect to Mars Electrum server after several attempts.");
throw error;
}
}
}
async function reconnect() {
retries = 0; // Reset retry counter for a fresh start
attemptConnection();
}
await attemptConnection();
}
const mainMARS = async () => {
try {
await connectElectrumClient(marsecl);
} catch (e) {
console.error("Error connecting to MARS electrum:", e);
}
};
mainMARS();
setInterval(async function () {
try {
await marsecl.server_ping();
// console.log("Server's Active");
} catch (Exception) {
console.log(Exception);
}
}, 5000);
// Desc: Adding MARSCOIN Electrum X functionality
// Parameters:
// SenderAddress
// ReceiverAddress
// Amount
//
// Takes in address and amount to spend and returns rawtx
app.get("/api/mars/utxo/", async (req, res) => {
const sender_address = req.query.sender_address;
const receiver_address = req.query.receiver_address;
const amount = req.query.amount;
if (!sender_address) {
const err = new Error("Required query params missing");
err.status = 400;
res.send("Required: SENDER_ADDRESS parameter missing");
return;
} else if (!amount) {
const err = new Error("Required query params missing");
err.status = 400;
res.send("Required: AMOUNT parameter missing");
return;
}
try {
const list_unspent = await marsGetUtxosByAddress(sender_address);
const rawtx = await getTxHash(list_unspent, amount, receiver_address);
console.log(rawtx)
res.send(rawtx);
return rawtx;
} catch (error) {
console.error(error);
}
});
// Parameters:
// txhash
//
// Takes in txhash and broadcasts transaction
app.all("/api/mars/broadcast/", async (req, res) => {
let txhash = req.param("txhash");
if (!txhash) {
console.log(req.param)
const err = new Error("Required query params missing");
err.status = 400;
res.send("Required: TXHASH parameter missing");
console.log("Required: TXHASH parameter missing");
return;
}
try {
const broadcast = await broadcastTx(txhash);
const result = { tx_hash: broadcast };
console.log(result);
res.send(result);
return;
} catch (error) {
console.error(error);
}
return;
});
app.get("/api/mars/txdetails/", async (req, res) => {
let txid = req.query.txid;
if (!txid) {
console.log(req.query)
const err = new Error("Required query params missing");
err.status = 400;
res.send("Required: TXID parameter missing");
console.log("Required: TXID parameter missing");
return;
}
try {
const txdetails = await checkDetails(txid);
console.log(txdetails);
const result = {txid: txid, confirmations: txdetails.confirmations, blocktime: txdetails.blocktime}
console.log(result);
res.send(result);
} catch (error) {
console.error(error);
}
return;
});
app.get("/api/mars/balance/", async (req, res) => {
const address = req.query.address;
if (!address) {
return res.status(400).send("Required: ADDRESS parameter is missing");
}
try {
const balance = await getBalanceByAddress(address);
res.json({ address: address, balance: balance });
} catch (error) {
console.error(error);
res.status(500).send("Internal Server Error");
}
});
// =====================================================================
// =====================================================================
// =========================== Core Functions ==========================
// Batch get UTXO List given address
const marsGetUtxosByAddress = async (address) => {
if (!marsecl) throw new Error("Electrum client is not connected...");
console.log("Grabbing list unspent for address:", address);
const scriptHash = adddressToScriptHash(address);
let list_unspent = await marsecl.blockchainScripthash_listunspent(scriptHash);
console.log("List unspent for", address, ":", list_unspent);
return list_unspent;
};
// Given a txid return raw tx
const getTxHash = async (list_unspent, amount, receiver_address) => {
// error handler
if (!marsecl) throw new Error("Electrum client is not connected...");
amount = Math.round(marsToZubrins(amount));
const targets = [
{
address: receiver_address,
value: amount,
},
];
const fee_rate = 1550;
// loop through utxo's and format
let formattedUtxos = [];
for (const index in list_unspent) {
let utxo = list_unspent[index];
let rawtx = await getRawTx(utxo.tx_hash);
const prop = {
txId: utxo.tx_hash,
vout: utxo.tx_pos,
value: utxo.value,
rawTx: rawtx,
nonWitnessUtxo: Buffer.from(rawtx, "hex"),
index: utxo.tx_pos,
};
formattedUtxos.push(prop);
}
//console.log("Amount: ", amount);
//console.log("Format UTXO: ", formattedUtxos);
let { inputs, outputs, fee } = coinSelect(formattedUtxos, targets, fee_rate);
//console.log(inputs, "\n\n", outputs);
// .inputs and .outputs will be undefined if no solution was found
if (!inputs || !outputs) return "Empty";
const result = {
inputs: inputs,
outputs: outputs,
fee: fee
};
// throw in tx id to get raw tx
return result;
};
const getRawTx = async (tx) => {
const raw = await marsecl.blockchainTransaction_get(tx, false);
return raw;
};
const broadcastTx = async (hex) => {
if (!marsecl) throw new Error("Electrum client is not connected...");
const broadcast = await marsecl.blockchainTransaction_broadcast(hex);
return broadcast;
};
const checkDetails = async (hex) => {
if (!marsecl) throw new Error("Electrum client is not connected...");
const confirmations = await marsecl.blockchainTransaction_get(hex, true);
return confirmations;
};
const getBalanceByAddress = async (address) => {
const utxos = await marsGetUtxosByAddress(address);
const balance = utxos.reduce((acc, utxo) => acc + utxo.value, 0);
return zubrinToMars(balance);
};
// =====================================================================
// =====================================================================
// =========================== Helper Functions ========================
const marsToZubrins = (MARS) => {
return MARS * 100000000;
};
const zubrinToMars = (ZUBRIN) => {
return ZUBRIN / 100000000;
};
// Given address return script hash
const adddressToScriptHash = (address) => {
const script = bitcoinController.address.toOutputScript(
address,
Marscoin.mainnet
);
const hash = bitcoinController.crypto.sha256(script);
const reversedHash = Buffer(hash.reverse()).toString("hex");
return reversedHash;
};
// ==========================================================================================================================
// ==========================================================================================================================
// ==========================================================================================================================