Skip to content
This repository
tree: d0b39134bd
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 241 lines (205 sloc) 8.2 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 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
from Transport import Transport
from base64 import b64encode
from json import dumps, loads
from log import *
from sha256 import *
from threading import Thread
from time import sleep, time
from urlparse import urlsplit
from util import *
import httplib
import socket
import socks
import traceback
import urlparse


class NotAuthorized(Exception): pass
class RPCError(Exception): pass

class HttpTransport(Transport):
def __init__(self, servers, server):
super(HttpTransport, self).__init__(servers, server)

self.connection = self.lp_connection = None
self.long_poll_timeout = 3600
self.long_poll_max_askrate = 60 - self.servers.timeout
self.max_redirects = 3

self.postdata = {'method': 'getwork', 'id': 'json'}
self.headers = {"User-Agent": self.servers.user_agent, "Authorization": 'Basic ' + b64encode('%s:%s' % (self.user, self.pwd)), "X-Mining-Extensions": 'hostlist midstate rollntime'}
self.long_poll_url = ''

self.long_poll_active = False

def loop(self):
super(HttpTransport, self).loop()

thread = Thread(target=self.long_poll_thread)
thread.daemon = True
thread.start()

while True:
if self.should_stop: return

if self.check_failback():
return True

try:
with self.servers.lock:
update = self.servers.update = (self.servers.update or (time() - self.servers.last_work) > if_else(self.long_poll_active, self.long_poll_max_askrate, self.config.askrate))
if update:
work = self.getwork()
if self.servers.update:
self.queue_work(work)

while not self.result_queue.empty():
result = self.result_queue.get(False)
with self.servers.lock:
self.servers.send(result, self.send_internal)
sleep(1)
except Exception:
say_line("Unexpected error:")
traceback.print_exc()
break

def ensure_connected(self, connection, proto, host, timeout):
if connection != None and connection.sock != None:
return connection, False

if proto == 'https': connector = httplib.HTTPSConnection
else: connector = httplib.HTTPConnection

if not self.config.proxy:
return connector(host, strict=True, timeout=timeout), True

host, port = host.split(':')

proxy_proto, user, pwd, proxy_host, name = self.config.proxy
proxy_port = 9050
proxy_host = proxy_host.split(':')
if len(proxy_host) > 1:
proxy_port = int(proxy_host[1]); proxy_host = proxy_host[0]

connection = connector(host, strict=True)
connection.sock = socks.socksocket()
#connection.sock.settimeout(timeout)

proxy_type = socks.PROXY_TYPE_SOCKS5
if proxy_proto == 'http':
proxy_type = socks.PROXY_TYPE_HTTP
elif proxy_proto == 'socks4':
proxy_type = socks.PROXY_TYPE_SOCKS4

connection.sock.setproxy(proxy_type, proxy_host, proxy_port, True, user, pwd)
try:
connection.sock.connect((host, int(port)))
except socks.Socks5AuthError as e:
say_line('Proxy error: %s', str(e))
self.stop()
return connection, True

def request(self, connection, url, headers, data=None, timeout=0):
result = response = None
try:
if data: connection.request('POST', url, data, headers)
else: connection.request('GET', url, headers=headers)
if timeout:
start = time()
connection.sock.settimeout(min(timeout, 5))
response = None
while not response:
if self.should_stop or time() - start > timeout: return
try:
response = connection.getresponse()
except socket.timeout:
pass
else:
response = connection.getresponse()
if response.status == httplib.UNAUTHORIZED:
say_line('Wrong username or password for %s', self.servers.server_name())
raise NotAuthorized()
r = self.max_redirects
while response.status == httplib.TEMPORARY_REDIRECT:
response.read()
url = response.getheader('Location', '')
if r == 0 or url == '': raise HTTPException('Too much or bad redirects')
connection.request('GET', url, headers=headers)
response = connection.getresponse();
r -= 1
self.long_poll_url = response.getheader('X-Long-Polling', '')
self.servers.miner.update_time = bool(response.getheader('X-Roll-NTime', ''))
hostList = response.getheader('X-Host-List', '')
self.stratum_header = response.getheader('x-stratum', '')
if (not self.config.nsf) and hostList: self.servers.add_servers(loads(hostList))
result = loads(response.read())
if result['error']:
say_line('server error: %s', result['error']['message'])
raise RPCError(result['error']['message'])
return (connection, result)
finally:
if not result or not response or (response.version == 10 and response.getheader('connection', '') != 'keep-alive') or response.getheader('connection', '') == 'close':
connection.close()
connection = None

def getwork(self, data=None):
try:
self.connection = self.ensure_connected(self.connection, self.proto, self.host, self.servers.timeout)[0]
self.postdata['params'] = if_else(data, [data], [])
(self.connection, result) = self.request(self.connection, '/', self.headers, dumps(self.postdata))

self.servers.connection_ok()

return result['result']
except (IOError, httplib.HTTPException, ValueError, socks.ProxyError, NotAuthorized, RPCError):
self.stop()

def send_internal(self, result, nonce):
data = ''.join([result.header.encode('hex'), pack('III', long(result.time), long(result.difficulty), long(nonce)).encode('hex'), '000000800000000000000000000000000000000000000000000000000000000000000000000000000000000080020000'])
accepted = self.getwork(data)
if accepted != None:
self.servers.report(nonce, accepted)

def long_poll_thread(self):
last_host = None
while True:
if self.should_stop:
return

url = self.long_poll_url
if url != '':
proto = self.proto
host = self.host
parsedUrl = urlsplit(url)
if parsedUrl.scheme != '':
proto = parsedUrl.scheme
if parsedUrl.netloc != '':
host = parsedUrl.netloc
url = url[url.find(host) + len(host):]
if url == '': url = '/'
try:
if host != last_host: self.close_lp_connection()
self.lp_connection, changed = self.ensure_connected(self.lp_connection, proto, host, self.long_poll_timeout)
if changed:
say_line("LP connected to %s", self.servers.server_name())
last_host = host

self.long_poll_active = True
response = self.request(self.lp_connection, url, self.headers, timeout=self.long_poll_timeout)
self.long_poll_active = False
if response:
(self.lp_connection, result) = response
self.queue_work(result['result'])
if self.config.verbose:
say_line('long poll: new block %s%s', (result['result']['data'][56:64], result['result']['data'][48:56]))
except Exception:
traceback.print_exc()
except (IOError, httplib.HTTPException, ValueError, socks.ProxyError, NotAuthorized, RPCError):
say_line('long poll: IO error')
#traceback.print_exc()
self.close_lp_connection()
sleep(.5)

def stop(self):
self.should_stop = True
self.close_lp_connection()
self.close_connection()

def close_connection(self):
if self.connection:
self.connection.close()
self.connection = None

def close_lp_connection(self):
if self.lp_connection:
self.lp_connection.close()
self.lp_connection = None

def queue_work(self, work):
if work:
if not 'target' in work:
work['target'] = '0000000000000000000000000000000000000000000000000000ffff00000000'

self.servers.queue_work(self, work['data'], work['target'])
else:
self.servers.queue_work(self, work)

def detect_stratum(self):
work = self.getwork()

if work:
if self.stratum_header and 'stratum+tcp://'in self.stratum_header:
host = urlparse.urlparse(self.stratum_header).netloc
say_line('diverted to stratum on %s', host)
return host
else:
say_line('using JSON-RPC (no stratum header)')
self.queue_work(work)
return False

say_line('no response to getwork, using as stratum')
return self.host
Something went wrong with that request. Please try again.