You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

387 lines
10 KiB

9 years ago
#include "EthStratumClient.h"
#include <libdevcore/Log.h>
9 years ago
using boost::asio::ip::tcp;
9 years ago
EthStratumClient::EthStratumClient(GenericFarm<EthashProofOfWork> * f, MinerType m, string const & host, string const & port, string const & user, string const & pass, int const & retries, int const & worktimeout, bool const & precompute)
9 years ago
: m_socket(m_io_service)
{
m_minerType = m;
9 years ago
m_primary.host = host;
m_primary.port = port;
m_primary.user = user;
m_primary.pass = pass;
p_active = &m_primary;
9 years ago
m_authorized = false;
m_connected = false;
9 years ago
m_precompute = precompute;
m_pending = 0;
9 years ago
m_maxRetries = retries;
m_worktimeout = worktimeout;
9 years ago
9 years ago
p_farm = f;
9 years ago
p_worktimer = nullptr;
9 years ago
connect();
}
EthStratumClient::~EthStratumClient()
{
}
9 years ago
void EthStratumClient::setFailover(string const & host, string const & port)
{
setFailover(host, port, p_active->user, p_active->pass);
}
void EthStratumClient::setFailover(string const & host, string const & port, string const & user, string const & pass)
{
m_failover.host = host;
m_failover.port = port;
m_failover.user = user;
m_failover.pass = pass;
}
void EthStratumClient::connect()
{
9 years ago
tcp::resolver r(m_io_service);
9 years ago
tcp::resolver::query q(p_active->host, p_active->port);
9 years ago
r.async_resolve(q, boost::bind(&EthStratumClient::resolve_handler,
this, boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
9 years ago
cnote << "Connecting to stratum server " << p_active->host + ":" + p_active->port;
9 years ago
boost::thread t(boost::bind(&boost::asio::io_service::run, &m_io_service));
}
9 years ago
#define BOOST_ASIO_ENABLE_CANCELIO
void EthStratumClient::reconnect()
{
/*
if (p_farm->isMining())
{
cnote << "Stopping farm";
p_farm->stop();
}
*/
9 years ago
if (p_worktimer) {
p_worktimer->cancel();
p_worktimer = nullptr;
}
m_io_service.reset();
m_socket.close();
m_authorized = false;
m_connected = false;
9 years ago
if (!m_failover.host.empty())
{
m_retries++;
if (m_retries > m_maxRetries)
{
if (m_failover.host == "exit") {
disconnect();
return;
}
else if (p_active == &m_primary)
{
p_active = &m_failover;
}
else {
p_active = &m_primary;
}
m_retries = 0;
}
}
cnote << "Reconnecting in 3 seconds...";
boost::asio::deadline_timer timer(m_io_service, boost::posix_time::seconds(3));
timer.wait();
9 years ago
connect();
}
9 years ago
void EthStratumClient::disconnect()
{
cnote << "Disconnecting";
m_connected = false;
9 years ago
m_running = false;
if (p_farm->isMining())
{
cnote << "Stopping farm";
p_farm->stop();
}
9 years ago
m_socket.close();
m_io_service.stop();
}
void EthStratumClient::resolve_handler(const boost::system::error_code& ec, tcp::resolver::iterator i)
{
if (!ec)
{
async_connect(m_socket, i, boost::bind(&EthStratumClient::connect_handler,
this, boost::asio::placeholders::error,
boost::asio::placeholders::iterator));
}
else
{
9 years ago
cerr << "Could not resolve host" << p_active->host + ":" + p_active->port + ", " << ec.message();
reconnect();
}
}
void EthStratumClient::connect_handler(const boost::system::error_code& ec, tcp::resolver::iterator i)
{
dev::setThreadName("stratum");
if (!ec)
{
m_connected = true;
9 years ago
cnote << "Connected to stratum server " << p_active->host << ":" << p_active->port;
if (!p_farm->isMining())
{
cnote << "Starting farm";
if (m_minerType == MinerType::CPU)
p_farm->start("cpu");
else if (m_minerType == MinerType::CL)
p_farm->start("opencl");
else if (m_minerType == MinerType::CUDA)
p_farm->start("cuda");
}
std::ostream os(&m_requestBuffer);
os << "{\"id\": 1, \"method\": \"mining.subscribe\", \"params\": []}\n";
9 years ago
async_write(m_socket, m_requestBuffer,
9 years ago
boost::bind(&EthStratumClient::handleResponse, this,
boost::asio::placeholders::error));
}
else
{
9 years ago
cwarn << "Could not connect to stratum server " << p_active->host << ":" << p_active->port << ", " << ec.message();
reconnect();
}
}
void EthStratumClient::readline() {
m_mtx.lock();
if (m_pending == 0) {
9 years ago
async_read_until(m_socket, m_responseBuffer, "\n",
boost::bind(&EthStratumClient::readResponse, this,
boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
m_pending++;
}
m_mtx.unlock();
}
9 years ago
void EthStratumClient::handleResponse(const boost::system::error_code& ec) {
if (!ec)
{
readline();
9 years ago
}
else
{
dev::setThreadName("stratum");
9 years ago
cwarn << "Handle response failed: " << ec.message();
9 years ago
}
}
void EthStratumClient::readResponse(const boost::system::error_code& ec, std::size_t bytes_transferred)
{
dev::setThreadName("stratum");
m_mtx.lock();
m_pending = m_pending > 0 ? m_pending - 1 : 0;
m_mtx.unlock();
9 years ago
if (!ec)
{
std::istream is(&m_responseBuffer);
std::string response;
getline(is, response);
if (response.front() == '{' && response.back() == '}')
9 years ago
{
Json::Value responseObject;
Json::Reader reader;
if (reader.parse(response.c_str(), responseObject))
{
processReponse(responseObject);
m_response = response;
}
else
{
cwarn << "Parse response failed: " << reader.getFormattedErrorMessages();
}
9 years ago
}
else
{
cwarn << "Discarding incomplete response";
9 years ago
}
if (m_connected)
readline();
9 years ago
}
else
{
9 years ago
cwarn << "Read response failed: " << ec.message();
if (m_connected)
reconnect();
9 years ago
}
}
void EthStratumClient::processReponse(Json::Value& responseObject)
{
Json::Value error = responseObject.get("error", new Json::Value);
if (error.isArray())
{
string msg = error.get(1, "Unknown error").asString();
cnote << msg;
}
std::ostream os(&m_requestBuffer);
Json::Value params;
int id = responseObject.get("id", Json::Value::null).asInt();
switch (id)
{
case 1:
cnote << "Subscribed to stratum server";
9 years ago
os << "{\"id\": 2, \"method\": \"mining.authorize\", \"params\": [\"" << p_active->user << "\",\"" << p_active->pass << "\"]}\n";
async_write(m_socket, m_requestBuffer,
boost::bind(&EthStratumClient::handleResponse, this,
boost::asio::placeholders::error));
break;
case 2:
m_authorized = responseObject.get("result", Json::Value::null).asBool();
if (!m_authorized)
{
disconnect();
return;
}
9 years ago
cnote << "Authorized worker " << p_active->user;
break;
case 4:
9 years ago
if (responseObject.get("result", false).asBool()) {
cnote << "B-) Submitted and accepted.";
9 years ago
p_farm->acceptedSolution();
}
else {
cwarn << ":-( Not accepted.";
9 years ago
p_farm->rejectedSolution();
}
break;
default:
string method = responseObject.get("method", "").asString();
if (method == "mining.notify")
{
params = responseObject.get("params", Json::Value::null);
if (params.isArray())
{
m_job = params.get((Json::Value::ArrayIndex)0, "").asString();
string sHeaderHash = params.get((Json::Value::ArrayIndex)1, "").asString();
string sSeedHash = params.get((Json::Value::ArrayIndex)2, "").asString();
string sShareTarget = params.get((Json::Value::ArrayIndex)3, "").asString();
bool cleanJobs = params.get((Json::Value::ArrayIndex)4, "").asBool();
if (sShareTarget.length() < 66)
sShareTarget = "0x" + string(66 - sShareTarget.length(), '0') + sShareTarget.substr(2);
int l = sShareTarget.length();
if (sHeaderHash != "" && sSeedHash != "" && sShareTarget != "")
{
cnote << "Received new job #" + m_job.substr(0,8);
//cnote << "Header hash: " + sHeaderHash;
//cnote << "Seed hash: " + sSeedHash;
//cnote << "Share target: " + sShareTarget;
h256 seedHash = h256(sSeedHash);
h256 headerHash = h256(sHeaderHash);
EthashAux::FullType dag;
if (seedHash != m_current.seedHash)
cnote << "Grabbing DAG for" << seedHash;
if (!(dag = EthashAux::full(seedHash, true, [&](unsigned _pc){ cout << "\rCreating DAG. " << _pc << "% done..." << flush; return 0; })))
BOOST_THROW_EXCEPTION(DAGCreationFailure());
if (m_precompute)
EthashAux::computeFull(sha3(seedHash), true);
if (headerHash != m_current.headerHash)
{
9 years ago
if (p_worktimer)
p_worktimer->cancel();
m_current.headerHash = h256(sHeaderHash);
m_current.seedHash = seedHash;
m_current.boundary = h256(sShareTarget);// , h256::AlignRight);
p_farm->setWork(m_current);
9 years ago
p_worktimer = new boost::asio::deadline_timer(m_io_service, boost::posix_time::seconds(m_worktimeout));
p_worktimer->async_wait(boost::bind(&EthStratumClient::work_timeout_handler, this, boost::asio::placeholders::error));
}
}
}
}
else if (method == "mining.set_difficulty")
{
}
else if (method == "client.get_version")
{
os << "{\"error\": null, \"id\" : " << id << ", \"result\" : \"" << ETH_PROJECT_VERSION << "\"}\n";
async_write(m_socket, m_requestBuffer,
boost::bind(&EthStratumClient::handleResponse, this,
boost::asio::placeholders::error));
}
break;
}
9 years ago
}
9 years ago
void EthStratumClient::work_timeout_handler(const boost::system::error_code& ec) {
if (!ec) {
cnote << "No new work received in" << m_worktimeout << "seconds.";
9 years ago
reconnect();
}
}
9 years ago
bool EthStratumClient::submit(EthashProofOfWork::Solution solution) {
9 years ago
cnote << "Solution found; Submitting to" << p_active->host << "...";
cnote << " Nonce:" << "0x"+solution.nonce.hex();
cnote << " Mixhash:" << "0x" + solution.mixHash.hex();
cnote << " Header-hash:" << "0x" + m_current.headerHash.hex();
cnote << " Seedhash:" << "0x" + m_current.seedHash.hex();
cnote << " Target: " << "0x" + h256(m_current.boundary).hex();
cnote << " Ethash: " << "0x" + h256(EthashAux::eval(m_current.seedHash, m_current.headerHash, solution.nonce).value).hex();
if (EthashAux::eval(m_current.seedHash, m_current.headerHash, solution.nonce).value < m_current.boundary)
{
9 years ago
string json = "{\"id\": 4, \"method\": \"mining.submit\", \"params\": [\"" + p_active->user + "\",\"" + m_job + "\",\"0x" + solution.nonce.hex() + "\",\"0x" + m_current.headerHash.hex() + "\",\"0x" + solution.mixHash.hex() + "\"]}\n";
std::ostream os(&m_requestBuffer);
os << json;
async_write(m_socket, m_requestBuffer,
boost::bind(&EthStratumClient::handleResponse, this,
boost::asio::placeholders::error));
return true;
}
9 years ago
else {
cwarn << "FAILURE: GPU gave incorrect result!";
9 years ago
p_farm->rejectedSolution();
}
return false;
9 years ago
}