Integrate P2Pool

This commit is contained in:
devhyper 2022-04-01 10:27:35 -07:00
parent 002fe8eefa
commit 377a1a9680
No known key found for this signature in database
GPG key ID: D5F749908AE9DA70
7 changed files with 647 additions and 31 deletions

View file

@ -52,6 +52,8 @@ Rectangle {
case Wallet.ConnectionStatus_Connected: case Wallet.ConnectionStatus_Connected:
if (!appWindow.daemonSynced) if (!appWindow.daemonSynced)
return qsTr("Synchronizing"); return qsTr("Synchronizing");
if (persistentSettings.useRemoteNode && persistentSettings.allowRemoteNodeMining && appWindow.isMining)
return qsTr("Remote node") + " + " + qsTr("Mining");
if (persistentSettings.useRemoteNode) if (persistentSettings.useRemoteNode)
return qsTr("Remote node"); return qsTr("Remote node");
return appWindow.isMining ? qsTr("Connected") + " + " + qsTr("Mining"): qsTr("Connected"); return appWindow.isMining ? qsTr("Connected") + " + " + qsTr("Mining"): qsTr("Connected");

View file

@ -42,6 +42,7 @@ import moneroComponents.WalletManager 1.0
import moneroComponents.PendingTransaction 1.0 import moneroComponents.PendingTransaction 1.0
import moneroComponents.NetworkType 1.0 import moneroComponents.NetworkType 1.0
import moneroComponents.Settings 1.0 import moneroComponents.Settings 1.0
import moneroComponents.P2PoolManager 1.0
import "components" import "components"
import "components" as MoneroComponents import "components" as MoneroComponents
@ -731,6 +732,7 @@ ApplicationWindow {
if (splash) { if (splash) {
appWindow.showProcessingSplash(qsTr("Waiting for daemon to stop...")); appWindow.showProcessingSplash(qsTr("Waiting for daemon to stop..."));
} }
p2poolManager.exit()
daemonManager.stopAsync(persistentSettings.nettype, function(result) { daemonManager.stopAsync(persistentSettings.nettype, function(result) {
daemonStartStopInProgress = 0; daemonStartStopInProgress = 0;
if (splash) { if (splash) {
@ -1405,6 +1407,8 @@ ApplicationWindow {
property string account_name property string account_name
property string wallet_path property string wallet_path
property bool allow_background_mining : false property bool allow_background_mining : false
property bool allow_p2pool_mining : false
property bool allowRemoteNodeMining : false
property bool miningIgnoreBattery : true property bool miningIgnoreBattery : true
property var nettype: NetworkType.MAINNET property var nettype: NetworkType.MAINNET
property int restore_height : 0 property int restore_height : 0
@ -1413,6 +1417,7 @@ ApplicationWindow {
property bool is_recovering_from_device : false property bool is_recovering_from_device : false
property bool customDecorations : true property bool customDecorations : true
property string daemonFlags property string daemonFlags
property string p2poolFlags
property int logLevel: 0 property int logLevel: 0
property string logCategories: "" property string logCategories: ""
property string daemonUsername: "" // TODO: drop after v0.17.2.0 release property string daemonUsername: "" // TODO: drop after v0.17.2.0 release
@ -2177,7 +2182,7 @@ ApplicationWindow {
console.log("close accepted"); console.log("close accepted");
// Close wallet non async on exit // Close wallet non async on exit
daemonManager.exit(); daemonManager.exit();
p2poolManager.exit();
closeWallet(Qt.quit); closeWallet(Qt.quit);
} }

View file

@ -26,11 +26,14 @@
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import QtQml.Models 2.2
import QtQuick 2.9 import QtQuick 2.9
import QtQuick.Layouts 1.1 import QtQuick.Layouts 1.1
import QtQuick.Dialogs 1.2 import QtQuick.Dialogs 1.2
import "../components" as MoneroComponents import "../components" as MoneroComponents
import moneroComponents.Wallet 1.0 import moneroComponents.Wallet 1.0
import moneroComponents.P2PoolManager 1.0
import moneroComponents.DaemonManager 1.0
Rectangle { Rectangle {
id: root id: root
@ -52,13 +55,14 @@ Rectangle {
MoneroComponents.Label { MoneroComponents.Label {
id: soloTitleLabel id: soloTitleLabel
fontSize: 24 fontSize: 24
text: qsTr("Solo mining") + translationManager.emptyString text: qsTr("Mining") + translationManager.emptyString
} }
MoneroComponents.WarningBox { MoneroComponents.WarningBox {
Layout.bottomMargin: 8 Layout.bottomMargin: 8
id: localDaemonWarning
text: qsTr("Mining is only available on local daemons.") + translationManager.emptyString text: qsTr("Mining is only available on local daemons.") + translationManager.emptyString
visible: persistentSettings.useRemoteNode visible: persistentSettings.useRemoteNode && !persistentSettings.allowRemoteNodeMining
} }
MoneroComponents.WarningBox { MoneroComponents.WarningBox {
@ -69,7 +73,7 @@ Rectangle {
MoneroComponents.TextPlain { MoneroComponents.TextPlain {
id: soloMainLabel id: soloMainLabel
text: qsTr("Mining with your computer helps strengthen the Monero network. The more people mine, the harder it is for the network to be attacked, and every little bit helps.\n\nMining also gives you a small chance to earn some Monero. Your computer will create hashes looking for block solutions. If you find a block, you will get the associated reward. Good luck!") + translationManager.emptyString text: qsTr("Mining with your computer helps strengthen the Monero network. The more people mine, the harder it is for the network to be attacked, and every little bit helps.\n\nMining also gives you a small chance to earn some Monero. Your computer will create hashes looking for block solutions. If you find a block, you will get the associated reward. Good luck!") + "\n\n" + qsTr("P2Pool mining is a decentralized way to pool mine that pays out more frequently compared to solo mining, while also supporting the network.") + translationManager.emptyString
wrapMode: Text.Wrap wrapMode: Text.Wrap
Layout.fillWidth: true Layout.fillWidth: true
font.family: MoneroComponents.Style.fontRegular.name font.family: MoneroComponents.Style.fontRegular.name
@ -90,6 +94,43 @@ Rectangle {
columnSpacing: 20 columnSpacing: 20
rowSpacing: 16 rowSpacing: 16
ListModel {
id: miningModeModel
ListElement { column1: qsTr("Solo") ; column2: ""; priority: 0}
ListElement { column1: "P2Pool" ; column2: ""; priority: 1}
}
ColumnLayout {
Layout.fillWidth: true
Layout.alignment : Qt.AlignTop | Qt.AlignLeft
MoneroComponents.Label {
id: miningModeLabel
color: MoneroComponents.Style.defaultFontColor
text: qsTr("Mining mode") + translationManager.emptyString
fontSize: 16
}
}
ColumnLayout {
Layout.topMargin: 5
spacing: 10
MoneroComponents.StandardDropdown {
Layout.maximumWidth: 200
id: miningModeDropdown
visible: true
currentIndex: 0
dataModel: miningModeModel
onChanged: {
persistentSettings.allow_p2pool_mining = miningModeDropdown.currentIndex === 1;
walletManager.stopMining();
p2poolManager.exit();
}
}
}
ColumnLayout { ColumnLayout {
Layout.fillWidth: true Layout.fillWidth: true
Layout.alignment : Qt.AlignTop | Qt.AlignLeft Layout.alignment : Qt.AlignTop | Qt.AlignLeft
@ -194,6 +235,7 @@ Rectangle {
MoneroComponents.Label { MoneroComponents.Label {
id: optionsLabel id: optionsLabel
color: MoneroComponents.Style.defaultFontColor color: MoneroComponents.Style.defaultFontColor
visible: !persistentSettings.allow_p2pool_mining
text: qsTr("Options") + translationManager.emptyString text: qsTr("Options") + translationManager.emptyString
fontSize: 16 fontSize: 16
wrapMode: Text.Wrap wrapMode: Text.Wrap
@ -208,7 +250,8 @@ Rectangle {
RowLayout { RowLayout {
MoneroComponents.CheckBox { MoneroComponents.CheckBox {
id: backgroundMining id: backgroundMining
enabled: startSoloMinerButton.enabled visible: !persistentSettings.allow_p2pool_mining
enabled: startSoloMinerButton.enabled && !persistentSettings.allow_p2pool_mining
checked: persistentSettings.allow_background_mining checked: persistentSettings.allow_background_mining
onClicked: persistentSettings.allow_background_mining = checked onClicked: persistentSettings.allow_background_mining = checked
text: qsTr("Background mining (experimental)") + translationManager.emptyString text: qsTr("Background mining (experimental)") + translationManager.emptyString
@ -241,16 +284,52 @@ Rectangle {
primary: !stopSoloMinerButton.enabled primary: !stopSoloMinerButton.enabled
text: qsTr("Start mining") + translationManager.emptyString text: qsTr("Start mining") + translationManager.emptyString
onClicked: { onClicked: {
var success = walletManager.startMining(appWindow.currentWallet.address(0, 0), threads, persistentSettings.allow_background_mining, persistentSettings.miningIgnoreBattery) var daemonReady = appWindow.daemonSynced && appWindow.daemonRunning && !persistentSettings.useRemoteNode
if (success) { if (persistentSettings.allowRemoteNodeMining) {
daemonReady = persistentSettings.useRemoteNode && appWindow.daemonSynced
}
if (daemonReady) {
var success;
if (persistentSettings.allow_p2pool_mining) {
if (p2poolManager.isInstalled()) {
if (persistentSettings.allowRemoteNodeMining) {
startP2Pool()
}
else {
daemonManager.stopAsync(persistentSettings.nettype, startP2PoolLocal)
}
}
else {
confirmationDialog.title = qsTr("P2Pool installation") + translationManager.emptyString;
confirmationDialog.text = qsTr("P2Pool will be installed at %1. Proceed?").arg(applicationDirectory) + translationManager.emptyString;
confirmationDialog.icon = StandardIcon.Question;
confirmationDialog.cancelText = qsTr("No") + translationManager.emptyString;
confirmationDialog.okText = qsTr("Yes") + translationManager.emptyString;
confirmationDialog.onAcceptedCallback = function() {
p2poolManager.download();
statusMessageText.text = "Downloading P2Pool...";
statusMessage.visible = true
startSoloMinerButton.enabled = false;
stopSoloMinerButton.enabled = false;
}
confirmationDialog.open();
}
}
else
{
success = walletManager.startMining(appWindow.currentWallet.address(0, 0), threads, persistentSettings.allow_background_mining, persistentSettings.miningIgnoreBattery)
if (success)
{
update() update()
} else { }
errorPopup.title = qsTr("Error starting mining") + translationManager.emptyString; else
errorPopup.text = qsTr("Couldn't start mining.<br>") + translationManager.emptyString {
if (persistentSettings.useRemoteNode) miningError(qsTr("Couldn't start mining.<br>") + translationManager.emptyString)
errorPopup.text += qsTr("Mining is only available on local daemons. Run a local daemon to be able to mine.<br>") + translationManager.emptyString }
errorPopup.icon = StandardIcon.Critical }
errorPopup.open() }
else {
miningError(qsTr("Couldn't start mining.<br>") + translationManager.emptyString)
} }
} }
} }
@ -263,6 +342,7 @@ Rectangle {
text: qsTr("Stop mining") + translationManager.emptyString text: qsTr("Stop mining") + translationManager.emptyString
onClicked: { onClicked: {
walletManager.stopMining() walletManager.stopMining()
p2poolManager.exit()
update() update()
} }
} }
@ -295,11 +375,148 @@ Rectangle {
inputPaddingLeft: 0 inputPaddingLeft: 0
} }
} }
ListModel {
id: chainModel
ListElement { column1: qsTr("Mini") ; column2: ""; priority: 0}
ListElement { column1: qsTr("Main") ; column2: ""; priority: 1}
}
ColumnLayout {
Layout.fillWidth: true
Layout.alignment : Qt.AlignTop | Qt.AlignLeft
MoneroComponents.Label {
id: chainLabel
color: MoneroComponents.Style.defaultFontColor
visible: persistentSettings.allow_p2pool_mining
text: qsTr("Chain") + translationManager.emptyString
fontSize: 16
}
MoneroComponents.Tooltip {
id: chainsHelpTooltip
text: qsTr("Use the mini chain if you have a low hashrate.") + translationManager.emptyString
}
MouseArea {
id: chainsTooltipArea
width: parent.width
height: parent.height
enabled: persistentSettings.allow_p2pool_mining
hoverEnabled: true
onEntered: {
chainsHelpTooltip.tooltipPopup.open();
}
onExited: {
chainsHelpTooltip.tooltipPopup.close();
}
} }
} }
function updateStatusText() { ColumnLayout {
Layout.topMargin: 5
spacing: 10
MoneroComponents.StandardDropdown {
Layout.maximumWidth: 200
id: chainDropdown
visible: persistentSettings.allow_p2pool_mining
currentIndex: 0
dataModel: chainModel
}
}
ColumnLayout {
Layout.fillWidth: true
Layout.alignment : Qt.AlignTop | Qt.AlignLeft
MoneroComponents.Label {
id: flagsLabel
visible: persistentSettings.allow_p2pool_mining
color: MoneroComponents.Style.defaultFontColor
text: qsTr("Flags") + translationManager.emptyString
fontSize: 16
}
MoneroComponents.Tooltip {
id: flagsHelpTooltip
text: "
Usage:<br>
--wallet Wallet address to mine to. Subaddresses and integrated addresses are not supported!<br>
--host IP address of your Monero node, default is 127.0.0.1<br>
--rpc-port monerod RPC API port number, default is 18081<br>
--zmq-port monerod ZMQ pub port number, default is 18083 (same port as in monerod\'s \"--zmq-pub\" command line parameter)<br>
--stratum Comma-separated list of IP:port for stratum server to listen on<br>
--p2p Comma-separated list of IP:port for p2p server to listen on<br>
--addpeers Comma-separated list of IP:port of other p2pool nodes to connect to<br>
--light-mode Don't allocate RandomX dataset, saves 2GB of RAM<br>
--loglevel Verbosity of the log, integer number between 0 and 6<br>
--config Name of the p2pool config file<br>
--data-api Path to the p2pool JSON data (use it in tandem with an external web-server)<br>
--local-api Enable /local/ path in api path for Stratum Server and built-in miner statistics<br>
--stratum-api An alias for --local-api<br>
--no-cache Disable p2pool.cache<br>
--no-color Disable colors in console output<br>
--no-randomx Disable internal RandomX hasher: p2pool will use RPC calls to monerod to check PoW hashes<br>
--out-peers N Maximum number of outgoing connections for p2p server (any value between 10 and 1000)<br>
--in-peers N Maximum number of incoming connections for p2p server (any value between 10 and 1000)<br>
--start-mining N Start built-in miner using N threads (any value between 1 and 64)<br>
--help Show this help message
"
}
MouseArea {
id: flagsTooltipArea
width: parent.width
height: parent.height
enabled: persistentSettings.allow_p2pool_mining
hoverEnabled: true
onEntered: {
flagsHelpTooltip.tooltipPopup.open();
}
onExited: {
flagsHelpTooltip.tooltipPopup.close();
}
}
}
ColumnLayout {
Layout.fillWidth: true
MoneroComponents.LineEditMulti {
id: p2poolFlags
Layout.minimumWidth: 100
Layout.bottomMargin: 20
labelFontSize: 14
fontSize: 15
visible: persistentSettings.allow_p2pool_mining
wrapMode: Text.WrapAnywhere
labelText: qsTr("P2Pool startup flags") + translationManager.emptyString
placeholderText: qsTr("(optional)") + translationManager.emptyString
placeholderFontSize: 15
text: persistentSettings.p2poolFlags
addressValidation: false
onEditingFinished: {
persistentSettings.allowRemoteNodeMining = p2poolFlags.text.includes("--host");
persistentSettings.p2poolFlags = p2poolFlags.text;
}
}
}
}
}
function updateStatusText(p2poolHashrate) {
if (appWindow.isMining) { if (appWindow.isMining) {
if (persistentSettings.allow_p2pool_mining) {
if (p2poolHashrate === 0) {
statusText.text = qsTr("Starting P2Pool") + translationManager.emptyString;
}
else {
statusText.text = qsTr("Mining with P2Pool, at %1 H/s").arg(p2poolHashrate) + translationManager.emptyString;
}
}
else {
var userHashRate = walletManager.miningHashRate(); var userHashRate = walletManager.miningHashRate();
if (userHashRate === 0) { if (userHashRate === 0) {
statusText.text = qsTr("Mining temporarily suspended.") + translationManager.emptyString; statusText.text = qsTr("Mining temporarily suspended.") + translationManager.emptyString;
@ -314,22 +531,42 @@ Rectangle {
statusText.text = qsTr("Mining at %1 H/s. It gives you a 1 in %2 daily chance of finding a block.").arg(userHashRate).arg(chanceFindBlockDay) + translationManager.emptyString; statusText.text = qsTr("Mining at %1 H/s. It gives you a 1 in %2 daily chance of finding a block.").arg(userHashRate).arg(chanceFindBlockDay) + translationManager.emptyString;
} }
} }
}
else { else {
statusText.text = qsTr("Not mining") + translationManager.emptyString; statusText.text = qsTr("Not mining") + translationManager.emptyString;
} }
} }
function onMiningStatus(isMining) { function onMiningStatus(isMining, hashrate) {
var daemonReady = !persistentSettings.useRemoteNode && appWindow.daemonSynced var daemonReady = appWindow.daemonSynced
if (!persistentSettings.allowRemoteNodeMining) {
var daemonReady = !persistentSettings.useRemoteNode && daemonReady
}
appWindow.isMining = isMining; appWindow.isMining = isMining;
updateStatusText() updateStatusText(hashrate)
startSoloMinerButton.enabled = !appWindow.isMining && daemonReady startSoloMinerButton.enabled = !appWindow.isMining && daemonReady
stopSoloMinerButton.enabled = !startSoloMinerButton.enabled && daemonReady stopSoloMinerButton.enabled = !startSoloMinerButton.enabled && daemonReady
} }
function update() { function update() {
persistentSettings.allow_p2pool_mining = miningModeDropdown.currentIndex === 1;
if (persistentSettings.allow_p2pool_mining) {
p2poolManager.getStatus();
}
else {
walletManager.miningStatusAsync(); walletManager.miningStatusAsync();
} }
}
function miningError(message) {
p2poolManager.exit()
errorPopup.title = qsTr("Error starting mining") + translationManager.emptyString;
errorPopup.text = message
if (persistentSettings.useRemoteNode && !persistentSettings.allowRemoteNodeMining)
errorPopup.text += qsTr("Mining is only available on local daemons. Run a local daemon to be able to mine.<br>") + translationManager.emptyString
errorPopup.icon = StandardIcon.Critical
errorPopup.open()
}
MoneroComponents.StandardDialog { MoneroComponents.StandardDialog {
id: errorPopup id: errorPopup
@ -345,14 +582,68 @@ Rectangle {
function onPageCompleted() { function onPageCompleted() {
console.log("Mining page loaded"); console.log("Mining page loaded");
update() update()
timer.running = !persistentSettings.useRemoteNode timer.running = !persistentSettings.useRemoteNode || persistentSettings.allowRemoteNodeMining
} }
function onPageClosed() { function onPageClosed() {
timer.running = false timer.running = false
} }
function startP2PoolLocal() {
var noSync = false;
var customDaemonArgs = persistentSettings.daemonFlags.toLowerCase();
var daemonArgs = "--zmq-pub " + "tcp://127.0.0.1:18083 " + "--disable-dns-checkpoints "
if (!customDaemonArgs.includes("--zmq-pub") && !customDaemonArgs.includes("--disable-dns-checkpoints") && !customDaemonArgs.includes("--no-zmq")) {
daemonArgs = daemonArgs + customDaemonArgs;
}
var success = daemonManager.start(daemonArgs, persistentSettings.nettype, persistentSettings.blockchainDataDir, persistentSettings.bootstrapNodeAddress, noSync, persistentSettings.pruneBlockchain)
if (success) {
startP2Pool()
}
else {
miningError(qsTr("Couldn't start mining.<br>") + translationManager.emptyString)
}
}
function startP2Pool() {
var address = currentWallet.address(0, 0);
var chain = "mini"
if (chainDropdown.currentIndex === 1) {
chain = "main"
}
var p2poolArgs = persistentSettings.p2poolFlags;
var success = p2poolManager.start(p2poolArgs, address, chain, threads);
if (success)
{
update()
}
else {
miningError(qsTr("Couldn't start mining.<br>") + translationManager.emptyString)
}
}
function p2poolDownloadFailed() {
statusMessage.visible = false
errorPopup.title = qsTr("P2Pool Installation Failed") + translationManager.emptyString;
errorPopup.text = "P2Pool installation failed."
errorPopup.icon = StandardIcon.Critical
errorPopup.open()
update()
}
function p2poolDownloadSucceeded() {
statusMessage.visible = false
informationPopup.title = qsTr("P2Pool Installation Succeeded") + translationManager.emptyString;
informationPopup.text = qsTr("P2Pool has successfully installed.");
informationPopup.icon = StandardIcon.Critical
informationPopup.open()
update()
}
Component.onCompleted: { Component.onCompleted: {
walletManager.miningStatus.connect(onMiningStatus); walletManager.miningStatus.connect(onMiningStatus);
p2poolManager.p2poolStatus.connect(onMiningStatus);
p2poolManager.p2poolDownloadFailure.connect(p2poolDownloadFailed);
p2poolManager.p2poolDownloadSuccess.connect(p2poolDownloadSucceeded);
} }
} }

View file

@ -36,6 +36,8 @@ file(GLOB SOURCE_FILES
"libwalletqt/UnsignedTransaction.h" "libwalletqt/UnsignedTransaction.h"
"daemon/*.h" "daemon/*.h"
"daemon/*.cpp" "daemon/*.cpp"
"p2pool/*.h"
"p2pool/*.cpp"
"model/*.h" "model/*.h"
"model/*.cpp" "model/*.cpp"
"qt/*.h" "qt/*.h"
@ -97,6 +99,7 @@ target_include_directories(monero-wallet-gui PUBLIC
${CMAKE_SOURCE_DIR}/monero/external/qrcodegen ${CMAKE_SOURCE_DIR}/monero/external/qrcodegen
${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/daemon ${CMAKE_CURRENT_SOURCE_DIR}/daemon
${CMAKE_CURRENT_SOURCE_DIR}/p2pool
${CMAKE_CURRENT_SOURCE_DIR}/libwalletqt ${CMAKE_CURRENT_SOURCE_DIR}/libwalletqt
${CMAKE_CURRENT_SOURCE_DIR}/model ${CMAKE_CURRENT_SOURCE_DIR}/model
${CMAKE_CURRENT_SOURCE_DIR}/QR-Code-scanner ${CMAKE_CURRENT_SOURCE_DIR}/QR-Code-scanner

View file

@ -79,6 +79,7 @@
// IOS exclusions // IOS exclusions
#ifndef Q_OS_IOS #ifndef Q_OS_IOS
#include "daemon/DaemonManager.h" #include "daemon/DaemonManager.h"
#include "p2pool/P2PoolManager.h"
#endif #endif
#if defined(Q_OS_WIN) #if defined(Q_OS_WIN)
@ -401,6 +402,8 @@ Verify update binary using 'shasum'-compatible (SHA256 algo) output signed by tw
#ifndef Q_OS_IOS #ifndef Q_OS_IOS
qmlRegisterUncreatableType<DaemonManager>("moneroComponents.DaemonManager", 1, 0, "DaemonManager", qmlRegisterUncreatableType<DaemonManager>("moneroComponents.DaemonManager", 1, 0, "DaemonManager",
"DaemonManager can't be instantiated directly"); "DaemonManager can't be instantiated directly");
qmlRegisterUncreatableType<P2PoolManager>("moneroComponents.P2PoolManager", 1, 0, "P2PoolManager",
"P2PoolManager can't be instantiated directly");
#endif #endif
qmlRegisterUncreatableType<AddressBookModel>("moneroComponents.AddressBookModel", 1, 0, "AddressBookModel", qmlRegisterUncreatableType<AddressBookModel>("moneroComponents.AddressBookModel", 1, 0, "AddressBookModel",
"AddressBookModel can't be instantiated directly"); "AddressBookModel can't be instantiated directly");
@ -462,7 +465,9 @@ Verify update binary using 'shasum'-compatible (SHA256 algo) output signed by tw
// Exclude daemon manager from IOS // Exclude daemon manager from IOS
#ifndef Q_OS_IOS #ifndef Q_OS_IOS
DaemonManager daemonManager; DaemonManager daemonManager;
P2PoolManager p2poolManager;
engine.rootContext()->setContextProperty("daemonManager", &daemonManager); engine.rootContext()->setContextProperty("daemonManager", &daemonManager);
engine.rootContext()->setContextProperty("p2poolManager", &p2poolManager);
#endif #endif
engine.rootContext()->setContextProperty("isWindows", isWindows); engine.rootContext()->setContextProperty("isWindows", isWindows);

View file

@ -0,0 +1,238 @@
// Copyright (c) 2014-2022, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "P2PoolManager.h"
#include "net/http_client.h"
#include "common/util.h"
#include "qt/utils.h"
#include <QElapsedTimer>
#include <QFile>
#include <QMutexLocker>
#include <QFileInfo>
#include <QDir>
#include <QDebug>
#include <QUrl>
#include <QtConcurrent/QtConcurrent>
#include <QApplication>
#include <QProcess>
#include <QMap>
#include <QCryptographicHash>
void P2PoolManager::download() {
m_scheduler.run([this] {
QUrl url;
QString fileName;
QString validHash;
#ifdef Q_OS_WIN
url = "https://github.com/SChernykh/p2pool/releases/download/v1.9/p2pool-v1.9-windows-x64.zip";
fileName = "p2pool-v1.9-windows-x64.zip";
validHash = "2587903dc04a4879dca2b6f5c5b584e869928e716274a7660e24b219c9f18839";
#elif defined(Q_OS_LINUX)
url = "https://github.com/SChernykh/p2pool/releases/download/v1.9/p2pool-v1.9-linux-x64.tar.gz";
fileName = "p2pool-v1.9-linux-x64.tar.gz";
validHash = "0cd85d933ac4a76708d326698d9db3155bb29d0be82984c735fabd9e9a351b8e";
#elif defined(Q_OS_MACOS)
url = "https://github.com/SChernykh/p2pool/releases/download/v1.9/p2pool-v1.9-macos-x64.tar.gz";
fileName = "p2pool-v1.9-macos-x64.tar.gz";
validHash = "47fbdd69d719da80597dd5487f109b61e30b540499cced7b93de1ee01344351e";
#endif
QFile file(fileName);
epee::net_utils::http::http_simple_client http_client;
const epee::net_utils::http::http_response_info* response = NULL;
std::string userAgent = randomUserAgent().toStdString();
std::chrono::milliseconds timeout = std::chrono::seconds(10);
http_client.set_server(url.host().toStdString(), "443", {});
bool success = http_client.invoke_get(url.path().toStdString(), timeout, {}, std::addressof(response), {{"User-Agent", userAgent}});
if (response->m_response_code == 302) {
epee::net_utils::http::fields_list fields = response->m_header_info.m_etc_fields;
for (std::pair<std::string, std::string> i : fields) {
if (i.first == "Location") {
url = QString::fromStdString(i.second);
http_client.set_server(url.host().toStdString(), "443", {});
std::string query = url.query(QUrl::FullyEncoded).toStdString();
std::string path = url.path().toStdString() + "?" + query;
http_client.wipe_response();
success = http_client.invoke_get(path, timeout, {}, std::addressof(response), {{"User-Agent", userAgent}});
}
}
}
if (!success) {
emit p2poolDownloadFailure();
}
else {
std::string stringData = response->m_body;
QByteArray data(stringData.c_str(), stringData.length());
QByteArray hashData = QCryptographicHash::hash(data, QCryptographicHash::Sha256);
QString hash = hashData.toHex();
if (hash != validHash) {
emit p2poolDownloadFailure();
}
else {
file.open(QIODevice::WriteOnly);
file.write(data);
file.close();
QProcess::execute("tar", {"-xzf", fileName, "--strip=1", "-C", QApplication::applicationDirPath()});
QFile::remove(fileName);
if (isInstalled()) {
emit p2poolDownloadSuccess();
}
else {
emit p2poolDownloadFailure();
}
}
}
});
return;
}
bool P2PoolManager::isInstalled() {
if (!QFileInfo(m_p2pool).isFile())
{
return false;
}
return true;
}
void P2PoolManager::getStatus() {
QString statsPath = QApplication::applicationDirPath() + "/stats/local/miner";
bool status = true;
if (!QFileInfo(statsPath).isFile() || !started)
{
status = started;
emit p2poolStatus(status, 0);
return;
}
QFile statsFile(statsPath);
statsFile.open(QIODevice::ReadOnly);
QTextStream statsOut(&statsFile);
QByteArray data;
statsOut >> data;
statsFile.close();
QJsonDocument json = QJsonDocument::fromJson(data);
QJsonObject jsonObj = json.object();
int hashrate = jsonObj.value("current_hashrate").toInt();
emit p2poolStatus(status, hashrate);
return;
}
bool P2PoolManager::start(const QString &flags, const QString &address, const QString &chain, const QString &threads)
{
// prepare command line arguments and pass to p2pool
QStringList arguments;
// Custom startup flags for p2pool
foreach (const QString &str, flags.split(" ")) {
qDebug() << QString(" [%1] ").arg(str);
if (!str.isEmpty())
arguments << str;
}
if (!arguments.contains("--local-api")) {
arguments << "--local-api";
}
if (!arguments.contains("--data-api")) {
QDir dir;
QString dirName = QApplication::applicationDirPath() + "/stats/";
QDir statsDir(dirName);
if (dir.exists(dirName)) {
statsDir.removeRecursively();
}
dir.mkdir(dirName);
arguments << "--data-api" << dirName;
}
if (!arguments.contains("--start-mining")) {
arguments << "--start-mining" << threads;
}
if (chain == "mini") {
arguments << "--mini";
}
if (!arguments.contains("--wallet")) {
arguments << "--wallet" << address;
}
qDebug() << "starting p2pool " + m_p2pool;
qDebug() << "With command line arguments " << arguments;
QMutexLocker locker(&m_p2poolMutex);
m_p2poold.reset(new QProcess());
// Set program parameters
m_p2poold->setProgram(m_p2pool);
m_p2poold->setArguments(arguments);
m_p2poold->setWorkingDirectory(QApplication::applicationDirPath());
// Start p2pool
started = m_p2poold->startDetached();
if (!started) {
qDebug() << "P2Pool start error: " + m_p2poold->errorString();
emit p2poolStartFailure();
return false;
}
return true;
}
void P2PoolManager::exit()
{
qDebug("P2PoolManager: exit()");
#ifdef Q_OS_WIN
QProcess::execute("taskkill", {"/F", "/IM", "p2pool.exe"});
#else
QProcess::execute("pkill", {"p2pool"});
#endif
started = false;
QString dirName = QApplication::applicationDirPath() + "/stats/";
QDir dir(dirName);
dir.removeRecursively();
}
P2PoolManager::P2PoolManager(QObject *parent)
: QObject(parent)
, m_scheduler(this)
{
started = false;
// Platform dependent path to p2pool
#ifdef Q_OS_WIN
m_p2pool = QApplication::applicationDirPath() + "/p2pool.exe";
#elif defined(Q_OS_UNIX)
m_p2pool = QApplication::applicationDirPath() + "/p2pool";
#endif
if (m_p2pool.length() == 0) {
qCritical() << "no p2pool binary defined for current platform";
}
}
P2PoolManager::~P2PoolManager() {
m_scheduler.shutdownWaitForFinished();
}

View file

@ -0,0 +1,72 @@
// Copyright (c) 2014-2022, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other
// materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors may be
// used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
// THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
// THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef P2POOLMANAGER_H
#define P2POOLMANAGER_H
#include <memory>
#include <QMutex>
#include <QObject>
#include <QUrl>
#include <QProcess>
#include "NetworkType.h"
#include "qt/FutureScheduler.h"
class P2PoolManager : public QObject
{
Q_OBJECT
public:
explicit P2PoolManager(QObject *parent = 0);
~P2PoolManager();
Q_INVOKABLE bool start(const QString &flags, const QString &address, const QString &chain, const QString &threads);
Q_INVOKABLE void exit();
Q_INVOKABLE bool isInstalled();
Q_INVOKABLE void getStatus();
Q_INVOKABLE void download();
private:
bool running(NetworkType::Type nettype) const;
signals:
void p2poolStartFailure() const;
void p2poolStatus(bool isMining, int hashrate) const;
void p2poolDownloadFailure() const;
void p2poolDownloadSuccess() const;
private:
std::unique_ptr<QProcess> m_p2poold;
QMutex m_p2poolMutex;
QString m_p2pool;
bool started = false;
mutable FutureScheduler m_scheduler;
};
#endif // P2POOLMANAGER_H