-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathdatabase.py
More file actions
134 lines (107 loc) · 2.77 KB
/
database.py
File metadata and controls
134 lines (107 loc) · 2.77 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
# coding:utf-8
import json
import os
BASEDBPATH = 'data'
BLOCKFILE = 'blockchain'
TXFILE = 'tx'
UNTXFILE = 'untx'
ACCOUNTFILE = 'account'
NODEFILE = 'node'
class BaseDB():
filepath = ''
def __init__(self):
self.set_path()
self.filepath = '/'.join((BASEDBPATH, self.filepath))
def set_path(self):
pass
def find_all(self):
return self.read()
def insert(self, item):
self.write(item)
def read(self):
raw = ''
if not os.path.exists(self.filepath):
return []
with open(self.filepath,'r+') as f:
raw = f.readline()
if len(raw) > 0:
data = json.loads(raw)
else:
data = []
return data
def write(self, item):
data = self.read()
if isinstance(item,list):
data = data + item
else:
data.append(item)
with open(self.filepath,'w+') as f:
f.write(json.dumps(data))
return True
def clear(self):
with open(self.filepath,'w+') as f:
f.write('')
def hash_insert(self, item):
exists = False
for i in self.find_all():
if item['hash'] == i['hash']:
exists = True
break
if not exists:
self.write(item)
class NodeDB(BaseDB):
def set_path(self):
self.filepath = NODEFILE
class AccountDB(BaseDB):
def set_path(self):
self.filepath = ACCOUNTFILE
def find_one(self):
ac = self.read()
return ac[0]
class BlockChainDB(BaseDB):
def set_path(self):
self.filepath = BLOCKFILE
def last(self):
bc = self.read()
if len(bc) > 0:
return bc[-1]
else:
return []
def find(self, hash):
one = {}
for item in self.find_all():
if item['hash'] == hash:
one = item
break
return one
def insert(self, item):
self.hash_insert(item)
class TransactionDB(BaseDB):
"""
Transactions that save with blockchain.
"""
def set_path(self):
self.filepath = TXFILE
def find(self, hash):
one = {}
for item in self.find_all():
if item['hash'] == hash:
one = item
break
return one
def insert(self, txs):
if not isinstance(txs,list):
txs = [txs]
for tx in txs:
self.hash_insert(tx)
class UnTransactionDB(TransactionDB):
"""
Transactions that doesn't store in blockchain.
"""
def set_path(self):
self.filepath = UNTXFILE
def all_hashes(self):
hashes = []
for item in self.find_all():
hashes.append(item['hash'])
return hashes