-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
611 lines (503 loc) · 13.7 KB
/
db.go
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
package main
import (
"database/sql"
"fmt"
"log"
"net"
"strconv"
"time"
_ "github.com/mattn/go-sqlite3"
)
// Default max number of arguments for an SQLite query
const SQLITE_MAX_VARIABLE_NUMBER = 999
// Special values for ids
const (
ID_UNKNOWN = 0 // The state of the node in the DB is unknown
ID_NOT_IN_DB = -1 // The node was not found in the DB
)
type ip_port struct {
ip string
port string
}
type nodeDB struct {
node *Node
tx *sql.Tx
now int64 // Current time for updated_at, next_refresh..
dbInfo dbNodeInfo
dbNeighbours map[string]dbNeighbourInfo // Key is joined IP/Port
}
// Node attributes which are stored in the DB
type dbNodeInfo struct {
id int64
ip string
port string
protocol int
user_agent string
next_refresh int64
online bool
online_at int64
success bool
success_at int64
}
// Node neighbour partial attributes stored in the DB
type dbNeighbourInfo struct {
id int64
next_refresh int64
}
// In schemas, type DATE is used instead of DATETIME so that the sqlite driver
// does not try to convert the underlying int to a time.Time. SQLite considers
// both types as NUMERIC (see http://www.sqlite.org/datatype3.html)
const INIT_SCHEMA_NODES = `
CREATE TABLE IF NOT EXISTS "nodes" (
"id" INTEGER PRIMARY KEY AUTOINCREMENT,
"ip" TEXT NOT NULL,
"port" INTEGER NOT NULL,
"protocol" INTEGER NOT NULL DEFAULT 0,
"user_agent" TEXT DEFAULT '',
"online" BOOLEAN NOT NULL DEFAULT 0,
"success" BOOLEAN NOT NULL DEFAULT 0,
"next_refresh" DATE NOT NULL DEFAULT 0,
"online_at" DATE NOT NULL DEFAULT 0, -- Move to seperate table ?
"success_at" DATE NOT NULL DEFAULT 0,
"created_at" DATE NOT NULL DEFAULT (strftime('%s', 'now')),
"updated_at" DATE NOT NULL,
UNIQUE (ip, port)
);
`
const INIT_SCHEMA_NODES_KNOWN = `
CREATE TABLE IF NOT EXISTS "nodes_known" (
"id" INTEGER PRIMARY KEY,
"id_source" INTEGER,
"id_known" INTEGER,
"created_at" DATE DEFAULT (strftime('%s', 'now')),
"updated_at" DATE,
UNIQUE (id_source, id_known)
);
`
const INDEX_IP_PORT = "CREATE INDEX IF NOT EXISTS node_ip_port ON nodes (ip, port);"
const INDEX_SOURCE_KNOWN = "CREATE INDEX IF NOT EXISTS nodes_known_source_known ON nodes_known (id_source, id_known);"
var dbConnectionPool chan *sql.DB
// Initialize pool of DB connections
func initDB() (err error) {
log.Print("Initializing DB connections")
dbConnectionPool = make(chan *sql.DB, NUM_DB_CONN)
for i := 0; i < NUM_DB_CONN; i++ {
db, err := sql.Open("sqlite3", "data.db")
if err != nil {
return err
}
if _, err = db.Exec("PRAGMA journal_mode=WAL;"); err != nil {
log.Fatal("Failed to Exec PRAGMA journal_mode:", err)
}
dbConnectionPool <- db
}
db := acquireDBConn()
defer releaseDBConn(db)
setupDB(db)
return
}
// Set up the database schema
func setupDB(db *sql.DB) {
for _, q := range []string{
INIT_SCHEMA_NODES,
INIT_SCHEMA_NODES_KNOWN,
INDEX_IP_PORT,
INDEX_SOURCE_KNOWN,
} {
_, err := db.Exec(q)
if err != nil {
logQueryError(q, err)
}
}
}
// Clean up pool of DB connections
func cleanDB() {
log.Print("Cleaning up DB connections")
for i := 0; i < NUM_DB_CONN; i++ {
db := <-dbConnectionPool
db.Close()
}
}
// Get a connection from the pool of DB connections
func acquireDBConn() (db *sql.DB) {
return <-dbConnectionPool
}
// Release a connection back to the pool of DB connections
func releaseDBConn(db *sql.DB) {
dbConnectionPool <- db
}
// Returns whether there are nodes in the DB which can be used to crawl the
// bitcoin network
func haveKnownNodes() bool {
db := acquireDBConn()
defer releaseDBConn(db)
row := db.QueryRow(`SELECT COUNT(*)
FROM nodes
WHERE success = 1`)
var count int
err := row.Scan(&count)
if err != nil {
log.Fatal(err)
}
return count != 0
}
// Retrieves addresses which need to be updated
func addressesToUpdate() (addresses []ip_port, max int) {
db := acquireDBConn()
defer releaseDBConn(db)
query := fmt.Sprintf(`SELECT ip, port
FROM nodes
WHERE port!=0
AND next_refresh != 0
AND next_refresh < strftime('%%s', 'now')
ORDER BY next_refresh
LIMIT %d`, ADDRESSES_NUM)
rows, err := db.Query(query)
if err != nil {
logQueryError(query, err)
}
var ip, port string
addresses = make([]ip_port, 0, ADDRESSES_NUM)
for rows.Next() {
rows.Scan(&ip, &port)
// if verbose {
// log.Print("Getting ", ip, " ", port)
// }
addresses = append(addresses, ip_port{ip: ip, port: port})
}
// Get max count
query = `SELECT COUNT(*)
FROM nodes
WHERE port!=0
AND next_refresh != 0
AND next_refresh < strftime('%s', 'now')`
row := db.QueryRow(query)
err = row.Scan(&max)
if err != nil {
logQueryError(query, err)
}
return addresses, max
}
// Save the node to the database
func (node *Node) Save(db *sql.DB) (err error) {
dbnode := nodeDB{node: node}
return dbnode.Save(db)
}
// Save or the node to the database. The relation to other nodes is also saved.
func (n *nodeDB) Save(db *sql.DB) (err error) {
n.dbInfo = dbNodeInfo{
ip: n.node.NetAddr.IP.String(),
port: strconv.Itoa(int(n.node.NetAddr.Port)),
}
if n.node.Version != nil {
if n.node.Version.UserAgent != "" || len(n.node.Addresses) > 0 {
log.Print(n.node.Version.UserAgent, " ", len(n.node.Addresses),
" peers ", n.dbInfo.ip, " ", n.dbInfo.port)
}
}
n.tx, err = db.Begin()
if err != nil {
log.Fatal(err)
}
defer n.tx.Rollback()
// Get existing information from current node if any
n.dbGetNode()
// Update last updated time
n.now = time.Now().Unix()
//Was able to connect to node
if n.node.Conn == nil {
n.dbInfo.online = false
n.dbInfo.next_refresh = 0 // stop updating node
} else {
n.dbInfo.online = true
n.dbInfo.online_at = n.now
n.dbInfo.next_refresh = n.now + (NODE_REFRESH_INTERVAL * 3600)
}
// Was able initiate communication with node
if n.node.Version != nil {
n.dbInfo.protocol = int(n.node.Version.Protocol)
n.dbInfo.user_agent = n.node.Version.UserAgent
n.dbInfo.success = true
n.dbInfo.success_at = n.now
} else {
n.dbInfo.success = false
}
n.dbPutNode()
// Update neighbour nodes
// Initialize struct and get existing information on neighnours, if any
n.dbGetNeighbours()
// Update next_refresh if necessary
for _, addr := range n.node.Addresses {
canon_addr := net.JoinHostPort(addr.IP.String(), strconv.Itoa(int(addr.Port)))
neigh := n.dbNeighbours[canon_addr]
if neigh.next_refresh < n.now {
neigh.next_refresh = n.dbInfo.next_refresh
n.dbNeighbours[canon_addr] = neigh
}
}
n.dbPutNeighbours()
err = n.tx.Commit()
if err != nil {
log.Fatal(err)
}
return
}
// Retrive database information about a single node
func (n *nodeDB) dbGetNode() {
if n.tx == nil {
log.Fatal("Transaction not initialized")
}
// Get dates with strftime to get timestamps
query := `SELECT id, protocol, user_agent, online, online_at,
success, success_at, next_refresh
FROM nodes
WHERE ip=?
AND port=?`
row := n.tx.QueryRow(query, n.dbInfo.ip, n.dbInfo.port)
err := row.Scan(&(n.dbInfo.id), &(n.dbInfo.protocol), &(n.dbInfo.user_agent),
&(n.dbInfo.online), &(n.dbInfo.online_at),
&(n.dbInfo.success), &(n.dbInfo.success_at),
&(n.dbInfo.next_refresh))
// Ignore if err if node does not exist
switch {
case err == sql.ErrNoRows:
n.dbInfo.id = -1
case err != nil:
logQueryError(query, err)
}
}
// Retrieve only the id for the given node
func (n *nodeDB) dbGetNodeId() {
if n.tx == nil {
log.Fatal("Transaction not initialized")
}
// Get dates with strftime to get timestamps
query := `SELECT id
FROM nodes
WHERE ip=?
AND port=?`
row := n.tx.QueryRow(query, n.dbInfo.ip, n.dbInfo.port)
err := row.Scan(&(n.dbInfo.id))
// Ignore if err if node does not exist
switch {
case err == sql.ErrNoRows:
n.dbInfo.id = -1
case err != nil:
logQueryError(query, err)
}
}
// Save a node to the DB and store its id
func (n *nodeDB) dbPutNode() {
if n.tx == nil {
log.Fatal("Transaction not initialized")
}
// Retrieve info from DB if state unknown
if n.dbInfo.id == ID_UNKNOWN {
n.dbGetNodeId()
}
var (
err error
query string
)
params := [11]interface{}{n.dbInfo.ip, n.dbInfo.port, n.dbInfo.next_refresh,
n.dbInfo.protocol, n.dbInfo.user_agent,
n.dbInfo.online, n.dbInfo.online_at,
n.dbInfo.success, n.dbInfo.success_at,
n.now, 0}
if n.dbInfo.id == ID_NOT_IN_DB {
query = `INSERT INTO nodes (ip, port, next_refresh, protocol, user_agent,
online, online_at, success, success_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
_, err = n.tx.Exec(query, params[:10]...)
} else {
query = `UPDATE nodes SET ip=?, port=?, next_refresh=?, protocol=?,
user_agent=?, online=?, online_at=?, success=?, success_at=?,
updated_at=?
WHERE id=?`
params[10] = n.dbInfo.id
_, err = n.tx.Exec(query, params[:11]...)
}
if err != nil {
logQueryError(query, err)
}
// Retrieve the inserted row's id if previously unknown
if n.dbInfo.id == ID_UNKNOWN || n.dbInfo.id == ID_NOT_IN_DB {
n.dbGetNode()
}
}
// Gets id and next_refresh for neighbour nodes. Stores in n.dbNeighbours
// Uses prepared statements insted of creating one big query
func (n *nodeDB) dbGetNeighbours() {
if n.node.Addresses == nil {
return
}
var init = (n.dbNeighbours == nil)
// Initialize neighbours map if this is the first call to dbGetNeighbours
if init {
n.dbNeighbours = make(map[string]dbNeighbourInfo)
}
// Prepare query
query := "SELECT id, next_refresh FROM nodes WHERE ip=? AND port=?"
stmt, err := n.tx.Prepare(query)
if err != nil {
logQueryError(query, err)
}
defer stmt.Close()
var (
row *sql.Row
neigh dbNeighbourInfo
canon_addr string
id int64
ip string
port string
next_refresh int64
)
// Retrieve neighbour information
for i := 0; i < len(n.node.Addresses); i++ {
ip = n.node.Addresses[i].IP.String()
port = strconv.Itoa(int(n.node.Addresses[i].Port))
canon_addr = net.JoinHostPort(ip, port)
row = stmt.QueryRow(ip, port)
err = row.Scan(&id, &next_refresh)
switch {
case err == sql.ErrNoRows:
neigh = dbNeighbourInfo{
id: ID_NOT_IN_DB,
}
case err != nil:
// Unexpected DB error
log.Fatal(err)
default:
if !init {
// Update existing
neigh = n.dbNeighbours[canon_addr]
neigh.id = id
neigh.next_refresh = next_refresh
} else {
// Create new
neigh = dbNeighbourInfo{
id: id,
next_refresh: next_refresh,
}
}
}
n.dbNeighbours[canon_addr] = neigh
}
}
// Update neighbour nodes and relations in DB
func (n *nodeDB) dbPutNeighbours() {
if len(n.dbNeighbours) == 0 {
return
}
if n.dbInfo.id == ID_UNKNOWN || n.dbInfo.id == ID_NOT_IN_DB {
n.dbGetNodeId()
if n.dbInfo.id == ID_UNKNOWN || n.dbInfo.id == ID_NOT_IN_DB {
log.Fatal("Attempted to insert neighbours for a node which is not in DB")
}
}
// Prepare node queries
select_node_query := "SELECT id FROM nodes WHERE ip=? AND port=?"
select_node_stmt, err := n.tx.Prepare(select_node_query)
if err != nil {
logQueryError(select_node_query, err)
}
defer select_node_stmt.Close()
insert_node_query := "INSERT INTO nodes (ip, port, next_refresh, updated_at) VALUES (?, ?, ?, ?)"
insert_node_stmt, err := n.tx.Prepare(insert_node_query)
if err != nil {
logQueryError(insert_node_query, err)
}
defer insert_node_stmt.Close()
update_node_query := "UPDATE nodes SET next_refresh=?, updated_at=? WHERE id=?"
update_node_stmt, err := n.tx.Prepare(update_node_query)
if err != nil {
logQueryError(update_node_query, err)
}
defer update_node_stmt.Close()
// Prepare known nodes queries
select_known_query := "SELECT id FROM nodes_known WHERE id_source=? AND id_known=?"
select_known_stmt, err := n.tx.Prepare(select_known_query)
if err != nil {
logQueryError(select_known_query, err)
}
defer select_known_stmt.Close()
insert_known_query := "INSERT INTO nodes_known (id_source, id_known, updated_at) VALUES (?, ?, ?)"
insert_known_stmt, err := n.tx.Prepare(insert_known_query)
if err != nil {
logQueryError(insert_known_query, err)
}
defer insert_known_stmt.Close()
update_known_query := "UPDATE nodes_known SET updated_at=? WHERE id=?"
update_known_stmt, err := n.tx.Prepare(update_known_query)
if err != nil {
logQueryError(update_known_query, err)
}
defer update_known_stmt.Close()
// Insert nodes
var (
row *sql.Row
id_rel int64
ip string
port string
)
for hostport, info := range n.dbNeighbours {
ip, port, err = net.SplitHostPort(hostport)
if err != nil {
log.Fatal(err)
}
// Check if node is in DB if currently unknown
if info.id == ID_UNKNOWN {
row = select_node_stmt.QueryRow(ip, port)
err = row.Scan(&(info.id))
switch {
case err == sql.ErrNoRows:
info.id = ID_NOT_IN_DB
case err != nil:
// Unexpected DB error
log.Fatal(err)
}
}
// Insert/update node in DB
if info.id == ID_NOT_IN_DB {
// insert
_, err = insert_node_stmt.Exec(ip, port, info.next_refresh, n.now)
if err != nil {
log.Fatal(err)
}
// retrieve new id
row = select_node_stmt.QueryRow(ip, port)
err = row.Scan(&(info.id))
if err != nil {
log.Fatal(err)
}
} else {
//update
_, err = update_node_stmt.Exec(info.next_refresh, n.now, info.id)
if err != nil {
log.Fatal(err)
}
}
// insert/update known nodes relation
row = select_known_stmt.QueryRow(n.dbInfo.id, info.id)
err = row.Scan(&id_rel)
switch {
case err == sql.ErrNoRows:
_, err = insert_known_stmt.Exec(n.dbInfo.id, info.id, n.now)
if err != nil {
log.Fatal(err)
}
case err != nil:
log.Fatal(err)
default:
_, err = update_known_stmt.Exec(n.now, id_rel)
if err != nil {
log.Fatal(err)
}
}
}
}
// Log a query error. Calls os.Exit(1)
func logQueryError(query string, err error) {
log.Print(query)
log.Fatal(err)
}