forked from simpleledger/SLPDB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.ts
408 lines (354 loc) · 15.4 KB
/
db.ts
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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import { MongoClient, Db as MongoDb } from 'mongodb';
import { DbConfig } from './config';
import { TNATxn } from './tna';
import { UtxoDbo, AddressBalancesDbo, GraphTxnDbo, TokenDBObject } from "./interfaces";
export class Db {
db!: MongoDb;
mongo!: MongoClient;
dbUrl: string;
dbName: string;
config: DbConfig;
constructor({ dbUrl, dbName, config }: { dbUrl: string, dbName: string, config: DbConfig }) {
this.dbUrl = dbUrl;
this.dbName = dbName;
this.config = config;
}
private async checkClientStatus(): Promise<boolean> {
if (!this.mongo) {
//let network = await Info.getNetwork();
//console.log("[INFO] Initializing MongoDB...")
this.mongo = await MongoClient.connect(this.dbUrl, { useNewUrlParser: true });
//let dbname = network === 'mainnet' ? this.config.name : this.config.name_testnet;
this.db = this.mongo.db(this.dbName);
return true;
}
return false;
}
async exit() {
await this.mongo.close();
}
async statusUpdate(status: any) {
await this.checkClientStatus();
await this.db.collection('statuses').deleteMany({ "context": status.context });
return await this.db.collection('statuses').insertOne(status);
}
async statusFetch(context: string) {
await this.checkClientStatus();
return await this.db.collection('statuses').findOne({ "context": context });
}
async tokenInsertReplace(token: any) {
await this.checkClientStatus();
await this.db.collection('tokens').deleteMany({ "tokenDetails.tokenIdHex": token.tokenDetails.tokenIdHex })
return await this.db.collection('tokens').insertMany([ token ]);
}
// async tokenreplace(token: any) {
// await this.db.collection('tokens').deleteMany({ "tokenDetails.tokenIdHex": token.tokenDetails.tokenIdHex })
// return await this.db.collection('tokens').insertMany([ token ]);
// }
async tokenDelete(tokenIdHex: string) {
await this.checkClientStatus();
return await this.db.collection('tokens').deleteMany({ "tokenDetails.tokenIdHex": tokenIdHex })
}
async tokenFetch(tokenIdHex: string): Promise<TokenDBObject|null> {
await this.checkClientStatus();
return await this.db.collection('tokens').findOne({ "tokenDetails.tokenIdHex": tokenIdHex })
}
async tokenReset() {
await this.checkClientStatus();
await this.db.collection('tokens').deleteMany({})
.catch(function(err) {
console.log('[ERROR] token collection reset ERR ', err)
throw err;
})
}
async graphInsertReplace(graph: GraphTxnDbo[], tokenIdHex: string) {
await this.checkClientStatus();
await this.db.collection('graphs').deleteMany({ "tokenDetails.tokenIdHex": tokenIdHex })
if(graph.length > 0) {
return await this.db.collection('graphs').insertMany(graph);
}
}
// async graphreplace(graph: GraphTxnDbo[]) {
// await this.db.collection('graphs').deleteMany({ "tokenDetails.tokenIdHex": graph[0].tokenDetails.tokenIdHex })
// return await this.db.collection('graphs').insertMany(graph);
// }
async graphDelete(tokenIdHex: string) {
await this.checkClientStatus();
return await this.db.collection('graphs').deleteMany({ "tokenDetails.tokenIdHex": tokenIdHex })
}
async graphFetch(tokenIdHex: string): Promise<GraphTxnDbo[]> {
await this.checkClientStatus();
return await this.db.collection('graphs').find({ "tokenDetails.tokenIdHex": tokenIdHex }).toArray();
// return await this.db.collection('graphs').find({
// "tokenDetails.tokenIdHex": tokenIdHex,
// "$or": [ { "graphTxn.hasUnspent": true }, { "graphTxn.hasUnspent": { "$exists": false } } ]
// }).toArray();
}
async graphTxnFetch(txid: string): Promise<GraphTxnDbo|null> {
await this.checkClientStatus();
return await this.db.collection('graphs').findOne({ "graphTxn.txid": txid });
}
async graphReset() {
await this.checkClientStatus();
await this.db.collection('graphs').deleteMany({})
.catch(function(err) {
console.log('[ERROR] graphs collection reset ERR ', err)
throw err;
})
}
async addressInsertReplace(addresses: AddressBalancesDbo[], tokenIdHex: string) {
await this.checkClientStatus();
await this.db.collection('addresses').deleteMany({ "tokenDetails.tokenIdHex": tokenIdHex })
if(addresses.length > 0) {
return await this.db.collection('addresses').insertMany(addresses);
}
}
// async addressreplace(addresses: AddressBalancesDbo[]) {
// await this.db.collection('addresses').deleteMany({ "tokenDetails.tokenIdHex": addresses[0].tokenDetails.tokenIdHex })
// return await this.db.collection('addresses').insertMany(addresses);
// }
async addressDelete(tokenIdHex: string) {
await this.checkClientStatus();
return await this.db.collection('addresses').deleteMany({ "tokenDetails.tokenIdHex": tokenIdHex })
}
async addressFetch(tokenIdHex: string): Promise<AddressBalancesDbo[]> {
await this.checkClientStatus();
return await this.db.collection('addresses').find({ "tokenDetails.tokenIdHex": tokenIdHex }).toArray();
}
async addressReset() {
await this.checkClientStatus();
await this.db.collection('addresses').deleteMany({})
.catch(function(err) {
console.log('[ERROR] addresses collection reset ERR ', err)
throw err;
})
}
async utxoInsertReplace(utxos: UtxoDbo[], tokenIdHex: string) {
await this.checkClientStatus();
await this.db.collection('utxos').deleteMany({ "tokenDetails.tokenIdHex": tokenIdHex })
if(utxos.length > 0) {
return await this.db.collection('utxos').insertMany(utxos);
}
}
// async utxoreplace(utxos: UtxoDbo[]) {
// await this.db.collection('utxos').deleteMany({ "tokenDetails.tokenIdHex": utxos[0].tokenDetails.tokenIdHex })
// return await this.db.collection('utxos').insertMany(utxos);
// }
async utxoDelete(tokenIdHex: string) {
await this.checkClientStatus();
return await this.db.collection('utxos').deleteMany({ "tokenDetails.tokenIdHex": tokenIdHex })
}
async utxoFetch(tokenIdHex: string): Promise<UtxoDbo[]> {
await this.checkClientStatus();
return await this.db.collection('utxos').find({ "tokenDetails.tokenIdHex": tokenIdHex }).toArray();
}
async singleUtxo(utxo: string): Promise<UtxoDbo|null> {
await this.checkClientStatus();
return await this.db.collection('utxos').findOne({ "utxo": utxo });
}
async singleMintUtxo(utxo: string): Promise<TokenDBObject|null> {
await this.checkClientStatus();
return await this.db.collection('tokens').findOne({ "mintBatonUtxo": utxo });
}
async utxoReset() {
await this.checkClientStatus();
await this.db.collection('utxos').deleteMany({})
.catch(function(err) {
console.log('[ERROR] utxos collection reset ERR ', err);
throw err;
})
}
async unconfirmedInsert(item: TNATxn) {
await this.checkClientStatus();
return await this.db.collection('unconfirmed').insertMany([item])
}
async unconfirmedReset() {
await this.checkClientStatus();
await this.db.collection('unconfirmed').deleteMany({})
.catch(function(err) {
console.log('[ERROR] mempoolreset ERR ', err);
throw err;
})
}
async unconfirmedFetch(txid: string): Promise<TNATxn|null> {
await this.checkClientStatus();
let res = await this.db.collection('unconfirmed').findOne({ "tx.h": txid }) as TNATxn;
return res;
}
async unconfirmedDelete(txid: string): Promise<any> {
await this.checkClientStatus();
let res = await this.db.collection('unconfirmed').deleteMany({ "tx.h": txid });
return res;
}
async unconfirmedProcessedSlp(): Promise<string[]> {
await this.checkClientStatus();
return (await this.db.collection('unconfirmed').find().toArray()).filter((i:TNATxn) => i.slp);
}
async unconfirmedSync(items: TNATxn[]) {
await this.checkClientStatus();
await this.db.collection('unconfirmed').deleteMany({})
.catch(function(err) {
console.log('[ERROR] unconfirmedSync ERR ', err)
})
while (true) {
let chunk = items.splice(0, 1000)
if (chunk.length > 0) {
await this.db.collection('unconfirmed').insertMany(chunk, { ordered: false }).catch(function(err) {
if (err.code !== 11000) {
console.log('[ERROR] ## ERR ', err, items)
throw err;
}
})
} else {
break
}
}
}
async confirmedFetch(txid: string): Promise<TNATxn|null> {
await this.checkClientStatus();
return await this.db.collection('confirmed').findOne({ "tx.h": txid }) as TNATxn;
}
async confirmedDelete(txid: string): Promise<any> {
await this.checkClientStatus();
return await this.db.collection('confirmed').deleteMany({ "tx.h": txid });
}
async confirmedReset() {
await this.checkClientStatus();
await this.db.collection('confirmed').deleteMany({}).catch(function(err) {
console.log('[ERROR] confirmedReset ERR ', err)
throw err;
})
}
async confirmedReplace(items: TNATxn[], requireSlpMetadata=true, block_index?: number) {
await this.checkClientStatus();
if(requireSlpMetadata) {
if(items.filter(i => !i.slp).length > 0) {
console.log(items.filter(i => !i.slp).map(i => i.tx.h));
//throw Error("Attempted to add items without SLP property.");
}
}
if(items.filter(i => !i.blk).length > 0) {
//console.log(items.filter(i => !i.slp).map(i => i.tx.h));
throw Error("Attempted to add items without BLK property.");
}
if(block_index) {
console.log('[INFO] Deleting confirmed transactions in block (for replacement):', block_index)
try {
await this.db.collection('confirmed').deleteMany({ 'blk.i': block_index })
} catch(err) {
console.log('confirmedReplace ERR ', err)
throw err;
}
console.log('[INFO] Updating block', block_index, 'with', items.length, 'items')
} else {
for(let i=0; i < items.length; i++) {
await this.db.collection('confirmed').deleteMany({ "tx.h": items[i].tx.h })
}
}
let index = 0
while (true) {
let chunk = items.slice(index, index+1000)
if (chunk.length > 0) {
try {
await this.db.collection('confirmed').insertMany(chunk, { ordered: false })
} catch(err) {
// duplicates are ok because they will be ignored
if (err.code !== 11000) {
console.log('[ERROR] confirmedReplace ERR ', err, items)
throw err;
}
}
index+=1000
} else {
break
}
}
}
async confirmedInsert(items: TNATxn[], requireSlpMetadata: boolean) {
await this.checkClientStatus();
if(requireSlpMetadata) {
if(items.filter(i => !i.slp).length > 0) {
console.log(items.filter(i => !i.slp).map(i => i.tx.h));
//throw Error("Attempted to add items without SLP property.");
}
}
let index = 0
while (true) {
let chunk = items.slice(index, index + 1000)
if (chunk.length > 0) {
try {
await this.db.collection('confirmed').insertMany(chunk, { ordered: false })
} catch (e) {
// duplicates are ok because they will be ignored
if (e.code !== 11000) {
console.log('[ERROR] confirmedInsert error:', e, items)
throw e
}
}
index+=1000
} else {
break
}
}
}
async confirmedIndex() {
await this.checkClientStatus();
console.log('[INFO] * Indexing MongoDB...')
console.time('TotalIndex')
if (this.config.index) {
let collectionNames = Object.keys(this.config.index)
for(let j=0; j<collectionNames.length; j++) {
let collectionName: string = collectionNames[j]
let keys: string[] = this.config.index[collectionName].keys
let fulltext: string[] = this.config.index[collectionName].fulltext
if (keys) {
console.log('[INFO] Indexing keys...')
for(let i=0; i<keys.length; i++) {
let o: { [key:string]: number } = {}
o[keys[i]] = 1
console.time('Index:' + keys[i])
try {
if (keys[i] === 'tx.h') {
await this.db.collection(collectionName).createIndex(o, { unique: true })
//console.log('* Created unique index for ', keys[i])
} else {
await this.db.collection(collectionName).createIndex(o)
//console.log('* Created index for ', keys[i])
}
} catch (e) {
console.log('[ERROR] blockindex error:', e)
throw e;
}
console.timeEnd('Index:' + keys[i])
}
}
if (fulltext && fulltext.length > 0) {
console.log('[INFO] Creating full text index...')
let o: { [key:string]: string } = {}
fulltext.forEach(function(key) {
o[key] = 'text'
})
console.time('Fulltext search for ' + collectionName) //,o)
try {
await this.db.collection(collectionName).createIndex(o, { name: 'fulltext' })
} catch (e) {
console.log('[ERROR] blockindex error:', e)
throw e;
}
console.timeEnd('Fulltext search for ' + collectionName)
}
}
}
//console.log('* Finished indexing MongoDB...')
console.timeEnd('TotalIndex')
try {
let result = await this.db.collection('confirmed').indexInformation(<any>{ full: true }) // <- No MongoSession passed
console.log('* Confirmed Index = ', result)
result = await this.db.collection('unconfirmed').indexInformation(<any>{ full: true }) // <- No MongoSession passed
console.log('* Unonfirmed Index = ', result)
} catch (e) {
console.log('[INFO] * Error fetching index info ', e)
throw e;
}
}
}