-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdatabase.js
More file actions
1413 lines (1245 loc) · 41.8 KB
/
Copy pathdatabase.js
File metadata and controls
1413 lines (1245 loc) · 41.8 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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const path = require('path');
const Database = require('better-sqlite3');
const crypto = require('crypto');
const { v4: uuidv4 } = require('uuid');
const db = new Database(path.join(__dirname, 'playerList', 'database.db'));
// 1) PRAGMAs
db.pragma('page_size = 4096');
db.pragma('journal_mode = WAL'); // permite leitores concorrentes sem bloquear
db.pragma('synchronous = NORMAL'); // durabilidade razoável com commits rápidos
db.pragma('temp_store = MEMORY'); // usa memória para arquivos temporários
db.pragma('cache_size = 65536'); // ajustar dependendo do page_size e RAM disponível
db.pragma('mmap_size = 268435456'); // 256 MB mmap para acelerar leituras (opcional)
db.pragma('busy_timeout = 10000'); // aguarda até 5s se DB estiver ocupado (evita SQLITE_BUSY)
db.pragma('wal_autocheckpoint = 5000'); // checkpoint automático do WAL a cada 1000 frames
db.pragma('journal_size_limit = 134217728'); // limite do journal (ex: 64MB) - opcional
db.pragma('foreign_keys = OFF'); // ative se você depende de FK; desligue só por ganho extremo
db.pragma('cache_spill = OFF'); // evita escrever páginas sujas em arquivos temporários
db.pragma('secure_delete = OFF'); // evita zeroing pages ao deletar (ganho leve de perf)
db.pragma('automatic_index = ON'); // padrão — deixe ON a menos que crie índices manualmente
const SATS_PER_COIN = 100_000_000;
/**
* Converte um valor “coin” (string ou número, e.g. 0.12345678) em satoshis (INTEGER)
*/
function toSats(amount) {
// parseFloat(…) para aceitar string ou número, Math.round para garantir inteiro
return Math.round(parseFloat(amount) * SATS_PER_COIN);
}
/**
* Converte satoshis (INTEGER) para string “coin” com 8 casas decimais
*/
function fromSats(sats) {
return (sats / SATS_PER_COIN).toFixed(8);
}
function walCheckpoint(mode = 'PASSIVE') {
try {
// modes: PASSIVE, FULL, RESTART
const res = db.pragma(`wal_checkpoint(${mode})`, { simple: true });
// better-sqlite3 returns an array/object depending da versão; aqui não precisamos do resultado
return res;
} catch (err) {
console.error('WAL checkpoint failed:', err);
}
}
// 2) Criação inicial de tabelas
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id TEXT PRIMARY KEY,
coins INTEGER DEFAULT 0,
cooldown INTEGER DEFAULT 0,
notified INTEGER DEFAULT 0
);
CREATE TABLE IF NOT EXISTS servers (
server_id TEXT PRIMARY KEY,
api_channel TEXT
);
CREATE TABLE IF NOT EXISTS cards (
code TEXT PRIMARY KEY,
owner_id TEXT NOT NULL
);
CREATE TABLE IF NOT EXISTS transactions (
id TEXT PRIMARY KEY,
date TEXT NOT NULL,
from_id TEXT NOT NULL,
to_id TEXT NOT NULL,
amount INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS dm_queue (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
embed_json TEXT NOT NULL,
row_json TEXT NOT NULL,
created_at INTEGER DEFAULT (strftime('%s','now'))
);
`);
const ipCols = db
.prepare(`PRAGMA table_info('ips')`)
.all()
.map(c => c.name);
if (ipCols.length > 0) {
// tabela existe, só adiciona a coluna se faltar
if (!ipCols.includes('try')) {
db.exec(`
ALTER TABLE ips
ADD COLUMN try INTEGER NOT NULL DEFAULT 0;
`);
console.log("⚙️ Migration: added 'try' in ips");
}
} else {
// tabela não existe, cria do zero já com 'try'
db.exec(`
CREATE TABLE ips (
ip_address TEXT PRIMARY KEY,
type INTEGER NOT NULL,
time INTEGER NOT NULL,
try INTEGER NOT NULL DEFAULT 0
);
`);
console.log("⚙️ Tabble created: 'ips'");
}
// 2) Garante os índices
db.exec(`
CREATE INDEX IF NOT EXISTS idx_ips_type ON ips(type);
CREATE INDEX IF NOT EXISTS idx_ips_time ON ips(time);
CREATE INDEX IF NOT EXISTS idx_ips_try ON ips(try);
`);
;
db.exec(`
CREATE TABLE IF NOT EXISTS user_grafic (
user_id TEXT PRIMARY KEY,
d1 REAL DEFAULT 0,
d2 REAL DEFAULT 0,
d3 REAL DEFAULT 0,
d4 REAL DEFAULT 0,
d5 REAL DEFAULT 0,
d6 REAL DEFAULT 0,
d7 REAL DEFAULT 0,
d8 REAL DEFAULT 0,
d9 REAL DEFAULT 0,
d10 REAL DEFAULT 0,
d11 REAL DEFAULT 0,
d12 REAL DEFAULT 0,
d13 REAL DEFAULT 0,
d14 REAL DEFAULT 0,
d15 REAL DEFAULT 0,
d16 REAL DEFAULT 0,
d17 REAL DEFAULT 0,
d18 REAL DEFAULT 0,
d19 REAL DEFAULT 0,
d20 REAL DEFAULT 0,
d21 REAL DEFAULT 0,
d22 REAL DEFAULT 0,
d23 REAL DEFAULT 0,
d24 REAL DEFAULT 0,
d25 REAL DEFAULT 0,
d26 REAL DEFAULT 0,
d27 REAL DEFAULT 0,
d28 REAL DEFAULT 0,
d29 REAL DEFAULT 0,
d30 REAL DEFAULT 0
);
`);
// 3) Garante os índices (novos ou existentes)
db.exec(`
CREATE INDEX IF NOT EXISTS idx_ips_type ON ips(type);
CREATE INDEX IF NOT EXISTS idx_ips_time ON ips(time);
CREATE INDEX IF NOT EXISTS idx_ips_try ON ips(try);
`);
// — IPS CRUD — adicione estas funções em database.js, após a criação da tabela ips
/**
* Insere ou atualiza um registro de IP na tabela ips.
* @param {string} ip_address IP normalizado (texto)
* @param {number} type 1 = login fail, 2 = account register
* @param {number} time timestamp em ms
*/
function upsertIp(ip_address, type, time) {
db.prepare(`
INSERT INTO ips (ip_address, type, time)
VALUES (?, ?, ?)
ON CONFLICT(ip_address) DO UPDATE SET
type = excluded.type,
time = excluded.time
`).run(ip_address, type, time);
}
/**
* Busca um registro de IP pelo endereço.
* @param {string} ip_address
* @returns {{ ip_address: string, type: number, time: number }|undefined}
*/
function getIp(ip_address) {
return db
.prepare('SELECT ip_address, type, time FROM ips WHERE ip_address = ?')
.get(ip_address);
}
/**
* Remove um registro de IP específico.
* @param {string} ip_address
*/
function deleteIp(ip_address) {
db.prepare('DELETE FROM ips WHERE ip_address = ?')
.run(ip_address);
}
/**
* Limpa registros de IP antigos:
* - type = 1 com time ≤ agora–1min
* - type = 2 com time ≤ agora–24h
*
* @returns {{ removedType1: number, removedType2: number }}
*/
function cleanOldIps() {
const now = Date.now();
const oneMin = now - 60 * 1000;
const oneDay = now - 24 * 60 * 60 * 1000;
const info1 = db
.prepare('DELETE FROM ips WHERE type = 1 AND time <= ?')
.run(oneMin);
const info2 = db
.prepare('DELETE FROM ips WHERE type = 2 AND time <= ?')
.run(oneDay);
return {
removedType1: info1.changes,
removedType2: info2.changes
};
}
// 3) Migração: adiciona coluna card_hash se ainda não existir
const cardCols = db.prepare(`PRAGMA table_info(cards)`).all().map(c => c.name);
if (!cardCols.includes('card_hash')) {
db.exec(`ALTER TABLE cards ADD COLUMN card_hash TEXT;`);
}
// 4) Índices
db.exec(`
CREATE INDEX IF NOT EXISTS idx_transactions_from ON transactions(from_id);
CREATE INDEX IF NOT EXISTS idx_transactions_to ON transactions(to_id);
CREATE INDEX IF NOT EXISTS idx_users_coins ON users(coins);
CREATE INDEX IF NOT EXISTS idx_cards_hash ON cards(card_hash);
`);
// Migração para colunas username e password na tabela users
const cols = db.prepare(`PRAGMA table_info(users)`).all().map(c => c.name);
if (!cols.includes('username')) {
db.exec(`ALTER TABLE users ADD COLUMN username TEXT;`);
}
if (!cols.includes('password')) {
db.exec(`ALTER TABLE users ADD COLUMN password TEXT;`);
}
// Criar tabela sessions se não existir
db.exec(`
CREATE TABLE IF NOT EXISTS sessions (
session_id TEXT PRIMARY KEY,
user_id TEXT NOT NULL,
created_at INTEGER DEFAULT (strftime('%s','now')),
expires_at INTEGER,
FOREIGN KEY(user_id) REFERENCES users(id)
);
`);
db.exec(`
CREATE TABLE IF NOT EXISTS backups (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT NOT NULL UNIQUE,
userId TEXT NOT NULL
);
/* <<< ADICIONE ISSO >>> */
CREATE TABLE IF NOT EXISTS bills (
bill_id TEXT PRIMARY KEY,
from_id TEXT,
to_id TEXT NOT NULL,
amount INTEGER NOT NULL,
date INTEGER NOT NULL,
FOREIGN KEY(from_id) REFERENCES users(id),
FOREIGN KEY(to_id) REFERENCES users(id)
);
`);
function createBackup(userId, code) {
// Insere um código de backup para o usuário
const stmt = db.prepare('INSERT INTO backups (userId, code) VALUES (?, ?)');
stmt.run(userId, code);
}
function deleteBackupById(id) {
const stmt = db.prepare('DELETE FROM backups WHERE id = ?');
stmt.run(id);
}
function getBackupByCode(code) {
const stmt = db.prepare('SELECT * FROM backups WHERE code = ?');
return stmt.get(code);
}
setInterval(checkpoint, 5 * 60 * 1000);
// —— FUNÇÕES ——
function checkpoint() {
try {
db.exec('PRAGMA wal_checkpoint(FULL);');
console.log('✅ Checkpoint manual executado.');
} catch (err) {
console.error('❌ Erro ao executar checkpoint manual:', err);
}
}
db.exec(`
CREATE TABLE IF NOT EXISTS bills (
bill_id TEXT PRIMARY KEY,
from_id TEXT NOT NULL,
to_id TEXT NOT NULL,
amount INTEGER NOT NULL,
date INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS idx_bills_from ON bills(from_id);
CREATE INDEX IF NOT EXISTS idx_bills_to ON bills(to_id);
`);
// — USERS —
function getUser(id) {
const stmt = db.prepare('SELECT * FROM users WHERE id = ?');
let user = stmt.get(id);
if (!user) {
db.prepare('INSERT INTO users (id) VALUES (?)').run(id);
user = stmt.get(id);
}
return {
...user,
// extensão útil para lógica/commands:
balance: {
sats: user.coins,
coins: fromSats(user.coins)
}
};
}
function setCoins(id, sats) {
// no toSats here
db.prepare('UPDATE users SET coins = ? WHERE id = ?').run(sats, id);
}
function addCoins(id, sats) {
// no toSats here
db.prepare('UPDATE users SET coins = coins + ? WHERE id = ?').run(sats, id);
}
function setCooldown(id, ts) {
getUser(id);
db.prepare('UPDATE users SET cooldown = ? WHERE id = ?').run(ts, id);
}
function getCooldown(id) {
return getUser(id).cooldown || 0;
}
function setNotified(id, flag) {
getUser(id);
db.prepare('UPDATE users SET notified = ? WHERE id = ?').run(flag ? 1 : 0, id);
}
function wasNotified(id) {
return Boolean(getUser(id).notified);
}
function getAllUsers() {
return db.prepare('SELECT * FROM users').all();
}
// — SERVERS —
function setServerApiChannel(serverId, channelId) {
db.prepare(`
INSERT INTO servers(server_id, api_channel)
VALUES(?,?)
ON CONFLICT(server_id) DO UPDATE SET api_channel=excluded.api_channel
`).run(serverId, channelId);
}
function getServerApiChannel(serverId) {
const row = db.prepare('SELECT api_channel FROM servers WHERE server_id = ?')
.get(serverId);
return row?.api_channel || null;
}
// — CARDS —
function createCard(userId) {
const code = crypto.randomBytes(6).toString('hex');
db.prepare('DELETE FROM cards WHERE owner_id = ?').run(userId);
db.prepare('INSERT INTO cards (code, owner_id) VALUES (?,?)').run(code, userId);
return code;
}
function resetCard(userId) { return createCard(userId); }
function getCardOwner(code) {
const row = db.prepare('SELECT owner_id FROM cards WHERE code = ?').get(code);
return row?.owner_id || null;
}
function deleteCard(code) {
db.prepare('DELETE FROM cards WHERE code = ?').run(code);
}
function getCardOwnerByHash(hash) {
const rows = db.prepare('SELECT code, owner_id FROM cards').all();
for (const { code, owner_id } of rows) {
if (crypto.createHash('sha256').update(code).digest('hex') === hash) {
return owner_id;
}
}
return null;
}
// — TRANSACTIONS —
function createTransaction(fromId, toId, coinAmount) {
const amountSats = toSats(coinAmount);
const txId = uuidv4();
const date = new Date().toISOString();
db.prepare(`
INSERT INTO transactions (id, date, from_id, to_id, amount)
VALUES (?, ?, ?, ?, ?)
`).run(txId, date, fromId, toId, amountSats);
return { txId, date };
}
// 2) recupera uma transação existente pelo ID
function getTransaction(txId) {
const stmt = db.prepare(`
SELECT id, date, from_id AS fromId, to_id AS toId, amount
FROM transactions
WHERE id = ?
`);
const tx = stmt.get(txId);
if (!tx) return null;
return {
id: tx.id,
date: tx.date,
fromId: tx.fromId,
toId: tx.toId, // valor bruto em satoshis
coins: fromSats(tx.amount) // valor formatado em coins (8 casas)
};
}
// 3) helper que gera um ID único (não conflita) e registra
function genUniqueTxId() {
let id;
do {
id = uuidv4();
} while (
db.prepare('SELECT 1 FROM transactions WHERE id = ?').get(id)
);
return id;
}
// 4) helper que gera e já insere via createTransaction
function genAndCreateTransaction(fromId, toId, amount) {
const txId = genUniqueTxId();
const date = new Date().toISOString();
db.prepare(`
INSERT INTO transactions (id, date, from_id, to_id, amount)
VALUES (?, ?, ?, ?, ?)
`).run(txId, date, fromId, toId, amount);
return { txId, date };
}
// — DM QUEUE —
function getNextDM() {
return db.prepare(`
SELECT * FROM dm_queue
ORDER BY id
LIMIT 1
`).get();
}
function deleteDM(id) {
db.prepare('DELETE FROM dm_queue WHERE id = ?').run(id);
}
function getUserByUsername(username) {
const stmt = db.prepare('SELECT * FROM users WHERE username = ? LIMIT 1');
const user = stmt.get(username);
return user || null;
}
function createUser(userId, username, hashedPassword) {
const stmt = db.prepare('INSERT INTO users (id, username, password) VALUES (?, ?, ?)');
stmt.run(userId, username, hashedPassword);
}
function updateUser(userId, username, hashedPassword) {
const stmt = db.prepare('UPDATE users SET username = ?, password = ? WHERE id = ?');
stmt.run(username, hashedPassword, userId);
}
// Cria sessão com id criptografado e timestamp atual
function createSession(userId) {
// Gera um ID aleatório (UUID ou random bytes)
const rawId = crypto.randomBytes(24).toString('hex');
// Criptografa com SHA256 para formar session_id
const sessionId = crypto.createHash('sha256').update(rawId).digest('hex');
const now = Math.floor(Date.now() / 1000); // timestamp UNIX em segundos
const stmt = db.prepare(`
INSERT INTO sessions (session_id, user_id, created_at)
VALUES (?, ?, ?)
`);
stmt.run(sessionId, userId, now);
return sessionId;
}
// Busca sessão pelo session_id
function getSession(sessionId) {
const stmt = db.prepare('SELECT * FROM sessions WHERE session_id = ? LIMIT 1');
return stmt.get(sessionId) || null;
}
// Deleta sessões antigas com created_at menor que timestamp limite
function deleteOldSessions(expirationTimestamp) {
const stmt = db.prepare('DELETE FROM sessions WHERE created_at <= ?');
const info = stmt.run(expirationTimestamp);
return info.changes;
}
function getSessionsByUserId(userId) {
const stmt = db.prepare('SELECT * FROM sessions WHERE user_id = ?');
return stmt.all(userId);
}
function deleteSession(sessionId) {
const stmt = db.prepare('DELETE FROM sessions WHERE session_id = ?');
return stmt.run(sessionId);
}
function getCardCodeByOwnerId(ownerId) {
const stmt = db.prepare('SELECT code FROM cards WHERE owner_id = ? LIMIT 1');
const row = stmt.get(ownerId);
return row ? row.code : null;
}
function listBackups(userId) {
const stmt = db.prepare(`
SELECT id, code, date FROM backups
WHERE userId = ?
ORDER BY date DESC
`);
return stmt.all(userId);
}
function deleteBackupByCode(code) {
const stmt = db.prepare('DELETE FROM backups WHERE code = ?');
return stmt.run(code);
}
function getBackupsByUserId(userId) {
const stmt = db.prepare('SELECT * FROM backups WHERE userId = ? ORDER BY created_at DESC');
return stmt.all(userId);
}
function insertBackupCode(userId, code) {
const stmt = db.prepare('INSERT INTO backups (userId, code, created_at) VALUES (?, ?, ?)');
const createdAt = Math.floor(Date.now() / 1000); // timestamp em segundos
return stmt.run(userId, code, createdAt);
}
// BILL API
function genUniqueBillId() {
let id;
do {
id = uuidv4();
} while (db.prepare('SELECT 1 FROM bills WHERE bill_id = ?').get(id));
return id;
}
// 3) Cria uma nova bill
function createBill(fromId, toId, amountStr, timestamp) {
const billId = genUniqueBillId();
db.prepare(`
INSERT INTO bills (bill_id, from_id, to_id, amount, date)
VALUES (?, ?, ?, ?, ?)
`).run(billId, fromId, toId, amountStr, timestamp);
return billId;
}
// 4) Recupera uma bill
function getBill(billId) {
return db.prepare('SELECT * FROM bills WHERE bill_id = ?').get(billId) || null;
}
// 5) Remove uma bill
function deleteBill(billId) {
return db.prepare('DELETE FROM bills WHERE bill_id = ?').run(billId);
}
// 6) Lista bills de um usuário (opcional)
function listBillsByUser(userId, role = 'from') {
const col = role === 'to' ? 'to_id' : 'from_id';
return db.prepare(`SELECT * FROM bills WHERE ${col} = ? ORDER BY date DESC`).all(userId);
}
/**
* Alias para uso direto em logic.js:
* expõe a mesma implementação de getCooldown como dbGetCooldown
*/
function dbGetCooldown(id) {
return getCooldown(id);
}
// === Limpeza automática de histórico antigo (90 dias) ===
function cleanOldTransactions(maxAgeMs = 30 * 24 * 60 * 60 * 1000) {
const cutoff = Date.now() - maxAgeMs;
const info = db.prepare(`
DELETE FROM transactions
WHERE strftime('%s', date) * 1000 < ?
`).run(cutoff);
return info.changes;
}
function getTransactionById(txId) {
if (!txId) return null;
try {
// se seu db for better-sqlite3 e a variável for `db`:
const row = db.prepare('SELECT id, date, from_id, to_id, amount FROM transactions WHERE id = ?').get(txId);
return row || null;
} catch (err) {
console.error('⚠️ getTransactionById error:', err);
return null;
}
}
function transferAtomic(fromId, toId, sats) {
return db.transaction(() => {
// pega usuários
const from = getUser(fromId);
const to = getUser(toId);
if (!from) throw new Error('Sender not found');
if (!to) throw new Error('Receiver not found');
if (from.coins < sats) throw new Error('Insufficient funds');
// atualiza saldos
setCoins(fromId, from.coins - sats);
setCoins(toId, to.coins + sats);
// registra transação (ownerId -> targetId)
const tx = genAndCreateTransaction(fromId, toId, sats);
return tx;
})();
}
/**
* Concede uma recompensa ao usuário de forma atômica:
* - adiciona coins
* - atualiza cooldown
* - atualiza notified
* - registra a transação (system -> user)
*
* @param {string} userId
* @param {number} sats quantidade em satoshis (INTEGER)
* @returns {{ txId: string, date: string }} info da transação criada
*/
function claimReward(userId, sats) {
// usa better-sqlite3 db.transaction para garantir atomicidade
return db.transaction((userId, sats) => {
// garante existência do usuário (getUser cria se não existir)
const user = getUser(userId);
if (!user) throw new Error('User not found (claimReward)');
// atualiza saldo e cooldown/notified
addCoins(userId, sats);
setCooldown(userId, Date.now());
setNotified(userId, false);
// registra transação (system id '000000000000' -> userId)
// usa genAndCreateTransaction que gera um txId único
const tx = genAndCreateTransaction('000000000000', userId, sats);
return tx;
})(userId, sats);
}
function getBackupCodes(userId) {
try {
const stmt = db.prepare("SELECT code FROM backups WHERE userId = ?");
const rows = stmt.all(userId);
return rows.map(r => r.code);
} catch (err) {
console.error("❌ [database.js] getBackupCodes error:", err);
return [];
}
}
// database.js
function addBackupCode(userId, code) {
try {
// garante a ordem: (code, userId)
const stmt = db.prepare("INSERT OR IGNORE INTO backups (code, userId) VALUES (?, ?)");
const info = stmt.run(code, userId);
// info.changes = 1 se inseriu; 0 se IGNORE (duplicata)
return { ok: true, changes: info && typeof info.changes === 'number' ? info.changes : 0 };
} catch (err) {
console.error("❌ [database.js] addBackupCode error:", err);
return { ok: false, error: err.message || String(err) };
}
}
// Exemplo mínimo (síncrono/assíncrono conforme sua DB lib):
async function getBillsTo(userId, page = 1, pageSize = 50) {
// retornar array: [{ id, from_id, to_id, amount, date }, ...]
}
async function getBillsFrom(userId, page = 1, pageSize = 50) {
// retornar array: [{ id, from_id, to_id, amount, date }, ...]
}
// database.js (exemplo)
function logTransaction(id, date, fromId, toId, amount) {
try {
const stmt = db.prepare(`
INSERT INTO transactions(id, date, from_id, to_id, amount)
VALUES (?, ?, ?, ?, ?)
`);
stmt.run(id, date, fromId, toId, amount);
return true;
} catch (err) {
console.error('❌ [database.js] logTransaction error:', err);
return false;
}
}
// Exemplos com better-sqlite3 (síncrono). Ajuste se usar API assíncrona.
function getTotalCoins() {
try {
const row = db.prepare('SELECT IFNULL(SUM(coins), 0) AS sum FROM users').get();
return row ? row.sum : 0;
} catch (err) {
console.error('❌ [database.js] getTotalCoins error:', err);
return 0;
}
}
function getTransactionCount() {
try {
const row = db.prepare('SELECT COUNT(*) AS cnt FROM transactions').get();
return row ? row.cnt : 0;
} catch (err) {
console.error('❌ [database.js] getTransactionCount error:', err);
return 0;
}
}
function getClaimCount() {
try {
const row = db.prepare("SELECT COUNT(*) AS cnt FROM transactions WHERE from_id = '000000000000'").get();
return row ? row.cnt : 0;
} catch (err) {
console.error('❌ [database.js] getClaimCount error:', err);
return 0;
}
}
function getUserCount() {
try {
const row = db.prepare('SELECT COUNT(*) AS cnt FROM users').get();
return row ? row.cnt : 0;
} catch (err) {
console.error('❌ [database.js] getUserCount error:', err);
return 0;
}
}
function getBillCount() {
try {
const row = db.prepare('SELECT COUNT(*) AS cnt FROM bills').get();
return row ? row.cnt : 0;
} catch (err) {
console.error('❌ [database.js] getBillCount error:', err);
return 0;
}
}
// === Transaction helpers required by commands/history.js ===
/**
* Conta transações para um usuário (from_id = user OR to_id = user)
* @param {string} userId
* @returns {number}
*/
function countTransactionsForUser(userId) {
try {
const row = db.prepare(`
SELECT COUNT(*) AS cnt
FROM transactions
WHERE from_id = ? OR to_id = ?
`).get(userId, userId);
return row ? Number(row.cnt) : 0;
} catch (err) {
console.error('❌ [database.js] countTransactionsForUser error:', err);
return 0;
}
}
/**
* Busca transações do usuário (paginação)
* @param {string} userId
* @param {number} limit
* @param {number} offset
* @returns {Array<{id,date,from_id,to_id,amount}>}
*/
function getTransactionsForUser(userId, limit = 100, offset = 0) {
try {
return db.prepare(`
SELECT id, date, from_id, to_id, amount
FROM transactions
WHERE from_id = ? OR to_id = ?
ORDER BY date DESC
LIMIT ? OFFSET ?
`).all(userId, userId, limit, offset);
} catch (err) {
console.error('❌ [database.js] getTransactionsForUser error:', err);
return [];
}
}
/**
* Deduplica transações do usuário (mesma lógica que o comando history usava).
* Remove linhas duplicadas (mesma date, amount, from_id, to_id) mantendo a menor rowid.
* @param {string} userId
* @returns {{ changes?: number }}
*/
function dedupeUserTransactions(userId) {
try {
const info = db.prepare(`
DELETE FROM transactions
WHERE rowid NOT IN (
SELECT MIN(rowid)
FROM transactions
WHERE from_id = ? OR to_id = ?
GROUP BY date, amount, from_id, to_id
)
AND (from_id = ? OR to_id = ?)
`).run(userId, userId, userId, userId);
return info || {};
} catch (err) {
console.warn('⚠️ [database.js] dedupeUserTransactions failed:', err);
return {};
}
}
/**
* transferAtomicWithTxId(fromId, toId, sats, txId)
* - Realiza a transferência de sats entre contas de forma atômica e registra
* uma transação com o ID fornecido (txId).
* - Se fromId === toId (self-pay), não altera saldos, mas registra a transação.
*
* @param {string} fromId
* @param {string} toId
* @param {number} sats quantidade em satoshis (INTEGER)
* @param {string} txId id utilizado para a transação (ex: billId)
* @returns {{ txId: string, date: string }} info da transação criada
*/
function transferAtomicWithTxId(fromId, toId, sats, txId) {
return db.transaction((fromId, toId, sats, txId) => {
const from = getUser(fromId);
const to = getUser(toId);
if (!from) throw new Error('Sender not found');
if (!to) throw new Error('Receiver not found');
if (fromId !== toId) {
if (from.coins < sats) throw new Error('Insufficient funds');
// atualiza saldos
setCoins(fromId, from.coins - sats);
setCoins(toId, to.coins + sats);
}
// registra transação com o ID fornecido
const date = new Date().toISOString();
try {
db.prepare(`
INSERT INTO transactions (id, date, from_id, to_id, amount)
VALUES (?, ?, ?, ?, ?)
`).run(txId, date, fromId, toId, sats);
} catch (err) {
// se falhar ao inserir a transação, lança para reverter a transação outer (db.transaction)
throw err;
}
return { txId, date };
})(fromId, toId, sats, txId);
}
// database.js — adicionar estas funções (síncronas, para better-sqlite3)
/**
* Reseta a sequência autonumérica da tabela dm_queue (opcional).
* Mantém essa operação dentro de database.js para encapsular acesso ao DB.
*/
function resetDmQueueSequence() {
try {
// só tenta quando a tabela existir (silencioso em caso de erro)
db.prepare(`UPDATE sqlite_sequence SET seq = 0 WHERE name='dm_queue'`).run();
return true;
} catch (err) {
// log leve — não deve quebrar o processamento de DMs
// console.warn('resetDmQueueSequence failed:', err);
return false;
}
}
function getUserGraphData(userId) {
try {
let row = db.prepare(`
SELECT * FROM user_grafic
WHERE user_id = ?
`).get(userId);
if (!row) {
db.prepare(`
INSERT INTO user_grafic (user_id)
VALUES (?)
`).run(userId);
row = db.prepare(`
SELECT * FROM user_grafic
WHERE user_id = ?
`).get(userId);
}
const labels = [];
const values = [];
for (let i = 1; i <= 30; i++) {
labels.push(`Day ${i}`);
values.push(Number(row[`d${i}`] || 0));
}
return { labels, values };
} catch (err) {
console.error('❌ [database.js] getUserGraphData error:', err);
return { labels: [], values: [] };
}
}
// --- já deve existir no seu database.js, mas caso não exista: ---
// getNextDM()
// deleteDM()
// Essas já estavam sendo usadas por dmQueue.js; se não existirem, implemente assim:
function getNextDM() {
return db.prepare(`
SELECT id, user_id, embed_json, row_json, created_at
FROM dm_queue
ORDER BY id
LIMIT 1
`).get();
}
function deleteDM(id) {
return db.prepare('DELETE FROM dm_queue WHERE id = ?').run(id);
}
// ######################### DB helpers a adicionar #########################
/**
* IP helpers (type = 1 => login tries)
*/
function getIpRecord(ip_address) {
return db.prepare('SELECT try, time FROM ips WHERE ip_address = ? AND type = 1').get(ip_address) || null;
}
function insertIpTry(ip_address, type, time) {
return db.prepare('INSERT INTO ips (ip_address, type, time, try) VALUES (?, ?, ?, 1)').run(ip_address, type, time);
}
function updateIpTry(ip_address, tryCount, time) {
return db.prepare('UPDATE ips SET try = ?, time = ? WHERE ip_address = ? AND type = 1').run(tryCount, time, ip_address);
}
function updateIpTime(ip_address, time) {
return db.prepare('UPDATE ips SET time = ? WHERE ip_address = ? AND type = 1').run(time, ip_address);
}
function deleteIpType1(ip_address) {
return db.prepare('DELETE FROM ips WHERE ip_address = ? AND type = 1').run(ip_address);
}
/**
* Check if userId exists (uses users table) — used instead of raw SELECT 1
*/
function userIdExists(userId) {
const row = db.prepare('SELECT 1 FROM users WHERE id = ?').get(userId);
return !!row;
}
/**
* Retorna data da última transação enviada por um usuário (ISO string) ou null
*/
function getLastTransactionDate(userId) {