Repository navigation
Expand file tree
/
Copy pathsqldb.py
More file actions
100 lines (92 loc) · 2.88 KB
/
Copy pathsqldb.py
File metadata and controls
100 lines (92 loc) · 2.88 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
import sqlite3
import logging
logger = logging.getLogger(__name__)
import block
import blockchain
databaseLocation = 'blocks/blockchain.db'
def dbConnect():
db = sqlite3.connect(databaseLocation)
cursor = db.cursor()
cursor.execute("""CREATE TABLE IF NOT EXISTS blocks (
id integer NOT NULL,
ctime text,
phash text,
hash text NOT NULL,
nonce integer,
mroot text,
tx text,
PRIMARY KEY (id, hash))""")
cursor.execute("""CREATE TABLE IF NOT EXISTS branches (
id integer NOT NULL,
ctime text,
phash text,
hash text NOT NULL,
nonce integer,
mroot text,
tx text,
PRIMARY KEY (id, hash),
FOREIGN KEY (id) REFERENCES blocks(hash))""")
db.commit()
db.close()
def dbCheck():
db = sqlite3.connect(databaseLocation)
cursor = db.cursor()
cursor.execute('SELECT * FROM blocks WHERE id = (SELECT MAX(id) FROM blocks)')
# Last block from own database
lastBlock_db = cursor.fetchone()
bc = blockchain.Blockchain(lastBlock_db)
# Empty database
if not lastBlock_db:
genesis = bc.getLastBlock()
writeBlock(genesis)
db.commit()
db.close()
return bc
def writeBlock(b):
db = sqlite3.connect(databaseLocation)
cursor = db.cursor()
try:
if isinstance(b, list):
cursor.executemany('INSERT INTO blocks VALUES (?,?,?,?,?,?,?)', b)
else:
cursor.execute('INSERT INTO blocks VALUES (?,?,?,?,?,?,?)', (
b.__dict__['index'],
b.__dict__['timestamp'],
b.__dict__['prev_hash'],
b.__dict__['hash'],
b.__dict__['nonce'],
b.__dict__['mroot'],
b.__dict__['tx']))
except sqlite3.IntegrityError:
logger.warning('db insert duplicated block')
finally:
db.commit()
db.close()
def blockQuery(messages):
db = sqlite3.connect(databaseLocation)
cursor = db.cursor()
cursor.execute('SELECT * FROM blocks WHERE id = ?', (messages[1],))
b = cursor.fetchone()
db.close()
return b
def blocksQuery(messages):
db = sqlite3.connect(databaseLocation)
cursor = db.cursor()
cursor.execute('SELECT * FROM blocks WHERE id BETWEEN ? AND ?', (messages[1],messages[2]))
l = cursor.fetchall()
db.close()
return l
def blocksListQuery(messages):
db = sqlite3.connect(databaseLocation)
cursor = db.cursor()
idlist = messages[1:]
#idlist = [int(i) for i in messages[1:]]
cursor.execute('SELECT * FROM blocks WHERE id IN ({0})'.format(', '.join('?' for _ in idlist)), idlist)
l = cursor.fetchall()
db.close()
return l
def dbtoBlock(b):
if isinstance(b, block.Block) or b is None:
return b
else:
return block.Block(b[0],b[2],b[4],b[3],b[1],b[6])