Why not.
But this is last time I will answer such a direct question. The rest is classified. The code is really crappy since it is part of some iteration which was tested long ago:
import usb.core
import usb.util
import time
from threading import Thread, Event, RLock
import sys
import re
import struct
# find our device
dev = usb.core.find(idVendor=0x1234, idProduct=0x1010)
# was it found?
if dev is None:
raise ValueError('Device not found')
# set the active configuration. With no arguments, the first
# configuration will be the active one
dev.set_configuration()
run_app = 1
def get_time_str():
lt = time.localtime(time.time())
return "%d:%d:%d" %(lt.tm_hour, lt.tm_min, lt.tm_sec)
#######################################################################################
#######################################################################################
class EP2_listener(Thread):
def __init__(self):
Thread.__init__(self)
self.count = [0, 0]
self.starttime = time.time()
self.daemon = True
def run(self):
global run_app
print "[%s]EP2_listener started" % get_time_str()
while run_app:
ret = ''
try:
ret = dev.read(0x82, 64, 0, 100)
log_msg = ''.join([chr(x) for x in ret])
sys.stdout.write(log_msg)
except Exception as e:
pass
if len(ret) == 0:
time.sleep(0.01)
############ startez thread #########
listener = EP2_listener()
listener.start()
#####################################
def wr_dev_ok_err(msg):
try:
dev.write(1, msg, 0, 3100)
tick = time.time()
while time.time() < tick + 1.0:
try:
ret = dev.read(0x81, 64, 0, 3100)
retbuf = ''.join([chr(x) for x in ret])
if re.search("OK", retbuf):
print retbuf
return 1
if re.search("ERR", retbuf):
print retbuf
return -1
if re.search("BUSY", retbuf):
print retbuf
return -2
print "retbuf="+retbuf
except Exception as e:
print e
pass
except Exception as e:
print e
pass
return 0
def get_ok():
tick = time.time()
while time.time() < tick + 1.0:
try:
ret = dev.read(0x81, 256, 0, 3100)
retbuf = ''.join([chr(x) for x in ret])
if re.search("OK", retbuf):
print "got OK:" + retbuf
return 1
if re.search("ERR", retbuf):
print retbuf
return -1
if re.search("BUSY", retbuf):
print retbuf
return -2
print "retbuf="+retbuf
except Exception as e:
print e
pass
def wr_dev(msg):
try:
dev.write(1, msg, 0, 3100)
tick = time.time()
while time.time() < tick + 1.0:
try:
ret = dev.read(0x81, 64, 0, 3100)
retbuf = ''.join([chr(x) for x in ret])
if len(retbuf):
#print "retbuf="+retbuf
return retbuf
except Exception as e:
#print e
pass
except Exception as e:
#print e
pass
return 0
def ask_op(op):
wr_dev("Z7X,00000000%02x"% (op &0xff))
retcode = wr_dev("Z7X,0100000200")
return retcode
def memvar_dump(ram_off, len, name):
wr_dev("Z7X,%08lx05" % ram_off)
ar = []
for j in xrange(len):
retcode = ask_op(0x07)
val = 0
try:
val = int(retcode, 16)
except:
pass
ar.append(val)
return ar
tick = time.time()
run_once = 1
time.sleep(0.5)
print "GET_ID=%s" % ask_op(1)
########################################################
#### dll result ####
########################################################
#######################################################################################
#######################################################################################
def uint32(x):
return x & 0xffffffffL
def bytereverse(x):
return uint32(( ((x) << 24) | (((x) <<
& 0x00ff0000) |
(((x) >>
& 0x0000ff00) | ((x) >> 24) ))
def bufreverse(in_buf):
out_words = []
for i in range(0, len(in_buf), 4):
word = struct.unpack('@I', in_buf[i:i+4])[0]
out_words.append(struct.pack('@I', bytereverse(word)))
return ''.join(out_words)
#######################################################################################
host = "127.0.0.1"
http_port = 8337
#host = "mine.pool-x.eu"
#http_port = 8337
#host = "pool1.us.multipool.us"
#http_port = 17777
host = "mining.eu.hypernova.pw"
http_port = 9332
host = "pooledbits.com"
http_port = 8332
user = "xxxx"
password = "x"
#######################################################################################
import json
import base64
from ctypes import cdll, byref
lib = cdll.LoadLibrary('./scrypt.dll')
#print lib
import ctypes
class Scrypt(object):
def __init__(self):
#self.obj = lib.say_hello()
none = 0
def scanhash(self, pdata, ptarget, max_nonce, c_long_last_nonce, n):
return lib.scanhash_scrypt(pdata, ptarget, max_nonce, c_long_last_nonce, n)
scr = Scrypt()
long_polling_path = ''
import time
while 1:
#try:
if 1:
#print "getwork->con_init()"
import httplib
conn = httplib.HTTPConnection(host, http_port, True, 10)
#print "getwork->con_established"
req = json.dumps({"method": "getwork", "params": [], "id": 'json'})
auth = "Basic " + base64.b64encode(user+ ":" + password)
headers = {"User-Agent": "lt_miner", "Content-type": "application/json", "Content-Length": len(req), "Authorization": auth}
#print "getwork->req_sent"
conn.request("POST", '/', req, headers)
#print "getwork->req_answered"
http_response = conn.getresponse()
buf = http_response.read()
#print "http_response=%s" % buf
response = json.loads(buf)
#print "getwork->got_data"
if response["error"] != None:
print "error [%s]" % response["error"]
sys.exit(1)
if response["result"]:
#print("getwork() ok\n")
work = response['result']
#print work
if long_polling_path == '':
headers = http_response.getheaders()
for (key,val) in headers:
if key == "x-long-polling":
long_polling_path = val
if long_polling_path != '':
do_long_poll = True
######################################################
stime = time.time()
last_nonce = ctypes.c_long(0)
#n = 0
#data = work['data'].decode('hex')
data_orig = work['data']
data_pt_c = work['data'].decode('hex')
#target = work['target'].decode('hex')
target_pt_c = work['target'].decode('hex')
target = work['target']
#print "data_orig=%s" % data_orig
#print "target(full, bytereversed)=%s" % target
print "data=%s." % data_orig[:73]
# sys.exit(1)
#res = scr.scanhash(data, target, 0xffff, byref(last_nonce), n )
######################################################
target_short = 0xffffffff
if len(target) > 8:
#target_short = bufreverse(target[56:].decode('hex'))
target_short = bytereverse(int(target[56:], 16)) ^ 0xffffffff
target_short = 0xffff0000 #wired diff 1
#print "target(bit_complemented)=%08lx" % target_short
data = data_orig.decode('hex')
data = bufreverse(data)
#print data.encode('hex')
ram_off = 4262
wr_dev("Z7X,%08lx05" % ram_off)
for i in xrange(19):
word = struct.unpack('@I', data[i*4:i*4+4])[0]
wr_dev("Z7X,%08lx06" % word)
wr_dev("Z7X,0000000006") #### nonce
wr_dev("Z7X,0000ffff06") #### range
wr_dev("Z7X,%08lx06" % target_short)
wr_dev("Z7X,000000000e")
start = time.time()
tick = time.time() + 1.0
while 1:
time.sleep(0.1)
retcode = wr_dev("Z7X,0000000000")
if re.search("515151", retcode):
time.sleep(0.01)
else:
retcode = wr_dev("Z7X,0000000000")
if not re.search("515151", retcode):
time.sleep(0.01)
delta_time = (time.time() - start) * 1000
print "Scanhash took %d ms" % (delta_time),
rram = memvar_dump(4281, 1, "nonce")
print "/ Approximate speed = %.2f kHash" %((float(rram[0])) / (delta_time))
break
if time.time() > tick:
tick = time.time() + 1.0
print ".",
rram = memvar_dump(4281, 1, "nonce")
nonce = rram[0]
res = 0
if nonce < 0x10000:
res = 1
###########################################################################
nonce_str = "%08lx" %(nonce & 0xffffffff)
data_new = data_orig[:156] + nonce_str[4:] + data_orig[160:]
n = nonce - 1
res2 = scr.scanhash(data_pt_c, target_pt_c, nonce + 1, byref(last_nonce), n )
if res != 0 and res2 != 0:
f = open("succ.txt", "a")
f.write("----NEW BLOCK----\n")
f.write("data_orig:\n%s\n" % data_orig)
f.write("data_new:\n%s\n" % data_new)
f.write("nonce=%08lx\n" % nonce)
try:
sconn = httplib.HTTPConnection(host, http_port, True, 10)
req = json.dumps({"method": "getwork", "params": [data_new], "id": 0})
auth = "Basic " + base64.b64encode(user+ ":" + password)
headers = {"User-Agent": "lt_miner", "Content-type": "application/json", "Content-Length": len(req), "Authorization": auth}
sconn.request("POST", '/', req, headers)
response = json.loads(sconn.getresponse().read())
if response["error"] != None:
print ("Server reported error: %s\n" % response["error"])
f.write("Server reported error: %s\n" % response["error"]);
time.sleep(1.0)
if response["result"]:
print "%04x accepted" % (nonce)
f.write("accepted nonce=%04x %s\n" % (nonce, response["result"]));
else:
f.write("rejected share [%s]\n" % response["result"]);
except Exception as e:
print("Error while uploading share e=%s\n" % e)
f.write("Error while uploading share e=%s\n" % e);
time.sleep(1.0)
f.write("----END BLOCK----\n\n")
f.close()
# except Exception as e:
# print e
# sys.exit(1)
time.sleep(1.0)