-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-server.js
More file actions
388 lines (338 loc) · 11.9 KB
/
api-server.js
File metadata and controls
388 lines (338 loc) · 11.9 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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
const express = require('express');
const BlockchainAPI = require('./BlockchainAPI');
const app = express();
const api = new BlockchainAPI(30000); // 30 second cache for real-time data
const PORT = process.env.PORT || 3000;
app.use(express.json());
// Helper function to calculate percentage change
function calculatePercentageChange(oldValue, newValue) {
if (oldValue === 0) return 0;
return ((newValue - oldValue) / oldValue) * 100;
}
// Helper function to group transactions by month
function groupTransactionsByMonth(transactions) {
const monthlyData = {};
transactions.forEach(tx => {
const date = new Date(tx.time * 1000);
const monthKey = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
if (!monthlyData[monthKey]) {
monthlyData[monthKey] = {
month: monthKey,
transactionCount: 0,
totalValue: 0,
transactions: []
};
}
let txValue = 0;
tx.out.forEach(output => {
txValue += output.value;
});
monthlyData[monthKey].transactionCount++;
monthlyData[monthKey].totalValue += txValue;
monthlyData[monthKey].transactions.push(tx.hash);
});
return Object.values(monthlyData).sort((a, b) => a.month.localeCompare(b.month));
}
// Route 1: Bitcoin Month-over-Month trend
app.get('/bitcoin/mom', async (req, res) => {
try {
const latestBlock = await api.getLatestBlock();
const currentHeight = latestBlock.height;
// Approximate blocks per month (144 blocks/day * 30 days)
const blocksPerMonth = 144 * 30;
const currentMonthBlock = await api.getBlockAtHeight(currentHeight);
const lastMonthBlock = await api.getBlockAtHeight(currentHeight - blocksPerMonth);
const twoMonthsAgoBlock = await api.getBlockAtHeight(currentHeight - (blocksPerMonth * 2));
const currentMonth = currentMonthBlock.blocks[0];
const lastMonth = lastMonthBlock.blocks[0];
const twoMonthsAgo = twoMonthsAgoBlock.blocks[0];
// Calculate transaction count trend
const currentTxCount = currentMonth.n_tx || currentMonth.tx.length;
const lastMonthTxCount = lastMonth.n_tx || lastMonth.tx.length;
const twoMonthsAgoTxCount = twoMonthsAgo.n_tx || twoMonthsAgo.tx.length;
const txCountChange = calculatePercentageChange(lastMonthTxCount, currentTxCount);
const previousTxCountChange = calculatePercentageChange(twoMonthsAgoTxCount, lastMonthTxCount);
res.json({
success: true,
data: {
currentBlockHeight: currentHeight,
monthOverMonth: {
transactionCount: {
current: currentTxCount,
lastMonth: lastMonthTxCount,
twoMonthsAgo: twoMonthsAgoTxCount,
changePercent: txCountChange.toFixed(2),
trend: txCountChange > 0 ? 'up' : txCountChange < 0 ? 'down' : 'stable',
previousChangePercent: previousTxCountChange.toFixed(2)
},
blockInfo: {
current: {
height: currentHeight,
time: new Date(currentMonth.time * 1000).toISOString(),
size: currentMonth.size
},
lastMonth: {
height: currentHeight - blocksPerMonth,
time: new Date(lastMonth.time * 1000).toISOString(),
size: lastMonth.size
}
}
}
}
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
// Route 2: Bitcoin history (recent blocks)
app.get('/bitcoin/history', async (req, res) => {
try {
const limit = parseInt(req.query.limit) || 10;
const latestBlock = await api.getLatestBlock();
const currentHeight = latestBlock.height;
const history = [];
for (let i = 0; i < limit; i++) {
const blockData = await api.getBlockAtHeight(currentHeight - i);
const block = blockData.blocks[0];
history.push({
height: currentHeight - i,
hash: block.hash,
time: new Date(block.time * 1000).toISOString(),
transactionCount: block.n_tx || block.tx.length,
size: block.size,
weight: block.weight
});
// Rate limiting
if (i < limit - 1) {
await new Promise(resolve => setTimeout(resolve, 100));
}
}
res.json({
success: true,
data: {
latestBlock: currentHeight,
blocksRetrieved: history.length,
history
}
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
// Route 3: Address transaction history
app.get('/address/:address/history', async (req, res) => {
try {
const { address } = req.params;
const limit = parseInt(req.query.limit) || 50;
const details = await api.getAddressDetails(address, limit);
const history = details.txs.map(tx => {
let netChange = 0;
// Calculate net change for this address
tx.inputs.forEach(input => {
if (input.prev_out && input.prev_out.addr === address) {
netChange -= input.prev_out.value;
}
});
tx.out.forEach(output => {
if (output.addr === address) {
netChange += output.value;
}
});
return {
hash: tx.hash,
time: new Date(tx.time * 1000).toISOString(),
netChangeSatoshis: netChange,
netChangeBTC: api.satoshisToBTC(netChange),
netChangeFormatted: api.formatBTC(api.satoshisToBTC(netChange)),
size: tx.size,
fee: tx.fee
};
});
res.json({
success: true,
data: {
address,
totalTransactions: details.n_tx,
totalReceived: api.formatBTC(api.satoshisToBTC(details.total_received)),
totalSent: api.formatBTC(api.satoshisToBTC(details.total_sent)),
finalBalance: api.formatBTC(api.satoshisToBTC(details.final_balance)),
history
}
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
// Route 4: Find all past whale transactions for an address
app.get('/address/:address/whale-transactions', async (req, res) => {
try {
const { address } = req.params;
const minBTC = parseFloat(req.query.minBTC) || 100;
const limit = parseInt(req.query.limit) || 100;
const details = await api.getAddressDetails(address, limit);
const minSatoshis = minBTC * 100000000;
const whaleTransactions = details.txs.filter(tx => {
let totalValue = 0;
tx.out.forEach(output => {
totalValue += output.value;
});
return totalValue >= minSatoshis;
}).map(tx => {
let totalValue = 0;
let netChange = 0;
tx.out.forEach(output => {
totalValue += output.value;
if (output.addr === address) {
netChange += output.value;
}
});
tx.inputs.forEach(input => {
if (input.prev_out && input.prev_out.addr === address) {
netChange -= input.prev_out.value;
}
});
return {
hash: tx.hash,
time: new Date(tx.time * 1000).toISOString(),
totalValue: api.formatBTC(api.satoshisToBTC(totalValue)),
totalValueBTC: api.satoshisToBTC(totalValue),
netChange: api.formatBTC(api.satoshisToBTC(netChange)),
netChangeBTC: api.satoshisToBTC(netChange),
direction: netChange > 0 ? 'received' : netChange < 0 ? 'sent' : 'neutral',
inputs: tx.inputs.length,
outputs: tx.out.length,
topRecipients: tx.out
.sort((a, b) => b.value - a.value)
.slice(0, 3)
.map(out => ({
address: out.addr || 'Unknown',
amount: api.formatBTC(api.satoshisToBTC(out.value))
}))
};
});
res.json({
success: true,
data: {
address,
minBTC,
totalTransactionsScanned: details.txs.length,
whaleTransactionsFound: whaleTransactions.length,
whaleTransactions
}
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
// Route 5: Balance progression over time
app.get('/address/:address/balance-progression', async (req, res) => {
try {
const { address } = req.params;
const limit = parseInt(req.query.limit) || 50;
const details = await api.getAddressDetails(address, limit);
// Calculate balance at each transaction point
let runningBalance = details.final_balance;
const progression = [];
// Process transactions from newest to oldest, working backwards
for (let i = 0; i < details.txs.length; i++) {
const tx = details.txs[i];
// Add current state
progression.unshift({
time: new Date(tx.time * 1000).toISOString(),
balanceSatoshis: runningBalance,
balanceBTC: api.satoshisToBTC(runningBalance),
balanceFormatted: api.formatBTC(api.satoshisToBTC(runningBalance)),
transactionHash: tx.hash
});
// Calculate net change for this transaction
let netChange = 0;
tx.inputs.forEach(input => {
if (input.prev_out && input.prev_out.addr === address) {
netChange -= input.prev_out.value;
}
});
tx.out.forEach(output => {
if (output.addr === address) {
netChange += output.value;
}
});
// Work backwards: subtract the net change to get previous balance
runningBalance -= netChange;
}
// Calculate monthly summary
const monthlyData = groupTransactionsByMonth(details.txs);
res.json({
success: true,
data: {
address,
currentBalance: api.formatBTC(api.satoshisToBTC(details.final_balance)),
totalTransactions: details.n_tx,
dataPoints: progression.length,
progression,
monthlyBreakdown: monthlyData.map(month => ({
month: month.month,
transactionCount: month.transactionCount,
totalValueMoved: api.formatBTC(api.satoshisToBTC(month.totalValue))
}))
}
});
} catch (error) {
res.status(500).json({
success: false,
error: error.message
});
}
});
// Health check route
app.get('/health', (req, res) => {
res.json({
success: true,
message: 'Blockchain API Server is running',
timestamp: new Date().toISOString()
});
});
// Root route with API documentation
app.get('/', (req, res) => {
res.json({
success: true,
message: 'Blockchain.com Historical Data API',
endpoints: {
'GET /bitcoin/mom': 'Bitcoin Month-over-Month trend analysis',
'GET /bitcoin/history?limit=10': 'Recent Bitcoin block history',
'GET /address/:address/history?limit=50': 'Transaction history for an address',
'GET /address/:address/whale-transactions?minBTC=100&limit=100': 'Find whale transactions for an address',
'GET /address/:address/balance-progression?limit=50': 'Balance progression over time',
'GET /health': 'Health check'
},
examples: {
mom: 'http://localhost:3000/bitcoin/mom',
history: 'http://localhost:3000/bitcoin/history?limit=5',
addressHistory: 'http://localhost:3000/address/1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa/history?limit=10',
whaleTransactions: 'http://localhost:3000/address/1P5ZEDWTKTFGxQjZphgWPQUpe554WKDfHQ/whale-transactions?minBTC=50',
balanceProgression: 'http://localhost:3000/address/1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa/balance-progression?limit=20'
}
});
});
app.listen(PORT, () => {
console.log(`🚀 Blockchain API Server running on http://localhost:${PORT}`);
console.log(`\nAvailable endpoints:`);
console.log(` GET http://localhost:${PORT}/`);
console.log(` GET http://localhost:${PORT}/bitcoin/mom`);
console.log(` GET http://localhost:${PORT}/bitcoin/history`);
console.log(` GET http://localhost:${PORT}/address/:address/history`);
console.log(` GET http://localhost:${PORT}/address/:address/whale-transactions`);
console.log(` GET http://localhost:${PORT}/address/:address/balance-progression`);
console.log(`\nTry: http://localhost:${PORT}/`);
});