forked from sn-ntu/insight-api-zcoin
-
Notifications
You must be signed in to change notification settings - Fork 15
/
controller.js
207 lines (177 loc) · 6.6 KB
/
controller.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
'use strict';
const EventEmitter = require('events');
const MemoryStorage = require('./storage/memory');
const Stopped = 0;
const Running = 1;
const WaitingBlocks = 2;
const Stopping = 3;
const InvalidBlockError = new Error('block not valid');
const AlreadyLatestBlockError = new Error('already latest block');
class RichListController extends EventEmitter {
/**
* @param {object} options require node and storage is optional
*/
constructor(options) {
super();
this.node = options.node;
this.state = Stopped;
this.emitter = new EventEmitter();
if (options.storage) {
this.storage = options.storage;
} else {
this.storage = new MemoryStorage();
}
this.startScanBlocks = this.startScanBlocks.bind(this); // we need this to be able to pass startScanBlocks as a callback directly
}
init() {
this.state = Running;
this.startScanBlocks();
return Promise.resolve();
}
list(req, res) {
this.storage.getMostRichest(100).then(list => {
if (list) {
res.jsonp(list);
}
});
}
stop() {
return new Promise((resolve, reject) => {
let previousState = this.state;
// initiat stopping
this.state = Stopping;
this.emitter.once('stopped', resolve);
// check if scanning loop already completed and waiting for a new block
if (previousState === WaitingBlocks) {
this.startScanBlocks();
}
});
}
startScanBlocks() {
// check if stopping request
if (this.state === Stopping) {
this.state = Stopped;
this.node.services.bitcoind.removeListener('block', this.startScanBlocks);
this.emitter.emit('stopped');
return;
}
// start blocks scanning loop
this.state = Running;
this.storage.getLatestBlock().then(local => {
// check if latest local block still on the chain
return new Promise((resolve, reject) => {
this.node.getBlockHeader(local || 0, (err, block) => {
if (err) {
// assume the error is block is not valid
resolve();
} else {
resolve(block);
}
});
});
}).then(block => {
if (!block) {
// the latest local block does not on the chain, invalidate it
return this.storage.invalidateLatestBlock().then(() => {
throw InvalidBlockError;
});
}
if (!block.nextHash) {
throw AlreadyLatestBlockError;
}
// get next block
return new Promise((resolve, reject) => {
this.node.getBlockOverview(block.nextHash, (err, block) => {
if (err) {
// assume the error is block is not valid
resolve();
} else {
resolve(block);
}
});
});
}).then(block => {
if (!block) {
// the next block for latest local block does not on the chain, invalidate the latest local block
return this.storage.invalidateLatestBlock().then(() => {
throw InvalidBlockError;
});
}
// get a set of transactions that already have for the block
// we need this due to previously there is a bug that allow one transaction to be duplicated
return this.storage.hasTransactions(block.txids).then(skips => ({ block, skips }));
}).then(({ block, skips }) => {
// get all transactions for the block
let promise = undefined;
let txs = [];
for (let id of block.txids) {
// skill if it is duplicated
if (skips.has(id)) {
continue;
}
// get transaction detail
if (promise) {
promise = promise.then(tx => {
txs.push(tx);
return this.getTransaction(id);
});
} else {
promise = this.getTransaction(id);
}
// it is possible for transaction to be duplicated in the same block
skips.add(id);
}
// it is possible that all transactions in the block are duplicated
if (!promise) {
return { block, txs: [] };
}
return promise.then(tx => {
txs.push(tx);
return { block, txs };
});
}).then(({ block, txs }) => {
// if one of txs is undefined that mean a chain has been switched while we requesting transaction details
if (txs.some(tx => tx === undefined)) {
return this.storage.invalidateLatestBlock().then(() => {
throw InvalidBlockError;
});
}
return this.storage.addBlock(block, txs).then(() => block);
}).then(block => {
if (block.height % 100 === 0) {
this.node.log.info('Blocks scanned:', block.height);
}
// start next loop
this.startScanBlocks();
}).catch(err => {
if (err == InvalidBlockError) {
// start next loop
this.startScanBlocks();
} else if (err == AlreadyLatestBlockError) {
// local block is already up to date, wait until there is a new block to scan again
this.node.log.info('All blocks has been scanned');
if (this.state === Stopping) {
this.startScanBlocks();
} else {
this.state = WaitingBlocks;
this.node.services.bitcoind.once('block', this.startScanBlocks);
}
this.emit('latestBlockScanned');
} else {
throw err;
}
});
}
getTransaction(txid) {
return new Promise((resolve, reject) => {
this.node.getDetailedTransaction(txid, (err, transaction) => {
if (err) {
resolve();
} else {
resolve(transaction);
}
});
});
};
}
module.exports = RichListController;