Skip to content

Commit

Permalink
Version 0.2.0 is a major update that I believe will work towards fixi…
Browse files Browse the repository at this point in the history
…ng all the problems zCoin has had in the past
  • Loading branch information
Max00355 committed Nov 28, 2013
1 parent 68e8b25 commit 77393f0
Show file tree
Hide file tree
Showing 14 changed files with 478 additions and 644 deletions.
101 changes: 34 additions & 67 deletions check_coin.py
@@ -1,84 +1,51 @@
import get_difficulty
import socket
import send_command
from rsa import PublicKey, encrypt
import time
import os
import json
from rsa import *
import hashlib
import base64
import sqlite3
import config
import hashlib
import re
import os
import time
import base64

def check_coin(obj, data):
"""
{"address":<addr>, "hash":<hash>, "starter":<starter>}
{"address":<addr>, "hash":<hash>, "starter":starter}
"""
check = sqlite3.connect("db.db").cursor()
check.execute("SELECT * FROM coins WHERE hash=?", [data['hash']])
if check.fetchall():
print "Coin already exists"
check = config.db.find("coins", {"hash":data['hash']})
if check:
print "Coin already exists."
return
node = sqlite3.connect("nodes.db").cursor()
c = node.execute("SELECT public FROM data WHERE address=?", [data['address']])
c = c.fetchall()
check.execute("SELECT level FROM difficulty")
difficulty = check.fetchall()[0][0]
if c:
c = c[0]
check_addr = config.nodes.find("nodes", {"address":data['address']})
difficulty = config.db.find("coins", "all")
if not difficulty:
difficulty = []
difficulty = len(difficulty)/50500 + 7
if difficulty < 7:
difficulty = 7

if check_addr:
c = check_addr[0]
if len(data['hash']) == 128:
if hashlib.sha512(str(data['starter'])).hexdigest() == data['hash'] and data['hash'].startswith("1"*int(difficulty)):
if c[0].startswith("PublicKey(") and c[0].endswith(")"):
key = re.findall("([0-9]*)", c[0])
key = filter(None, key)
key = PublicKey(int(key[0]), int(key[1]))
key = re.findall("([0-9]*)", c['public'])
key = filter(None, key)
key = PublicKey(int(key[0]), int(key[1]))
data['plain'] = data['starter']
data['starter'] = base64.b64encode(encrypt(str(data['starter']), key))
obj.send(json.dumps({"response":"Coin Confirmed!"}))
try:
out = sqlite3.connect("db.db").cursor()
out.execute("SELECT * FROM coins")
data['difficulty'] = len(out.fetchall())/205000 + 7
except TypeError:
data['difficulty'] = 7
send_confirm(data)
while os.path.exists("db.lock"):
time.sleep(0.1)
open("db.lock", 'w').close()
config.db.insert("coins", {"starter":data['starter'], "hash":data['hash'], "address":data['address'], "difficulty":difficulty})
config.db.save()
os.remove("db.lock")
else:
obj.send(json.dumps({"response":"Invalid Coin!"}))


def send_confirm(data):
nodes = sqlite3.connect("nodes.db").cursor()
nodes = nodes.execute("SELECT ip, port FROM data WHERE relay=1 AND version=?", [config.version])
nodes = nodes.fetchall()
for x in nodes:
s = socket.socket()
try:
s.settimeout(120)
s.connect((x[0], x[1]))
except:
continue
print "Invalid Coin!"
else:
data['cmd'] = "confirm_coin"
s.send(json.dumps(data))
s.close()

def confirm_coin(obj, data):
db_ = sqlite3.connect("db.db")
db = db_.cursor()
check = sqlite3.connect("db.db").cursor()
check.execute("SELECT level FROM difficulty")
difficulty = check.fetchall()[0][0]
db.execute("SELECT * FROM coins WHERE hash=?", [data['hash']])
if data['hash'].startswith("1"*int(difficulty)) and len(data['hash']) == 128 and not db.fetchall() and hashlib.sha512(data['plain']).hexdigest() == data['hash']:
while os.path.exists("db.lock"):
time.sleep(0.1)
open("db.lock", 'w')
db_.execute("UPDATE difficulty SET level=? WHERE level=?", [data['difficulty'], difficulty])
db_.execute("INSERT INTO coins (starter, hash, address) VALUES (?, ?, ?)", [data['starter'], data['hash'], data['address']])
db_.commit()
os.remove("db.lock")
print "Hash not long enough"
else:
return

print "Addr invalid."
29 changes: 29 additions & 0 deletions coin_count.py
@@ -0,0 +1,29 @@
import config
import json
import send_command
import get_db

def coin_count(obj, data):
coins = config.db.find("coins", "all")
if coins:
obj.send(json.dumps({"coins":len(coins)}))
else:
obj.send(json.dumps({"coins":0}))

def send():
coins = config.db.find("coins", "all")
if coins:
coins = len(coins)
else:
coins = 0
out = send_command.send({"cmd":"coin_count"}, out=True)
try:
out = json.loads(out)
except ValueError:
send()
else:
print out
if out['coins'] > coins:
get_db.send()


13 changes: 8 additions & 5 deletions config.py
@@ -1,7 +1,10 @@
import sqlite3
import landerdb

relay = 0 #1 is on 0 is off If 1 you must portforward port 6565
brokers = [{0:"zcoin.zapto.org", 1:6564}, {0:"192.111.130.31", 1:6565}]#, {0:"162.209.89.34", 1:6565}]
port = 6565
relay = 0
brokers = [{"ip":"zcoin.zapto.org", "port":6564}]
version = "0.2.0"
host = "0.0.0.0"
version = "0.1.6"
port = 6565
nodes = landerdb.Connect("nodes.db")
wallet = landerdb.Connect("wallet.db")
db = landerdb.Connect("db.db")
102 changes: 34 additions & 68 deletions get_db.py
Expand Up @@ -2,90 +2,56 @@
import json
import config
import random
import sqlite3
import base64
import hashlib
import register, get_nodes
import time
import os
import time

def get_db(obj, data):
db = sqlite3.connect("db.db").cursor()
db.execute("CREATE TABLE IF NOT EXISTS difficulty (level INT default 7)")
db.execute("CREATE TABLE IF NOT EXISTS coins (hash TEXT, address TEXT, starter TEXT)")
db.execute("CREATE TABLE IF NOT EXISTS transactions (to_ TEXT, from_ TEXT, hash TEXT)")
try:
db.execute("SELECT * FROM coins")
except sqlite3.DatabaseError:
return
with open("db.db", 'rb') as file:
while True:
x = file.read(100)
if not x:
data = file.read(100)
if not data:
break
md5sum = hashlib.md5(x).hexdigest()
out = base64.b64encode(x)
x = json.dumps({"md5sum":md5sum, "data":out})
obj.send(x)
obj.send(data)

def get_db_send():
node = sqlite3.connect("nodes.db")
cmd = {"cmd":"get_db"}
try:
nodes = node.execute("SELECT ip, port FROM data WHERE relay=? AND version=?", [True, config.version])
except sqlite3.OperationalError:
get_nodes.get_nodes_send(True)
get_db_send()
register.register_send()
return
if not nodes:
return
nodes = nodes.fetchall()
if not nodes:
def send(god=False):
if god:
nodes = config.brokers
random.shuffle(nodes)
else:
nodes = config.nodes.find("nodes", {"relay":1})
random.shuffle(nodes)
for x in nodes:

s = socket.socket()
try:
s.settimeout(120)
s.connect((x[0], x[1]))
s.connect((x['ip'], x['port']))
except:
s.close()
continue
else:
s.send(json.dumps(cmd))
out = ""
current = ""
no = False
while True:
s.send(json.dumps({"cmd":"get_version"}))
data = s.recv(1024)
if data == config.version:
s.close()
s = socket.socket()
try:
data = s.recv(1)
s.connect((x['ip'], x['port']))
except:
no = True
break
if data:
current = current + data
if data != "}":
continue
try:
data = json.loads(current)
except ValueError:
break
else:
current = ""
check = base64.b64decode(data['data'])
if hashlib.md5(check).hexdigest() == data['md5sum']:
out = out + check
else:
break
s.close()
continue
else:
s.send(json.dumps({"cmd":"get_db"}))
out = ""
while True:
data = s.recv(1024)
if not data:
break
out = out + data
while os.path.exists("db.lock"):
time.sleep(0.1)
open("db.lock", 'w').close()
with open("db.db", 'wb') as file:
file.write(out)
os.remove("db.lock")
break
if not no:
while os.path.exists("db.lock"):
time.sleep(0.1)
open("db.lock", 'w')
with open("db.db", 'wb') as file:
file.write(out)
os.remove("db.lock")
break
else:
s.close()

54 changes: 8 additions & 46 deletions get_difficulty.py
@@ -1,50 +1,12 @@
import socket
import json
import sqlite3
import config
import json

def get_difficulty(obj, data):
node = sqlite3.connect("nodes.db")
nodes = node.execute("SELECT ip, port FROM data WHERE relay=1 AND version=?", [config.version])
nodes = nodes.fetchall()
difficulties = []
for x in nodes:
s = socket.socket()
try:
s.settimeout(120)
s.connect((x[0], x[1]))
except:
s.close()
continue
else:
s.send(json.dumps({"cmd":"get_raw_difficulty"}))
data = s.recv(1024)
if not data:
s.close()
continue
try:
data = int(data)
except:
continue
else:
difficulties.append(data)
out = 0
for x in difficulties:
out += x
try:
out = out/len(difficulties)
if out < 7:
out = 7
except ZeroDivisionError:
out = 7
try: # Without this it will raise an error when check_coin is called.
obj.send(json.dumps({"difficulty":out}))
except:
pass
return {"difficulty":out}
diff = config.db.find("coins", "all")
if not diff:
diff = []
diff = len(diff)/50500 + 7
if diff < 7:
diff = 7
obj.send(json.dumps({"difficulty":diff}))

def get_raw_difficulty(obj, data):
db = sqlite3.connect("db.db")
check = db.execute("SELECT level FROM difficulty")
check = check.fetchall()[0]
obj.send(str(check[0]))

0 comments on commit 77393f0

Please sign in to comment.