raw
genesis                 1 from lib.peer import Peer
genesis 2 import sqlite3
genesis 3 import imp
genesis 4 import hashlib
genesis 5 from itertools import chain
genesis 6
genesis 7 class State(object):
genesis 8
genesis 9 def __init__(self, server, db_path):
genesis 10 self.server = server
genesis 11 self.conn = sqlite3.connect(db_path)
genesis 12 self.cursor = self.conn.cursor()
genesis 13 self.cursor.execute("create table if not exists at(handle_id integer,\
genesis 14 address text not null,\
genesis 15 port integer not null,\
9991-improved-log... 16 active_at datetime default null,\
genesis 17 updated_at datetime default current_timestamp,\
genesis 18 unique(handle_id, address, port))")
genesis 19
genesis 20 self.cursor.execute("create table if not exists wot(peer_id integer primary key)")
genesis 21
genesis 22 self.cursor.execute("create table if not exists handles(handle_id integer primary key,\
genesis 23 peer_id integer,\
genesis 24 handle text,\
genesis 25 unique(handle))")
genesis 26
genesis 27 self.cursor.execute("create table if not exists keys(peer_id intenger,\
genesis 28 key text,\
genesis 29 used_at datetime default current_timestamp,\
genesis 30 unique(key))")
genesis 31
genesis 32 self.cursor.execute("create table if not exists logs(\
genesis 33 handle text not null,\
genesis 34 peer_id integer,\
genesis 35 message_bytes blob not null,\
genesis 36 created_at datetime default current_timestamp)")
genesis 37
genesis 38 def get_at(self, handle=None):
genesis 39 at = []
genesis 40 if handle == None:
9991-improved-log... 41 results = self.cursor.execute("select handle_id,address,port,active_at from at\
genesis 42 order by updated_at desc").fetchall()
genesis 43 else:
9992-handle-edge-... 44 result = self.cursor.execute("select handle_id from handles where handle=?",
9992-handle-edge-... 45 (handle,)).fetchone()
9992-handle-edge-... 46 if None != result:
9992-handle-edge-... 47 handle_id = result[0]
genesis 48 else:
genesis 49 return []
9991-improved-log... 50 results = self.cursor.execute("select handle_id,address,port,active_at from at \
9992-handle-edge-... 51 where handle_id=? order by updated_at desc",
9992-handle-edge-... 52 (handle_id,)).fetchall()
genesis 53 for result in results:
genesis 54 handle_id, address, port, updated_at = result
genesis 55 h = self.cursor.execute("select handle from handles where handle_id=?",
genesis 56 (handle_id,)).fetchone()[0]
genesis 57 at.append({"handle": h,
genesis 58 "address": "%s:%s" % (address, port),
9991-improved-log... 59 "active_at": updated_at})
genesis 60 return at
genesis 61
genesis 62
genesis 63 def get_last_message_hash(self, handle, peer_id=None):
genesis 64 if peer_id:
genesis 65 message_bytes = self.cursor.execute("select message_bytes from logs\
genesis 66 where handle=? and peer_id=?\
genesis 67 order by created_at desc limit 1",
genesis 68 (handle, peer_id)).fetchone()
genesis 69
genesis 70 else:
genesis 71 message_bytes = self.cursor.execute("select message_bytes from logs\
genesis 72 where handle=? and peer_id is null\
genesis 73 order by created_at desc limit 1",
genesis 74 (handle,)).fetchone()
genesis 75
genesis 76 if message_bytes:
genesis 77 return hashlib.sha256(message_bytes[0][:]).digest()
genesis 78 else:
genesis 79 return "0" * 32
genesis 80
genesis 81 def log(self, handle, message_bytes, peer_id=None):
genesis 82 self.cursor.execute("insert into logs(handle, peer_id, message_bytes)\
genesis 83 values(?, ?, ?)",
genesis 84 (handle, peer_id, buffer(message_bytes)))
genesis 85
genesis 86 def import_at_and_wot(self, at_path):
genesis 87 wot = imp.load_source('wot', at_path)
genesis 88 for peer in wot.peers:
genesis 89 results = self.cursor.execute("select * from handles where handle=? limit 1",
genesis 90 (peer["name"],)).fetchall()
genesis 91 if len(results) == 0:
genesis 92 key = peer["key"]
genesis 93 port = peer["port"]
genesis 94 address = peer["address"]
genesis 95 self.cursor.execute("insert into wot(peer_id) values(null)")
genesis 96 peer_id = self.cursor.lastrowid
genesis 97 self.cursor.execute("insert into handles(peer_id, handle) values(?, ?)",
genesis 98 (peer_id, peer["name"]))
genesis 99 handle_id = self.cursor.lastrowid
9991-improved-log... 100 self.cursor.execute("insert into at(handle_id, address, port, updated_at) values(?, ?, ?, ?)",
9991-improved-log... 101 (handle_id, peer["address"], peer["port"], None))
genesis 102 self.cursor.execute("insert into keys(peer_id, key) values(?, ?)",
genesis 103 (peer_id, key))
genesis 104
genesis 105 self.conn.commit()
genesis 106
9991-improved-log... 107 def update_address_table(self, peer, set_active_at=True):
genesis 108 row = self.cursor.execute("select handle_id from handles where handle=?",
genesis 109 (peer["handle"],)).fetchone()
genesis 110 if row != None:
genesis 111 handle_id = row[0]
genesis 112 else:
genesis 113 return
9991-improved-log... 114
genesis 115 try:
genesis 116 self.cursor.execute("insert into at(handle_id, address, port) values(?, ?, ?)",
genesis 117 (handle_id, peer["address"], peer["port"]))
genesis 118 except sqlite3.IntegrityError as ex:
genesis 119 self.cursor.execute("update at set updated_at = current_timestamp\
genesis 120 where handle_id=? and address=? and port=?",
genesis 121 (handle_id, peer["address"], peer["port"]))
9991-improved-log... 122 if set_active_at:
9991-improved-log... 123 self.cursor.execute("update at set active_at = current_timestamp\
9991-improved-log... 124 where handle_id=? and address=? and port=?",
9991-improved-log... 125 (handle_id, peer["address"], peer["port"]))
9991-improved-log... 126 self.conn.commit()
genesis 127
genesis 128 def add_peer(self, handle):
genesis 129 self.cursor.execute("insert into wot(peer_id) values(null)")
genesis 130 peer_id = self.cursor.lastrowid
genesis 131 self.cursor.execute("insert into handles(peer_id, handle) values(?, ?)",
genesis 132 (peer_id, handle))
genesis 133 self.conn.commit()
9991-improved-log... 134
genesis 135
genesis 136 def remove_peer(self, handle):
genesis 137 # get peer id
genesis 138
9992-handle-edge-... 139 result = self.cursor.execute("select peer_id from handles where handle=?", (handle,)).fetchone()
9992-handle-edge-... 140 if result == None:
9992-handle-edge-... 141 return
genesis 142 else:
9992-handle-edge-... 143 peer_id = result[0]
genesis 144 # get all aliases
genesis 145
genesis 146 handle_ids = self.get_handle_ids_for_peer(peer_id)
genesis 147 for handle_id in handle_ids:
genesis 148 # delete at entries for each alias
genesis 149
genesis 150 self.cursor.execute("delete from at where handle_id=?", (handle_id,))
genesis 151
genesis 152 self.cursor.execute("delete from handles where peer_id=?", (peer_id,))
genesis 153
genesis 154 # delete all keys for peer id
genesis 155
genesis 156 self.cursor.execute("delete from keys where peer_id=?", (handle_id,))
genesis 157
genesis 158 # delete peer from wot
genesis 159
genesis 160 self.cursor.execute("delete from wot where peer_id=?", (peer_id,))
genesis 161 self.conn.commit()
genesis 162
genesis 163
genesis 164 def add_key(self, handle, key):
genesis 165 peer_id = self.cursor.execute("select peer_id from handles where handle=?", (handle,)).fetchone()[0]
genesis 166 if peer_id != None:
genesis 167 self.cursor.execute("insert into keys(peer_id, key) values(?, ?)", (peer_id, key))
genesis 168 self.conn.commit()
genesis 169
genesis 170 def remove_key(self, key):
genesis 171 self.cursor.execute("delete from keys where key=?", (key,))
genesis 172 self.conn.commit()
genesis 173
genesis 174 def get_handle_ids_for_peer(self, peer_id):
genesis 175 return list(chain.from_iterable(self.cursor.execute("select handle_id from handles where peer_id=?",
genesis 176 (peer_id,)).fetchall()))
genesis 177
genesis 178 def get_peers(self):
genesis 179 peers = []
genesis 180 handles = self.cursor.execute("select handle from handles").fetchall()
genesis 181
genesis 182 for handle in handles:
genesis 183 peer = self.get_peer_by_handle(handle[0])
9992-handle-edge-... 184 if not (self.is_duplicate(peers, peer)):
genesis 185 peers.append(peer)
genesis 186 return peers
genesis 187
genesis 188 def get_peer_by_handle(self, handle):
genesis 189 handle_info = self.cursor.execute("select handle_id, peer_id from handles where handle=?",
genesis 190 (handle,)).fetchone()
genesis 191
genesis 192 if handle_info == None:
genesis 193 return None
genesis 194
genesis 195 address = self.cursor.execute("select address, port from at where handle_id=?\
genesis 196 order by updated_at desc limit 1",
genesis 197 (handle_info[0],)).fetchone()
genesis 198 handles = list(chain.from_iterable(self.cursor.execute("select handle from handles where peer_id=?",
genesis 199 (handle_info[1],)).fetchall()))
genesis 200 keys = list(chain.from_iterable(self.cursor.execute("select key from keys where peer_id=?\
genesis 201 order by used_at desc",
genesis 202 (handle_info[1],)).fetchall()))
genesis 203 return Peer(self.server, {
genesis 204 "handles": handles,
genesis 205 "peer_id": handle_info[1],
genesis 206 "address": address[0] if address else "",
genesis 207 "port": address[1] if address else "",
genesis 208 "keys": keys
genesis 209 })
genesis 210 def is_duplicate(self, peers, peer):
genesis 211 for existing_peer in peers:
genesis 212 if existing_peer.address == peer.address and existing_peer.port == peer.port:
genesis 213 return True
genesis 214 return False