diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a07fce8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,41 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof + +*.log +*.wallet +*.address +deploy/ +linux/ +otherInfos/ +rcc_cgo_linux_linux_amd64.go +rcc.cpp +rcc.qrc +moc_cgo_linux_linux_amd64.go +moc_moc.h +moc.cpp +moc.go +moc.h +*plugin_import.cpp +*windows_amd64.go \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..5f5ff16 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,166 @@ + + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/README.md b/README.md index 81b057f..69c9be6 100644 --- a/README.md +++ b/README.md @@ -1 +1,3 @@ -# TurtleCoin-Nest +# TurtleCoin Nest + +The universal GUI wallet for TurtleCoin \ No newline at end of file diff --git a/main.go b/main.go new file mode 100644 index 0000000..b239c99 --- /dev/null +++ b/main.go @@ -0,0 +1,452 @@ +package main + +import ( + "TurtleCoin-Nest/walletdmanager" + "os/exec" + "runtime" + "sort" + "strconv" + "time" + + "os" + + "github.com/atotto/clipboard" + + "github.com/therecipe/qt/core" + "github.com/therecipe/qt/gui" + "github.com/therecipe/qt/qml" + "github.com/therecipe/qt/quickcontrols2" + + log "github.com/sirupsen/logrus" +) + +var ( + // qmlObjects = make(map[string]*core.QObject) + qmlBridge *QmlBridge + + transfers []walletdmanager.Transfer + + tickerRefreshWalletData *time.Ticker + + logFileFilename = "turtlecoin-nest-logs.log" +) + +// QmlBridge is the bridge between qml and go +type QmlBridge struct { + core.QObject + + _ func(data string) `signal:"displayTotalBalance"` + _ func(data string) `signal:"displayAvailableBalance"` + _ func(data string) `signal:"displayLockedBalance"` + _ func(data string) `signal:"displayAddress"` + _ func(paymentID string, + transactionID string, + amount string, + confirmations string, + time string, + number string) `signal:"addTransactionToList"` + _ func(text string, + time int) `signal:"displayPopup"` + _ func(syncing string, + blocks string, + peers string) `signal:"displaySyncingInfo"` + _ func(errorMessage string) `signal:"displayErrorDialog"` + _ func() `signal:"clearTransferAmount"` + _ func() `signal:"clearListTransactions"` + _ func(filename string, + privateViewKey string, + privateSpendKey string, + walletAddress string) `signal:"displayPrivateKeys"` + _ func() `signal:"displayOpenWalletScreen"` + _ func() `signal:"displayMainWalletScreen"` + _ func() `signal:"finishedLoadingWalletd"` + _ func() `signal:"finishedCreatingWallet"` + + _ func(msg string) `slot:"log"` + _ func(transactionID string) `slot:"clickedButtonExplorer"` + _ func(transactionID string) `slot:"clickedButtonCopyTx"` + _ func() `slot:"clickedButtonCopyAddress"` + _ func(transferAddress string, + transferAmount string, + transferPaymentID string) `slot:"clickedButtonSend"` + _ func() `slot:"clickedButtonBackupWallet"` + _ func() `slot:"clickedOpenAnotherWallet"` + _ func(pathToWallet string, + passwordWallet string) `slot:"clickedButtonOpen"` + _ func(filenameWallet string, + passwordWallet string) `slot:"clickedButtonCreate"` + _ func(filenameWallet string, + passwordWallet string, + privateViewKey string, + privateSpendKey string) `slot:"clickedButtonImport"` + + _ func(object *core.QObject) `slot:"registerToGo"` + _ func(objectName string) `slot:"deregisterToGo"` +} + +func main() { + + f, err := os.OpenFile(logFileFilename, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666) + if err != nil { + log.Fatal("error opening file: ", err) + } + defer f.Close() + + log.SetOutput(f) + + log.SetLevel(log.DebugLevel) + + log.Info("Application started") + + gui.NewQGuiApplication(len(os.Args), os.Args) + + // Enable high DPI scaling + // app.SetAttribute(core.Qt__AA_EnableHighDpiScaling, true) + + // Use the material style for qml + quickcontrols2.QQuickStyle_SetStyle("material") + + engine := qml.NewQQmlApplicationEngine(nil) + engine.Load(core.NewQUrl3("qrc:/qml/nestmain.qml", 0)) + + qmlBridge = NewQmlBridge(nil) + + qmlBridge.ConnectLog(func(msg string) { + + log.Info("QML: ", msg) + + }) + + qmlBridge.ConnectClickedButtonCopyAddress(func() { + + clipboard.WriteAll(walletdmanager.WalletAddress) + + qmlBridge.DisplayPopup("Copied!", 1500) + + }) + + qmlBridge.ConnectClickedButtonCopyTx(func(transactionID string) { + + clipboard.WriteAll(transactionID) + + qmlBridge.DisplayPopup("Copied!", 1500) + + }) + + qmlBridge.ConnectClickedButtonExplorer(func(transactionID string) { + + url := "https://turtle-coin.com/?hash=" + transactionID + "#blockchain_transaction" + successOpenBrowser := openBrowser(url) + + if !successOpenBrowser { + log.Error("failure opening browser, url: " + url) + } + + }) + + qmlBridge.ConnectClickedButtonSend(func(transferAddress string, transferAmount string, transferPaymentID string) { + + transfer(transferAddress, transferAmount, transferPaymentID) + + }) + + qmlBridge.ConnectClickedButtonBackupWallet(func() { + + showWalletPrivateInfo() + + }) + + qmlBridge.ConnectClickedButtonOpen(func(pathToWallet string, passwordWallet string) { + + go func() { + + startWalletWithWalletInfo(pathToWallet, passwordWallet) + + }() + + }) + + qmlBridge.ConnectClickedButtonCreate(func(filenameWallet string, passwordWallet string) { + + go func() { + + createWalletWithWalletInfo(filenameWallet, passwordWallet) + + }() + + }) + + qmlBridge.ConnectClickedButtonImport(func(filenameWallet string, passwordWallet string, privateViewKey string, privateSpendKey string) { + + go func() { + + importWalletWithWalletInfo(filenameWallet, passwordWallet, privateViewKey, privateSpendKey) + + }() + + }) + + qmlBridge.ConnectClickedOpenAnotherWallet(func() { + + openAnotherWallet() + + }) + + engine.RootContext().SetContextProperty("QmlBridge", qmlBridge) + + gui.QGuiApplication_Exec() + + log.Info("Application closed") + + walletdmanager.StopWalletd() + +} + +func startDisplayWalletInfo() { + + getAndDisplayBalances() + + getAndDisplayAddress() + + getAndDisplayListTransactions() + + getAndDisplayConnectionInfo() + + go func() { + + tickerRefreshWalletData = time.NewTicker(time.Second * 15) + + for range tickerRefreshWalletData.C { + + getAndDisplayBalances() + + getAndDisplayListTransactions() + + getAndDisplayConnectionInfo() + + } + + }() + +} + +func getAndDisplayBalances() { + + walletAvailableBalance, walletLockedBalance, walletTotalBalance := walletdmanager.RequestBalance() + + qmlBridge.DisplayAvailableBalance(strconv.FormatFloat(walletAvailableBalance, 'f', -1, 64)) + qmlBridge.DisplayLockedBalance(strconv.FormatFloat(walletLockedBalance, 'f', -1, 64)) + qmlBridge.DisplayTotalBalance(strconv.FormatFloat(walletTotalBalance, 'f', -1, 64)) + +} + +func getAndDisplayAddress() { + + walletAddress := walletdmanager.RequestAddress() + + qmlBridge.DisplayAddress(walletAddress) + +} + +func getAndDisplayConnectionInfo() { + + syncing, blockCount, knownBlockCount, peers, err := walletdmanager.RequestConnectionInfo() + + if err == nil { + + blocks := blockCount + " / " + knownBlockCount + + qmlBridge.DisplaySyncingInfo(syncing, blocks, peers) + + } + +} + +func getAndDisplayListTransactions() { + + newTransfers := walletdmanager.RequestListTransactions() + + if len(newTransfers) != len(transfers) { + + transfers = newTransfers + + // sort starting by the most recent transaction + sort.Slice(transfers, func(i, j int) bool { return transfers[i].Timestamp.After(transfers[j].Timestamp) }) + + transactionNumber := len(transfers) + + qmlBridge.ClearListTransactions() + + for _, transfer := range transfers { + + amount := transfer.Amount + amountString := "" + if amount >= 0 { + amountString += "+ " + amountString += strconv.FormatFloat(amount, 'f', -1, 64) + } else { + amountString += "- " + amountString += strconv.FormatFloat(-amount, 'f', -1, 64) + } + amountString += " TRTL (fee: " + strconv.FormatFloat(transfer.Fee, 'f', 2, 64) + ")" + + confirmationsString := "(" + strconv.Itoa(transfer.Confirmations) + " conf.)" + + timeString := transfer.Timestamp.Format("2006-01-02 15:04:05") + + transactionNumberString := strconv.Itoa(transactionNumber) + ")" + transactionNumber-- + + qmlBridge.AddTransactionToList(transfer.PaymentID, transfer.TxID, amountString, confirmationsString, timeString, transactionNumberString) + + } + + } + +} + +func transfer(transferAddress string, transferAmount string, transferPaymentID string) bool { + + log.Info("SEND: ", transferAddress, transferAmount, transferPaymentID) + + transactionID, err := walletdmanager.SendTransaction(transferAddress, transferAmount, transferPaymentID) + + if err != nil { + + log.Warn("error transfer: ", err) + + qmlBridge.DisplayErrorDialog(err.Error()) + + return false + + } + + log.Info("succes transfer: ", transactionID) + + getAndDisplayBalances() + + qmlBridge.ClearTransferAmount() + + qmlBridge.DisplayPopup("TRTLs sent successfully", 4000) + + return true + +} + +func startWalletWithWalletInfo(pathToWallet string, passwordWallet string) bool { + + err := walletdmanager.StartWalletd(pathToWallet, passwordWallet) + + if err != nil { + + log.Warn("error starting walletd with provided wallet info. error: ", err) + + qmlBridge.FinishedLoadingWalletd() + + qmlBridge.DisplayErrorDialog(err.Error()) + + return false + + } + + log.Info("success starting walletd") + + qmlBridge.FinishedLoadingWalletd() + + startDisplayWalletInfo() + + qmlBridge.DisplayMainWalletScreen() + + return true + +} + +func createWalletWithWalletInfo(filenameWallet string, passwordWallet string) bool { + + err := walletdmanager.CreateWallet(filenameWallet, passwordWallet, "", "") + + if err != nil { + + log.Warn("error creating wallet. error: ", err) + + qmlBridge.FinishedCreatingWallet() + + qmlBridge.DisplayErrorDialog(err.Error()) + + return false + + } + + log.Info("success creating wallet") + + startWalletWithWalletInfo(filenameWallet, passwordWallet) + + showWalletPrivateInfo() + + return true + +} + +func importWalletWithWalletInfo(filenameWallet string, passwordWallet string, privateViewKey string, privateSpendKey string) bool { + + err := walletdmanager.CreateWallet(filenameWallet, passwordWallet, privateViewKey, privateSpendKey) + + if err != nil { + + log.Warn("error importing wallet. error: ", err) + + qmlBridge.FinishedCreatingWallet() + + qmlBridge.DisplayErrorDialog(err.Error()) + + return false + + } + + log.Info("success importing wallet") + + startWalletWithWalletInfo(filenameWallet, passwordWallet) + + return true + +} + +func openAnotherWallet() { + + tickerRefreshWalletData.Stop() + + walletdmanager.StopWalletd() + + qmlBridge.DisplayOpenWalletScreen() + +} + +func showWalletPrivateInfo() { + + privateViewKey, privateSpendKey, err := walletdmanager.GetPrivateViewKeyAndSpendKey() + + if err != nil { + + log.Error("Error getting view and spend key: ", err) + + } else { + + qmlBridge.DisplayPrivateKeys(walletdmanager.WalletFilename, privateViewKey, privateSpendKey, walletdmanager.WalletAddress) + + } + +} + +func openBrowser(url string) bool { + var args []string + switch runtime.GOOS { + case "darwin": + args = []string{"open"} + case "windows": + args = []string{"cmd", "/c", "start"} + default: + args = []string{"xdg-open"} + } + cmd := exec.Command(args[0], append(args[1:], url)...) + return cmd.Start() == nil +} diff --git a/qml/ItemListTransaction.qml b/qml/ItemListTransaction.qml new file mode 100644 index 0000000..aba9187 --- /dev/null +++ b/qml/ItemListTransaction.qml @@ -0,0 +1,134 @@ +import QtQuick 2.7 +import QtQuick.Controls 2.1 + +Item { + id: itemListTransaction + visible: true + property bool newTransaction: false + Text { + id: transactionAmount + color: "#cfcfcf" + text: transactionAmountValue + verticalAlignment: Text.AlignVCenter + anchors.left: parent.left + anchors.leftMargin: 35 + anchors.top: parent.top + anchors.topMargin: 5 + font.family: "Arial" + font.bold: true + font.pixelSize: 17 + } + + Text { + id: transactionID + color: "#cfcfcf" + text: "Tr. ID: " + transactionIDValue + anchors.top: transactionAmount.bottom + anchors.topMargin: 8 + anchors.left: transactionAmount.left + anchors.leftMargin: 0 + verticalAlignment: Text.AlignVCenter + font.family: "Arial" + font.pixelSize: 11 + font.bold: false + } + + Text { + id: transactionPaymentID + color: "#cfcfcf" + text: "Payment ID: " + transactionPaymentIDValue + anchors.top: transactionID.bottom + anchors.topMargin: 8 + anchors.left: transactionID.left + anchors.leftMargin: 0 + verticalAlignment: Text.AlignVCenter + font.family: "Arial" + font.pixelSize: 11 + font.bold: false + } + + Text { + id: transactionTime + x: 196 + y: 8 + color: "#cfcfcf" + text: transactionTimeValue + anchors.right: transactionConfirmations.left + anchors.rightMargin: 15 + anchors.verticalCenter: transactionAmount.verticalCenter + horizontalAlignment: Text.AlignRight + verticalAlignment: Text.AlignVCenter + font.pixelSize: 12 + font.bold: false + font.family: "Arial" + } + + Text { + id: transactionConfirmations + x: 310 + y: 8 + color: "#cfcfcf" + text: transactionConfirmationsValue + anchors.right: parent.right + anchors.rightMargin: 5 + anchors.verticalCenter: transactionTime.verticalCenter + horizontalAlignment: Text.AlignRight + verticalAlignment: Text.AlignVCenter + font.pixelSize: 12 + font.bold: false + font.family: "Arial" + } + + Text { + id: transactionNumber + color: "#cfcfcf" + text: transactionNumberValue + anchors.top: transactionAmount.top + anchors.topMargin: 0 + anchors.left: parent.left + anchors.leftMargin: 5 + font.bold: false + font.family: "Arial" + font.pixelSize: 11 + verticalAlignment: Text.AlignVCenter + } + + Button { + id: buttonCopyTxID + width: 13 + height: 14 + hoverEnabled: true + anchors.verticalCenter: transactionID.verticalCenter + anchors.left: transactionID.right + anchors.leftMargin: 10 + Image { + id: imageButtonCopyTxID + sourceSize.height: 13 + sourceSize.width: 14 + fillMode: Image.PreserveAspectFit + source: "images/copy_white.png" + } + onClicked: { + QmlBridge.clickedButtonCopyTx(transactionIDValue); + popupText.show("Copied!") + } + } + + Button { + id: buttonExplorerTxID + width: 13 + height: 14 + hoverEnabled: true + anchors.verticalCenter: buttonCopyTxID.verticalCenter + anchors.left: buttonCopyTxID.right + anchors.leftMargin: 10 + Image { + id: imageButtonExplorerTxID + sourceSize.height: 13 + sourceSize.width: 14 + fillMode: Image.PreserveAspectFit + source: "images/search_white.png" + } + onClicked: QmlBridge.clickedButtonExplorer(transactionIDValue) + } +} diff --git a/qml/OpenWallet.qml b/qml/OpenWallet.qml new file mode 100644 index 0000000..a5e6da5 --- /dev/null +++ b/qml/OpenWallet.qml @@ -0,0 +1,746 @@ +import QtQuick.Window 2.2 +import QtQuick 2.7 +import QtQuick.Controls 2.3 +import QtQuick.Controls.Styles 1.4 +import QtQuick.Dialogs 1.2 +import QtQuick.Layouts 1.1 + +Rectangle { + id: rectangleOpenWallet + anchors.fill: parent + color: "transparent" + + Text { + id: textOpenWalletDescr + color: "#ffffff" + text: qsTr("Welcome to your TurtleCoin wallet. Choose one of the options below. If you are new to TurtleCoin, create a new wallet.") + anchors.right: parent.right + anchors.rightMargin: 15 + anchors.left: parent.left + anchors.leftMargin: 40 + anchors.top: parent.top + anchors.topMargin: 40 + font.pixelSize: 14 + verticalAlignment: Text.AlignBottom + font.family: "Arial" + font.bold: true + horizontalAlignment: Text.AlignLeft + } + + // section open existing wallet + Rectangle { + id: rectangleOpenExistingWallet + color: "transparent" + anchors.left: parent.left + anchors.leftMargin: 10 + anchors.right: parent.right + anchors.rightMargin: 10 + anchors.top: textOpenWalletDescr.bottom + anchors.topMargin: 50 + height: 120 + radius: 7 + + Text { + id: textOpenExistingWalletDescr + color: "#ffffff" + text: qsTr("Open an existing wallet") + horizontalAlignment: Text.AlignLeft + verticalAlignment: Text.AlignBottom + font.bold: true + font.pixelSize: 16 + font.family: "Arial" + anchors.top: parent.top + anchors.topMargin: 10 + anchors.left: parent.left + anchors.leftMargin: 40 + } + + Text { + id: textExistingWalletPathDescr + color: "#ffffff" + text: qsTr("Path to wallet file") + horizontalAlignment: Text.AlignLeft + verticalAlignment: Text.AlignBottom + font.pixelSize: 14 + font.family: "Arial" + anchors.top: textOpenExistingWalletDescr.bottom + anchors.topMargin: 20 + anchors.left: parent.left + anchors.leftMargin: 80 + } + + Rectangle { + id: rectangleTextInputExistingWalletPath + color: "#555555" + height: 25 + width: 360 + anchors.top: textExistingWalletPathDescr.bottom + anchors.topMargin: 15 + anchors.left: textExistingWalletPathDescr.left + anchors.leftMargin: 0 + radius: 3 + + TextInput { + id: textInputExistingWalletPath + readOnly: true + anchors.fill: parent + color: "#cfcfcf" + text: qsTr("") + rightPadding: 5 + leftPadding: 5 + selectionColor: "#eeeeee" + selectedTextColor: "#999999" + selectByMouse: true + clip: true + font.family: "Arial" + horizontalAlignment: Text.AlignLeft + font.pixelSize: 14 + verticalAlignment: Text.AlignVCenter + + onTextChanged: { + buttonOpenWallet.enabled = textInputExistingWalletPath.text != "" && textInputExistingWalletPassword.text != "" + } + } + + MouseArea { + id: mouseAreaExistingWalletPath + anchors.fill: parent + onClicked: { + dialogChooseWalletFile.show(); + } + } + } + + Text { + id: textExistingWalletPasswordDescr + color: "#ffffff" + text: qsTr("Password") + horizontalAlignment: Text.AlignLeft + verticalAlignment: Text.AlignBottom + font.pixelSize: 14 + font.family: "Arial" + anchors.top: textExistingWalletPathDescr.top + anchors.topMargin: 0 + anchors.left: parent.left + anchors.leftMargin: 520 + } + + Rectangle { + id: rectangleTextInputExistingWalletPassword + color: "#555555" + height: 25 + width: 200 + anchors.top: rectangleTextInputExistingWalletPath.top + anchors.topMargin: 0 + anchors.left: textExistingWalletPasswordDescr.left + anchors.leftMargin: 0 + radius: 3 + + TextInput { + id: textInputExistingWalletPassword + echoMode: TextInput.Password + anchors.fill: parent + color: "#cfcfcf" + text: qsTr("") + rightPadding: 5 + leftPadding: 5 + selectionColor: "#eeeeee" + selectedTextColor: "#999999" + selectByMouse: true + clip: true + font.family: "Arial" + horizontalAlignment: Text.AlignLeft + font.pixelSize: 14 + verticalAlignment: Text.AlignVCenter + + onTextChanged: { + buttonOpenWallet.enabled = textInputExistingWalletPath.text != "" && textInputExistingWalletPassword.text != "" + } + } + + } + + Button { + id: buttonOpenWallet + text: qsTr("OPEN") + anchors.right: parent.right + anchors.rightMargin: 60 + anchors.bottom: parent.bottom + anchors.bottomMargin: 15 + enabled: false + + contentItem: Text { + text: buttonOpenWallet.text + font.bold: true + font.pointSize: 20 + font.family: "Arial" + opacity: enabled ? 1.0 : 0.3 + color: buttonOpenWallet.down ? "#dddddd" : "#ffffff" + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + } + + background: Rectangle { + implicitWidth: 140 + implicitHeight: 60 + opacity: enabled ? 1 : 0.3 + radius: 6 + color: buttonOpenWallet.down ? "#383838" : "#444444" + } + + onClicked: { + busyIndicator.running = true + QmlBridge.clickedButtonOpen(textInputExistingWalletPath.text, textInputExistingWalletPassword.text); + textInputExistingWalletPassword.text = "" + } + } + } + + // separator horizontal 1 + Rectangle { + height: 2 + color: "#858585" + anchors.top: rectangleOpenExistingWallet.bottom + anchors.topMargin: 10 + anchors.left: rectangleOpenExistingWallet.left + anchors.leftMargin: 30 + anchors.right: rectangleOpenExistingWallet.right + anchors.rightMargin: 30 + } + + // section create new wallet + Rectangle { + id: rectangleCreateWallet + color: "transparent" + anchors.left: rectangleOpenExistingWallet.left + anchors.leftMargin: 0 + anchors.right: rectangleOpenExistingWallet.right + anchors.rightMargin: 0 + anchors.top: rectangleOpenExistingWallet.bottom + anchors.topMargin: 20 + height: 160 + radius: 7 + + Text { + id: textCreateWalletDescr + color: "#ffffff" + text: qsTr("Create a new wallet") + horizontalAlignment: Text.AlignLeft + verticalAlignment: Text.AlignBottom + font.bold: true + font.pixelSize: 16 + font.family: "Arial" + anchors.top: parent.top + anchors.topMargin: 10 + anchors.left: parent.left + anchors.leftMargin: 40 + } + + Text { + id: textCreateWalletFilenameDescr + color: "#ffffff" + text: qsTr("Choose a filename for your new wallet file") + horizontalAlignment: Text.AlignLeft + verticalAlignment: Text.AlignBottom + font.pixelSize: 14 + font.family: "Arial" + anchors.top: textCreateWalletDescr.bottom + anchors.topMargin: 20 + anchors.left: parent.left + anchors.leftMargin: 80 + } + + Rectangle { + id: rectangleTextInputCreateWalletFilename + color: "#555555" + height: 25 + width: 200 + anchors.top: textCreateWalletFilenameDescr.bottom + anchors.topMargin: 15 + anchors.left: textCreateWalletFilenameDescr.left + anchors.leftMargin: 0 + radius: 3 + + TextInput { + id: textInputCreateWalletFilename + anchors.fill: parent + color: "#cfcfcf" + text: qsTr("myFirstTRTLWallet") + rightPadding: 5 + leftPadding: 5 + selectionColor: "#eeeeee" + selectedTextColor: "#999999" + selectByMouse: true + clip: true + font.family: "Arial" + horizontalAlignment: Text.AlignLeft + font.pixelSize: 14 + verticalAlignment: Text.AlignVCenter + + onTextChanged: { + buttonCreateWallet.enabled = textInputCreateWalletFilename.text != "" && textInputCreateWalletPassword.text != "" + } + } + } + + Text { + id: textCreateWalletFilename + color: "#999999" + text: textInputCreateWalletFilename.text + ".wallet" + anchors.verticalCenter: rectangleTextInputCreateWalletFilename.verticalCenter + anchors.left: rectangleTextInputCreateWalletFilename.right + anchors.leftMargin: 20 + font.pixelSize: 13 + verticalAlignment: Text.AlignBottom + font.family: "Arial" + font.bold: false + horizontalAlignment: Text.AlignLeft + } + + Text { + id: textCreateWalletExtensionDescr + color: "#999999" + text: qsTr("Do not include any extension, a \".walet\" will be added automatically. \nAvoid spaces and most special characters in the filename.") + anchors.top: rectangleTextInputCreateWalletFilename.bottom + anchors.topMargin: 12 + anchors.left: rectangleTextInputCreateWalletFilename.left + anchors.leftMargin: 0 + font.pixelSize: 13 + verticalAlignment: Text.AlignBottom + font.family: "Arial" + font.bold: false + horizontalAlignment: Text.AlignLeft + } + + Text { + id: textCreateWalletPasswordDescr + color: "#ffffff" + text: qsTr("Choose a strong password") + horizontalAlignment: Text.AlignLeft + verticalAlignment: Text.AlignBottom + font.pixelSize: 14 + font.family: "Arial" + anchors.top: textCreateWalletFilenameDescr.top + anchors.topMargin: 0 + anchors.left: parent.left + anchors.leftMargin: 520 + } + + Rectangle { + id: rectangleTextInputCreateWalletPassword + color: "#555555" + height: 25 + width: 200 + anchors.top: rectangleTextInputCreateWalletFilename.top + anchors.topMargin: 0 + anchors.left: textCreateWalletPasswordDescr.left + anchors.leftMargin: 0 + radius: 3 + + TextInput { + id: textInputCreateWalletPassword + echoMode: TextInput.Password + anchors.fill: parent + color: "#cfcfcf" + text: qsTr("") + rightPadding: 5 + leftPadding: 5 + selectionColor: "#eeeeee" + selectedTextColor: "#999999" + selectByMouse: true + clip: true + font.family: "Arial" + horizontalAlignment: Text.AlignLeft + font.pixelSize: 14 + verticalAlignment: Text.AlignVCenter + + onTextChanged: { + buttonCreateWallet.enabled = textInputCreateWalletFilename.text != "" && textInputCreateWalletPassword.text != "" + } + } + } + + Button { + id: buttonCreateWallet + text: qsTr("CREATE") + anchors.right: parent.right + anchors.rightMargin: 60 + anchors.bottom: parent.bottom + anchors.bottomMargin: 15 + enabled: false + + contentItem: Text { + text: buttonCreateWallet.text + font.bold: true + font.pointSize: 20 + font.family: "Arial" + opacity: enabled ? 1.0 : 0.3 + color: buttonOpenWallet.down ? "#dddddd" : "#ffffff" + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + } + + background: Rectangle { + implicitWidth: 140 + implicitHeight: 60 + opacity: enabled ? 1 : 0.3 + radius: 6 + color: buttonCreateWallet.down ? "#383838" : "#444444" + } + + onClicked: { + busyIndicator.running = true + QmlBridge.clickedButtonCreate(textCreateWalletFilename.text, textInputCreateWalletPassword.text); + textInputCreateWalletPassword.text = "" + } + } + } + + // separator horizontal 2 + Rectangle { + height: 2 + color: "#858585" + anchors.top: rectangleCreateWallet.bottom + anchors.topMargin: 10 + anchors.left: rectangleOpenExistingWallet.left + anchors.leftMargin: 30 + anchors.right: rectangleOpenExistingWallet.right + anchors.rightMargin: 30 + } + + // section import wallet from keys + Rectangle { + id: rectangleImportWalletFromKeys + color: "transparent" + anchors.left: rectangleOpenExistingWallet.left + anchors.leftMargin: 0 + anchors.right: rectangleOpenExistingWallet.right + anchors.rightMargin: 0 + anchors.top: rectangleCreateWallet.bottom + anchors.topMargin: 20 + anchors.bottom: parent.bottom + anchors.bottomMargin: 10 + radius: 7 + + Text { + id: textImportWalletDescr + color: "#ffffff" + text: qsTr("Import wallet from keys") + horizontalAlignment: Text.AlignLeft + verticalAlignment: Text.AlignBottom + font.bold: true + font.pixelSize: 16 + font.family: "Arial" + anchors.top: parent.top + anchors.topMargin: 10 + anchors.left: parent.left + anchors.leftMargin: 40 + } + + Text { + id: textImportWalletFilenameDescr + color: "#ffffff" + text: qsTr("Choose a filename for your new wallet file") + horizontalAlignment: Text.AlignLeft + verticalAlignment: Text.AlignBottom + font.pixelSize: 14 + font.family: "Arial" + anchors.top: textImportWalletDescr.bottom + anchors.topMargin: 20 + anchors.left: parent.left + anchors.leftMargin: 80 + } + + Rectangle { + id: rectangleTextInputImportWalletFilename + color: "#555555" + height: 25 + width: 200 + anchors.top: textImportWalletFilenameDescr.bottom + anchors.topMargin: 15 + anchors.left: textImportWalletFilenameDescr.left + anchors.leftMargin: 0 + radius: 3 + + TextInput { + id: textInputImportWalletFilename + anchors.fill: parent + color: "#cfcfcf" + text: qsTr("myTRTLWallet") + rightPadding: 5 + leftPadding: 5 + selectionColor: "#eeeeee" + selectedTextColor: "#999999" + selectByMouse: true + clip: true + font.family: "Arial" + horizontalAlignment: Text.AlignLeft + font.pixelSize: 14 + verticalAlignment: Text.AlignVCenter + + onTextChanged: { + rectangleImportWalletFromKeys.checkEnableButton() + } + } + } + + Text { + id: textImportWalletFilename + color: "#999999" + text: textInputImportWalletFilename.text + ".wallet" + anchors.verticalCenter: rectangleTextInputImportWalletFilename.verticalCenter + anchors.left: rectangleTextInputImportWalletFilename.right + anchors.leftMargin: 20 + font.pixelSize: 13 + verticalAlignment: Text.AlignBottom + font.family: "Arial" + font.bold: false + horizontalAlignment: Text.AlignLeft + } + + Text { + id: textImportWalletExtensionDescr + color: "#999999" + text: qsTr("Do not include any extension, a \".walet\" will be added automatically. \nAvoid spaces and most special characters in the filename.") + anchors.top: rectangleTextInputImportWalletFilename.bottom + anchors.topMargin: 12 + anchors.left: rectangleTextInputImportWalletFilename.left + anchors.leftMargin: 0 + font.pixelSize: 13 + verticalAlignment: Text.AlignBottom + font.family: "Arial" + font.bold: false + horizontalAlignment: Text.AlignLeft + } + + Text { + id: textImportWalletPasswordDescr + color: "#ffffff" + text: qsTr("Choose a strong password") + horizontalAlignment: Text.AlignLeft + verticalAlignment: Text.AlignBottom + font.pixelSize: 14 + font.family: "Arial" + anchors.top: textImportWalletFilenameDescr.top + anchors.topMargin: 0 + anchors.left: parent.left + anchors.leftMargin: 520 + } + + Rectangle { + id: rectangleTextInputImportWalletPassword + color: "#555555" + height: 25 + width: 200 + anchors.top: rectangleTextInputImportWalletFilename.top + anchors.topMargin: 0 + anchors.left: textImportWalletPasswordDescr.left + anchors.leftMargin: 0 + radius: 3 + + TextInput { + id: textInputImportWalletPassword + echoMode: TextInput.Password + anchors.fill: parent + color: "#cfcfcf" + text: qsTr("") + rightPadding: 5 + leftPadding: 5 + selectionColor: "#eeeeee" + selectedTextColor: "#999999" + selectByMouse: true + clip: true + font.family: "Arial" + horizontalAlignment: Text.AlignLeft + font.pixelSize: 14 + verticalAlignment: Text.AlignVCenter + + onTextChanged: { + rectangleImportWalletFromKeys.checkEnableButton() + } + } + } + + Text { + id: textImportWalletPrivateViewKeyDescr + color: "#ffffff" + text: qsTr("Private view key") + horizontalAlignment: Text.AlignLeft + verticalAlignment: Text.AlignBottom + font.pixelSize: 14 + font.family: "Arial" + anchors.top: textImportWalletExtensionDescr.bottom + anchors.topMargin: 20 + anchors.left: textImportWalletExtensionDescr.left + anchors.leftMargin: 0 + } + + Rectangle { + id: rectangleTextInputImportWalletPrivateViewKey + color: "#555555" + height: 25 + anchors.top: textImportWalletPrivateViewKeyDescr.bottom + anchors.topMargin: 15 + anchors.left: textImportWalletPrivateViewKeyDescr.left + anchors.leftMargin: 0 + anchors.right: rectangleTextInputImportWalletPassword.right + anchors.rightMargin: 0 + radius: 3 + + TextInput { + id: textInputImportWalletPrivateViewKey + anchors.fill: parent + color: "#cfcfcf" + text: qsTr("") + rightPadding: 5 + leftPadding: 5 + selectionColor: "#eeeeee" + selectedTextColor: "#999999" + selectByMouse: true + clip: true + font.family: "Arial" + horizontalAlignment: Text.AlignLeft + font.pixelSize: 14 + verticalAlignment: Text.AlignVCenter + + onTextChanged: { + rectangleImportWalletFromKeys.checkEnableButton() + } + } + } + + Text { + id: textImportWalletPrivateSpendKeyDescr + color: "#ffffff" + text: qsTr("Private spend key") + horizontalAlignment: Text.AlignLeft + verticalAlignment: Text.AlignBottom + font.pixelSize: 14 + font.family: "Arial" + anchors.top: rectangleTextInputImportWalletPrivateViewKey.bottom + anchors.topMargin: 20 + anchors.left: rectangleTextInputImportWalletPrivateViewKey.left + anchors.leftMargin: 0 + } + + Rectangle { + id: rectangleTextInputImportWalletPrivateSpendKey + color: "#555555" + height: 25 + anchors.top: textImportWalletPrivateSpendKeyDescr.bottom + anchors.topMargin: 15 + anchors.left: textImportWalletPrivateSpendKeyDescr.left + anchors.leftMargin: 0 + anchors.right: rectangleTextInputImportWalletPrivateViewKey.right + anchors.rightMargin: 0 + radius: 3 + + TextInput { + id: textInputImportWalletPrivateSpendKey + anchors.fill: parent + color: "#cfcfcf" + text: qsTr("") + rightPadding: 5 + leftPadding: 5 + selectionColor: "#eeeeee" + selectedTextColor: "#999999" + selectByMouse: true + clip: true + font.family: "Arial" + horizontalAlignment: Text.AlignLeft + font.pixelSize: 14 + verticalAlignment: Text.AlignVCenter + + onTextChanged: { + rectangleImportWalletFromKeys.checkEnableButton() + } + } + } + + Button { + id: buttonImportWallet + text: qsTr("IMPORT") + anchors.right: parent.right + anchors.rightMargin: 60 + anchors.bottom: parent.bottom + anchors.bottomMargin: 15 + enabled: false + + contentItem: Text { + text: buttonImportWallet.text + font.bold: true + font.pointSize: 20 + font.family: "Arial" + opacity: enabled ? 1.0 : 0.3 + color: buttonImportWallet.down ? "#dddddd" : "#ffffff" + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + } + + background: Rectangle { + implicitWidth: 140 + implicitHeight: 60 + opacity: enabled ? 1 : 0.3 + radius: 6 + color: buttonImportWallet.down ? "#383838" : "#444444" + } + + onClicked: { + busyIndicator.running = true + QmlBridge.clickedButtonImport(textImportWalletFilename.text, textInputImportWalletPassword.text, textInputImportWalletPrivateViewKey.text, textInputImportWalletPrivateSpendKey.text); + textInputImportWalletPassword.text = "" + } + } + + function checkEnableButton() { + + buttonImportWallet.enabled = textInputImportWalletFilename.text != "" && textInputImportWalletPassword.text != "" && textInputImportWalletPrivateViewKey.text != "" && textInputImportWalletPrivateSpendKey.text != "" + + } + } + + FileDialog { + id: dialogChooseWalletFile + title: "Please select your wallet file" + visible: false + onAccepted: { + textInputExistingWalletPath.text = dialogChooseWalletFile.fileUrl + } + + function show() { + dialogChooseWalletFile.open() + } + } + + BusyIndicator { + id: busyIndicator + anchors.centerIn: parent + running: false + } + + Connections { + target: QmlBridge + + onFinishedLoadingWalletd: + { + busyIndicator.running = false + } + + onFinishedCreatingWallet: + { + busyIndicator.running = false + } + + } + + function clearData() { + + textInputImportWalletPrivateViewKey.text = "" + textInputImportWalletPrivateSpendKey.text = "" + + } + +} \ No newline at end of file diff --git a/qml/images/copy_white.png b/qml/images/copy_white.png new file mode 100644 index 0000000..4a30265 Binary files /dev/null and b/qml/images/copy_white.png differ diff --git a/qml/images/search_white.png b/qml/images/search_white.png new file mode 100644 index 0000000..a2c3061 Binary files /dev/null and b/qml/images/search_white.png differ diff --git a/qml/nestmain.qml b/qml/nestmain.qml new file mode 100644 index 0000000..b5db5e4 --- /dev/null +++ b/qml/nestmain.qml @@ -0,0 +1,1064 @@ +import QtQuick.Window 2.2 +import QtQuick 2.7 +import QtQuick.Controls 2.3 +import QtQuick.Controls.Styles 1.4 +import QtQuick.Dialogs 1.2 +import QtQuick.Layouts 1.1 + +ApplicationWindow { + id: window + width: 1060 + height: 800 + maximumHeight: height + maximumWidth: width + minimumHeight: height + minimumWidth: width + color: "#333333" + title: "TurtleCoin Nest" + visible: true + + menuBar: MenuBar { + Menu { + id: menuWallet + enabled: false + title: "Wallet" + MenuItem { + text: "Open another wallet" + onTriggered: { + dialogWarningCloseWallet.show() + } + } + MenuItem { + text: "Backup wallet" + onTriggered: { + QmlBridge.clickedButtonBackupWallet(); + } + } + } + + } + + OpenWallet { + id: openWalletScreen + anchors.fill: parent + } + + Rectangle { + id: rectangleMainWallet + anchors.fill: parent + color: "transparent" + visible: false + + Row { + id: rowAddress + y: 175 + height: 106 + spacing: 0 + anchors.right: parent.right + anchors.rightMargin: 0 + anchors.left: parent.left + anchors.leftMargin: 0 + + Button { + id: buttonCopy + width: 39 + height: 42 + hoverEnabled: true + anchors.verticalCenter: textAddress.verticalCenter + anchors.right: parent.right + anchors.rightMargin: 30 + Image { + id: image_copy + sourceSize.height: 42 + sourceSize.width: 39 + fillMode: Image.PreserveAspectFit + source: "images/copy_white.png" + } + onClicked: { + QmlBridge.clickedButtonCopyAddress(); + } + } + + TextInput { + id: textAddress + color: "#ffffff" + text: qsTr("NO WALLET OPEN") + anchors.left: parent.left + anchors.leftMargin: 40 + anchors.verticalCenterOffset: -20 + anchors.verticalCenter: parent.verticalCenter + font.family: "Arial" + font.pixelSize: 15 + horizontalAlignment: Text.AlignHCenter + font.bold: true + readOnly: true + selectionColor: "#eeeeee" + selectedTextColor: "#777777" + selectByMouse: true + + Connections { + target: QmlBridge + onDisplayAddress: + { + textAddress.text = data + } + } + } + + Text { + id: textDescrCopyAddress + color: "#858585" + text: qsTr("Copy your address to receive TRTL") + anchors.top: buttonCopy.bottom + anchors.topMargin: 25 + anchors.right: buttonCopy.right + anchors.rightMargin: 0 + font.family: "Arial" + horizontalAlignment: Text.AlignRight + font.weight: Font.Normal + font.bold: true + font.pixelSize: 15 + } + } + + Rectangle { + id: rectangleTop + height: 110 + color: "#00000000" + anchors.right: parent.right + anchors.rightMargin: 15 + anchors.left: parent.left + anchors.leftMargin: 15 + anchors.top: parent.top + anchors.topMargin: 15 + opacity: 1 + + Rectangle { + id: rectangleLockedBalance + x: 415 + width: 338 + color: "#00000000" + anchors.right: parent.right + anchors.rightMargin: 0 + anchors.bottom: parent.bottom + anchors.bottomMargin: 0 + anchors.top: parent.top + anchors.topMargin: 0 + + Text { + id: textLockedUnit + y: 1 + color: "#cfcfcf" + text: qsTr("TRTL") + anchors.right: parent.right + anchors.rightMargin: 18 + verticalAlignment: Text.AlignBottom + font.family: "Arial" + font.pixelSize: 15 + anchors.bottom: parent.bottom + anchors.left: textBalanceValue.right + anchors.leftMargin: 15 + font.bold: false + horizontalAlignment: Text.AlignLeft + anchors.bottomMargin: 10 + } + + Text { + id: textAvailableUnit + x: -8 + y: -2 + color: "#cfcfcf" + text: qsTr("TRTL") + font.family: "Arial" + font.pixelSize: 15 + anchors.right: textLockedUnit.right + anchors.bottom: textLockedUnit.top + anchors.left: textBalanceValue.right + anchors.leftMargin: 15 + anchors.rightMargin: 0 + verticalAlignment: Text.AlignBottom + font.bold: false + horizontalAlignment: Text.AlignLeft + anchors.bottomMargin: 12 + } + + Text { + id: textLockedValue + x: 7 + y: 1 + color: "#cfcfcf" + text: qsTr("0") + anchors.right: textLockedUnit.left + anchors.rightMargin: 10 + anchors.bottom: textLockedUnit.bottom + anchors.bottomMargin: -1 + font.family: "Arial" + font.pixelSize: 20 + anchors.left: textBalanceValue.right + anchors.leftMargin: 15 + verticalAlignment: Text.AlignBottom + font.bold: false + horizontalAlignment: Text.AlignRight + + Connections + { + target: QmlBridge + onDisplayLockedBalance: + { + textLockedValue.text = data + } + } + } + + Text { + id: textAvailableValue + x: 16 + y: 1 + color: "#cfcfcf" + text: qsTr("0") + anchors.right: textLockedValue.right + anchors.rightMargin: 0 + anchors.bottom: textAvailableUnit.bottom + anchors.bottomMargin: -1 + font.family: "Arial" + font.pixelSize: 20 + anchors.left: textBalanceValue.right + anchors.leftMargin: 15 + verticalAlignment: Text.AlignBottom + font.bold: false + horizontalAlignment: Text.AlignRight + + Connections + { + target: QmlBridge + onDisplayAvailableBalance: + { + textAvailableValue.text = data + } + } + } + + Text { + id: textLockedDescr + y: -10 + color: "#cfcfcf" + text: qsTr("Locked/Unconfirmed:") + anchors.bottom: textLockedUnit.bottom + anchors.bottomMargin: 0 + font.family: "Arial" + font.pixelSize: 15 + anchors.left: parent.left + anchors.leftMargin: 10 + verticalAlignment: Text.AlignBottom + font.bold: false + horizontalAlignment: Text.AlignLeft + } + + Text { + id: textAvailableDescr + y: -7 + color: "#cfcfcf" + text: qsTr("Available:") + anchors.bottom: textAvailableUnit.bottom + anchors.bottomMargin: 0 + anchors.left: textLockedDescr.left + anchors.leftMargin: 0 + font.family: "Arial" + font.pixelSize: 15 + verticalAlignment: Text.AlignBottom + font.bold: false + horizontalAlignment: Text.AlignLeft + } + } + + Text { + id: textBalance + x: 454 + y: 15 + color: "#ffffff" + text: qsTr("BALANCE") + verticalAlignment: Text.AlignBottom + anchors.horizontalCenterOffset: 0 + anchors.horizontalCenter: parent.horizontalCenter + anchors.top: parent.top + anchors.topMargin: 15 + horizontalAlignment: Text.AlignHCenter + font.bold: true + font.family: "Arial" + font.pixelSize: 25 + } + + Text { + id: textBalanceValue + x: 455 + y: 11 + color: "#ffffff" + text: qsTr("0") + verticalAlignment: Text.AlignBottom + anchors.bottom: parent.bottom + anchors.bottomMargin: 10 + anchors.horizontalCenter: parent.horizontalCenter + font.family: "Arial" + font.pixelSize: 30 + font.bold: true + anchors.horizontalCenterOffset: 0 + horizontalAlignment: Text.AlignRight + + Connections + { + target: QmlBridge + onDisplayTotalBalance: + { + textBalanceValue.text = data + } + } + } + + Text { + id: textBalanceUnit + y: 1 + color: "#ffffff" + text: qsTr("TRTL") + verticalAlignment: Text.AlignBottom + anchors.left: textBalanceValue.right + anchors.leftMargin: 15 + anchors.bottom: textBalanceValue.bottom + anchors.bottomMargin: 2 + font.family: "Arial" + font.pixelSize: 18 + font.bold: true + horizontalAlignment: Text.AlignLeft + } + } + + Rectangle { + id: rectangleHistory + color: "#00000000" + anchors.bottom: rectangleConnectionInfo.top + anchors.bottomMargin: 10 + anchors.right: rectangleSeparator1.left + anchors.rightMargin: 10 + anchors.left: parent.left + anchors.leftMargin: 10 + anchors.top: rowAddress.bottom + anchors.topMargin: 10 + + Text { + id: textHistoryTitle + x: 116 + color: "#ffffff" + text: qsTr("PREVIOUS TRANSACTIONS") + anchors.top: parent.top + anchors.topMargin: 10 + anchors.horizontalCenter: parent.horizontalCenter + font.pixelSize: 25 + horizontalAlignment: Text.AlignHCenter + font.family: "Arial" + verticalAlignment: Text.AlignBottom + font.bold: true + } + + Component { + id: delegateListViewTransactions + ItemListTransaction { + id: itemListTransaction + anchors.left: parent.left + anchors.leftMargin: 0 + anchors.right: parent.right + anchors.rightMargin: 0 + height: 80 + y: 0 + } + } + + ListModel { + id: modelListViewTransactions + } + + ListView { + id: listViewTransactions + model: modelListViewTransactions + delegate: delegateListViewTransactions + clip: true + boundsBehavior: Flickable.DragAndOvershootBounds + anchors.bottom: parent.bottom + anchors.bottomMargin: 10 + anchors.right: parent.right + anchors.rightMargin: 10 + anchors.left: parent.left + anchors.leftMargin: 10 + anchors.top: textHistoryTitle.bottom + anchors.topMargin: 30 + + Connections { + target: QmlBridge + onAddTransactionToList: + { + modelListViewTransactions.append({ + transactionAmountValue: amount, + transactionPaymentIDValue: paymentID, + transactionIDValue: transactionID, + transactionConfirmationsValue: confirmations, + transactionTimeValue: time, + transactionNumberValue: number + }) + } + } + } + + Connections { + target: QmlBridge + onClearListTransactions: + { + modelListViewTransactions.clear(); + } + } + } + + Rectangle { + id: rectangleTransfer + color: "#00000000" + anchors.bottom: rectangleConnectionInfo.top + anchors.bottomMargin: 10 + anchors.left: rectangleSeparator1.right + anchors.leftMargin: 10 + anchors.right: parent.right + anchors.rightMargin: 10 + anchors.top: rectangleHistory.top + anchors.topMargin: 0 + + Text { + id: textTransferTitle + x: 116 + color: "#ffffff" + text: qsTr("TRANSFER") + font.pixelSize: 25 + horizontalAlignment: Text.AlignHCenter + font.bold: true + anchors.top: parent.top + font.family: "Arial" + anchors.horizontalCenter: parent.horizontalCenter + verticalAlignment: Text.AlignBottom + anchors.topMargin: 10 + } + + Text { + id: textTransferAddrDescr + color: "#ffffff" + text: qsTr("Recipient address") + anchors.top: textTransferTitle.bottom + anchors.topMargin: 34 + anchors.left: parent.left + anchors.bottomMargin: 0 + font.pixelSize: 14 + verticalAlignment: Text.AlignBottom + anchors.leftMargin: 30 + font.family: "Arial" + font.bold: true + horizontalAlignment: Text.AlignLeft + anchors.bottom: textAvailableUnit.bottom + } + + Text { + id: textTransferAmountDescr + color: "#ffffff" + text: qsTr("Amount") + anchors.top: rectangleTextInputTransferAddress.bottom + anchors.topMargin: 13 + anchors.left: textTransferAddrDescr.left + anchors.bottomMargin: 0 + verticalAlignment: Text.AlignBottom + font.pixelSize: 14 + horizontalAlignment: Text.AlignLeft + font.bold: true + font.family: "Arial" + anchors.leftMargin: 0 + anchors.bottom: textAvailableUnit.bottom + } + + Text { + id: textTransferPaymentIDDescr + color: "#ffffff" + text: qsTr("(optional) Payment ID") + anchors.top: rectangleTextInputTransferAmount.bottom + anchors.topMargin: 13 + anchors.left: textTransferAddrDescr.left + anchors.bottomMargin: 0 + font.pixelSize: 14 + verticalAlignment: Text.AlignBottom + anchors.leftMargin: 0 + font.family: "Arial" + font.bold: true + horizontalAlignment: Text.AlignLeft + anchors.bottom: textAvailableUnit.bottom + } + + Text { + id: textTransferFeeDescr + color: "#999999" + text: qsTr("The fee is currently fixed and set to 2 TRTL.") + anchors.top: textTransferPaymentIDDescr.bottom + anchors.topMargin: 45 + anchors.left: textTransferAddrDescr.left + anchors.bottomMargin: 0 + verticalAlignment: Text.AlignBottom + font.pixelSize: 14 + horizontalAlignment: Text.AlignLeft + font.bold: false + font.family: "Arial" + anchors.leftMargin: 0 + anchors.bottom: textAvailableUnit.bottom + } + + Text { + id: textTransferMixinDescr + color: "#999999" + text: qsTr("The mixin count is currently fixed and set to 4.") + anchors.top: textTransferFeeDescr.bottom + anchors.topMargin: 5 + anchors.left: textTransferAddrDescr.left + anchors.bottomMargin: 0 + font.pixelSize: 14 + verticalAlignment: Text.AlignBottom + anchors.leftMargin: 0 + font.family: "Arial" + font.bold: false + horizontalAlignment: Text.AlignLeft + anchors.bottom: textAvailableUnit.bottom + } + + Button { + id: buttonSend + text: qsTr("SEND") + anchors.horizontalCenter: parent.horizontalCenter + anchors.bottom: parent.bottom + anchors.bottomMargin: 30 + enabled: false + + contentItem: Text { + text: buttonSend.text + font.bold: true + font.pointSize: 20 + font.family: "Arial" + opacity: enabled ? 1.0 : 0.3 + color: buttonSend.down ? "#dddddd" : "#ffffff" + horizontalAlignment: Text.AlignHCenter + verticalAlignment: Text.AlignVCenter + elide: Text.ElideRight + } + + background: Rectangle { + implicitWidth: 140 + implicitHeight: 60 + opacity: enabled ? 1 : 0.3 + radius: 6 + color: buttonSend.down ? "#383838" : "#444444" + } + + onClicked: { + QmlBridge.clickedButtonSend(textInputTransferAddress.text, textInputTransferAmount.text, textInputTransferPaymentID.text); + } + } + + Rectangle { + id: rectangleTextInputTransferAddress + color: "#555555" + height: 25 + anchors.right: parent.right + anchors.rightMargin: 5 + anchors.top: textTransferAddrDescr.bottom + anchors.topMargin: 6 + anchors.left: textTransferAddrDescr.left + anchors.leftMargin: 0 + radius: 3 + + TextInput { + id: textInputTransferAddress + anchors.fill: parent + color: "#cfcfcf" + text: qsTr("") + rightPadding: 5 + leftPadding: 5 + padding: 2 + selectionColor: "#eeeeee" + selectedTextColor: "#999999" + selectByMouse: true + clip: true + font.family: "Arial" + horizontalAlignment: Text.AlignLeft + font.pixelSize: 14 + verticalAlignment: Text.AlignVCenter + + onTextChanged: { + buttonSend.enabled = textInputTransferAmount.text != "" && textInputTransferAddress.text != "" + } + } + } + + Rectangle { + id: rectangleTextInputTransferAmount + color: "#555555" + anchors.left: textTransferAmountDescr.left + anchors.leftMargin: 0 + anchors.top: textTransferAmountDescr.bottom + anchors.topMargin: 7 + height: 25 + width: 90 + radius: 3 + + TextInput { + id: textInputTransferAmount + anchors.fill: parent + color: "#cfcfcf" + text: qsTr("") + rightPadding: 5 + leftPadding: 5 + padding: 2 + selectionColor: "#eeeeee" + selectedTextColor: "#999999" + selectByMouse: true + clip: true + font.family: "Arial" + horizontalAlignment: Text.AlignRight + font.pixelSize: 16 + verticalAlignment: Text.AlignVCenter + + onTextChanged: { + buttonSend.enabled = textInputTransferAmount.text != "" && textInputTransferAddress.text != "" + } + + Connections{ + target: QmlBridge + onClearTransferAmount: + { + textInputTransferAmount.clear() + } + } + } + } + + Text { + id: textTransferAmountUnit + color: "#999999" + text: qsTr("TRTL") + anchors.verticalCenter: rectangleTextInputTransferAmount.verticalCenter + horizontalAlignment: Text.AlignLeft + font.pixelSize: 14 + anchors.left: rectangleTextInputTransferAmount.right + font.family: "Arial" + verticalAlignment: Text.AlignBottom + anchors.leftMargin: 10 + font.bold: true + } + + Rectangle { + id: rectangleTextInputTransferPaymentID + color: "#555555" + anchors.right: parent.right + anchors.rightMargin: 5 + anchors.top: textTransferPaymentIDDescr.bottom + anchors.topMargin: 6 + anchors.left: textTransferPaymentIDDescr.left + anchors.leftMargin: 0 + height: 25 + radius: 3 + + TextInput { + id: textInputTransferPaymentID + anchors.fill: parent + color: "#cfcfcf" + text: qsTr("") + rightPadding: 5 + leftPadding: 5 + padding: 2 + selectionColor: "#eeeeee" + selectedTextColor: "#999999" + selectByMouse: true + clip: true + font.family: "Arial" + horizontalAlignment: Text.AlignLeft + font.pixelSize: 16 + verticalAlignment: Text.AlignVCenter + } + } + + } + + Rectangle { + id: rectangleConnectionInfo + color: "#00000000" + anchors.bottom: parent.bottom + anchors.bottomMargin: 5 + anchors.left: rectangleSeparator1.right + anchors.leftMargin: 10 + anchors.right: parent.right + anchors.rightMargin: 10 + height: 20 + + Text { + id: textConnectionInfoPeersDescr + color: "#cccccc" + text: qsTr("connected peers") + font.pixelSize: 13 + horizontalAlignment: Text.AlignRight + anchors.verticalCenter: parent.verticalCenter + font.family: "Arial" + anchors.right: parent.right + anchors.rightMargin: 0 + } + + Text { + id: textConnectionInfoPeers + color: "#ffffff" + text: qsTr("0") + font.bold: true + font.pixelSize: 13 + horizontalAlignment: Text.AlignRight + anchors.verticalCenter: parent.verticalCenter + font.family: "Arial" + anchors.right: textConnectionInfoPeersDescr.left + anchors.rightMargin: 5 + } + + Text { + id: textConnectionInfoBlocksDescr + color: "#cccccc" + text: qsTr("synced blocks") + font.pixelSize: 13 + horizontalAlignment: Text.AlignRight + anchors.verticalCenter: parent.verticalCenter + font.family: "Arial" + anchors.right: textConnectionInfoPeers.left + anchors.rightMargin: 15 + } + + Text { + id: textConnectionInfoBlocks + color: "#ffffff" + text: qsTr("0/0") + font.bold: true + font.pixelSize: 13 + horizontalAlignment: Text.AlignRight + anchors.verticalCenter: parent.verticalCenter + font.family: "Arial" + anchors.right: textConnectionInfoBlocksDescr.left + anchors.rightMargin: 5 + } + + Text { + id: textConnectionInfoSync + color: "#ffffff" + text: qsTr("Blockchain syncing...") + font.bold: true + font.pixelSize: 13 + horizontalAlignment: Text.AlignRight + anchors.verticalCenter: parent.verticalCenter + font.family: "Arial" + anchors.right: textConnectionInfoBlocks.left + anchors.rightMargin: 20 + } + } + + Rectangle { + id: rectangleSeparator1 + width: 2 + color: "#858585" + anchors.bottom: rectangleHistory.bottom + anchors.bottomMargin: 40 + anchors.top: rectangleHistory.top + anchors.topMargin: 40 + anchors.left: parent.left + anchors.leftMargin: 610 + } + + Rectangle { + id: popupText + + color: "#4d4d4d" + border.color: "#ffffff"; border.width: 1 + radius: 4 + + y: parent.height // starts off "screen" + anchors.horizontalCenter: parent.horizontalCenter + width: labelPopupText.width + 20 + height: labelPopupText.height + 40 + + opacity: 0 + + function show(msg) { + labelPopupText.text = msg + popupText.state = "visible" + timerPopupText.start() + } + states: State { + name: "visible" + PropertyChanges { target: popupText; opacity: 1 } + PropertyChanges { target: popupText; y: (parent.height-popupText.height)/2 } + } + + transitions: [ + Transition { from: ""; PropertyAnimation { properties: "opacity,y"; duration: 65 } }, + Transition { from: "visible"; PropertyAnimation { properties: "opacity,y"; duration: 500 } } + ] + + Timer { + id: timerPopupText + interval: 1000 + + onTriggered: popupText.state = "" + } + + Text { + id: labelPopupText + anchors.centerIn: parent + + color: "white" + font.pixelSize: 15 + wrapMode: Text.WordWrap + horizontalAlignment: Text.AlignHCenter + smooth: true + } + + Connections{ + target: QmlBridge + onDisplayPopup: + { + timerPopupText.interval = time + popupText.show(text) + } + } + + } + + Dialog { + id: dialogWarningCloseWallet + title: "Warning" + standardButtons: StandardButton.Cancel | StandardButton.Ok + modality: Qt.WindowModal + + Text { + id: textDialogWarningCloseWallet + text: "This action will cose the current wallet" + font.family: "Arial" + } + + function show() { + + dialogWarningCloseWallet.open() + + } + + onAccepted: { + QmlBridge.clickedOpenAnotherWallet() + } + + } + + Dialog { + id: dialogPrivateKeys + title: "Private Keys" + standardButtons: StandardButton.Ok + + Text { + id: textDescriptionPrivateKeys + text: "See below your public address and your 2 private (secret) keys. The 2 private keys can be used to re-generate your wallet.\nCopy them both and keep them in a safe place.\nIf you lose them and lose your password or wallet file, you will not be able to recover your TRTLs.\nIf anybody has access to those keys, he can steal your TRTLs." + font.family: "Arial" + } + + Text { + id: textDescriptionWalletFilename + text: "Wallet file:" + anchors.top: textDescriptionPrivateKeys.bottom + anchors.topMargin: 25 + anchors.left: textDescriptionPrivateKeys.left + anchors.leftMargin: 0 + font.family: "Arial" + } + + Text { + id: textWalletFilename + text: "" + anchors.bottom: textDescriptionWalletFilename.bottom + anchors.bottomMargin: 0 + anchors.left: textDescriptionWalletFilename.right + anchors.leftMargin: 20 + font.family: "Arial" + + } + + Text { + id: textDescriptionAddress + text: "Address" + anchors.top: textDescriptionWalletFilename.bottom + anchors.topMargin: 25 + anchors.left: textDescriptionWalletFilename.left + anchors.leftMargin: 0 + font.family: "Arial" + } + + TextInput { + id: textInputAddress + anchors.top: textDescriptionAddress.bottom + anchors.topMargin: 10 + anchors.left: textDescriptionAddress.left + anchors.leftMargin: 0 + readOnly: true + text: "" + leftPadding: 5 + padding: 2 + selectionColor: "#333333" + selectedTextColor: "white" + selectByMouse: true + font.family: "Arial" + font.bold: true + horizontalAlignment: Text.AlignLeft + verticalAlignment: Text.AlignVCenter + } + + Text { + id: textDescriptionPrivateViewKey + text: "Private View Key" + anchors.top: textInputAddress.bottom + anchors.topMargin: 25 + anchors.left: textInputAddress.left + anchors.leftMargin: 0 + font.family: "Arial" + } + + TextInput { + id: textInputPrivateViewKey + anchors.top: textDescriptionPrivateViewKey.bottom + anchors.topMargin: 10 + anchors.left: textDescriptionPrivateViewKey.left + anchors.leftMargin: 0 + readOnly: true + text: "" + leftPadding: 5 + padding: 2 + selectionColor: "#333333" + selectedTextColor: "white" + selectByMouse: true + font.family: "Arial" + font.bold: true + horizontalAlignment: Text.AlignLeft + verticalAlignment: Text.AlignVCenter + } + + Text { + id: textDescriptionPrivateSpendKey + text: "Private Spend Key" + anchors.top: textInputPrivateViewKey.bottom + anchors.topMargin: 25 + anchors.left: textInputPrivateViewKey.left + anchors.leftMargin: 0 + font.family: "Arial" + } + + TextInput { + id: textInputPrivateSpendKey + anchors.top: textDescriptionPrivateSpendKey.bottom + anchors.topMargin: 10 + anchors.left: textDescriptionPrivateSpendKey.left + anchors.leftMargin: 0 + readOnly: true + text: "" + leftPadding: 5 + padding: 2 + selectionColor: "#333333" + selectedTextColor: "white" + selectByMouse: true + font.family: "Arial" + font.bold: true + horizontalAlignment: Text.AlignLeft + verticalAlignment: Text.AlignVCenter + } + + function show(filename, privateViewKey, privateSpendKey, walletAddress) { + + textWalletFilename.text = filename + textInputPrivateViewKey.text = privateViewKey + textInputPrivateSpendKey.text = privateSpendKey + textInputAddress.text = walletAddress + dialogPrivateKeys.open() + + } + + } + + Connections { + target: QmlBridge + onDisplayPrivateKeys: + { + dialogPrivateKeys.show(filename, privateViewKey, privateSpendKey, walletAddress); + } + } + } + + Dialog { + id: dialogInfo + title: "Info" + standardButtons: StandardButton.Ok + width: 600 + height: 100 + modality: Qt.WindowModal + + Text { + id: textDialogInfo + text: "" + font.family: "Arial" + } + + function show(title, msg) { + + dialogInfo.title = title + textDialogInfo.text = msg + dialogInfo.open() + + } + + function showError(msg) { + + dialogInfo.show("Error", msg) + + } + + Connections{ + target: QmlBridge + onDisplayErrorDialog: + { + dialogInfo.showError(errorMessage) + } + } + + } + + Connections { + target: QmlBridge + + onDisplayOpenWalletScreen: + { + menuWallet.enabled = false; + openWalletScreen.visible = true; + rectangleMainWallet.visible = false; + openWalletScreen.clearData(); + } + + onDisplayMainWalletScreen: + { + menuWallet.enabled = true; + openWalletScreen.visible = false; + rectangleMainWallet.visible = true; + textInputTransferAddress.text = ""; + textInputTransferAmount.text = ""; + textInputTransferPaymentID.text = ""; + } + + onDisplaySyncingInfo: + { + textConnectionInfoSync.text = syncing + textConnectionInfoBlocks.text = blocks + textConnectionInfoPeers.text = peers + } + } + +} diff --git a/turtlecoinnestlogo.png b/turtlecoinnestlogo.png new file mode 100644 index 0000000..d940bbd Binary files /dev/null and b/turtlecoinnestlogo.png differ diff --git a/walletdmanager/walletdmanager.go b/walletdmanager/walletdmanager.go new file mode 100644 index 0000000..3f1236f --- /dev/null +++ b/walletdmanager/walletdmanager.go @@ -0,0 +1,894 @@ +// Package walletdmanager handles the management of the wallet and the communication with the core wallet software +package walletdmanager + +import ( + "bufio" + "bytes" + "encoding/json" + "errors" + "io" + "io/ioutil" + "math/rand" + "net/http" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "syscall" + "time" + + log "github.com/sirupsen/logrus" +) + +type rpcPayload struct { + JSONRPC string `json:"jsonrpc"` + Method string `json:"method"` + Params *map[string]interface{} `json:"params,omitempty"` + Password string `json:"password"` + ID int `json:"id"` +} + +// Transfer contains all the information about a specific transfer +type Transfer struct { + PaymentID string + TxID string + Timestamp time.Time + Amount float64 + Fee float64 + Block int + Confirmations int + IsRecievingTransaction bool +} + +var ( + rpcURL = "http://127.0.0.1:8070/json_rpc" + + walletdCurrentSessionLogFileFilename = "walletdCurrentSession.log" + walletdLogFileFilename = "walletd.log" + + walletTotalBalance float64 + // WalletAvailableBalance is the available balance + WalletAvailableBalance float64 + walletLockedBalance float64 + + // WalletAddress is the wallet address + WalletAddress string + + // WalletFilename is the filename of the opened wallet + WalletFilename = "" + + // will be set to a random string when starting walletd + rpcPassword = "" + + // Transfers is a slice with all the history of transactions of the opened wallet + Transfers []Transfer + + cmdWalletd *exec.Cmd + + // WalletdOpenAndRunning is true when walletd is running with a wallet open + WalletdOpenAndRunning = false + + // WalletdSynced is true when wallet is synced and transfer is allowed + WalletdSynced = false +) + +// RequestBalance provides the available and locked balances of the current wallet +func RequestBalance() (availableBalance float64, lockedBalance float64, totalBalance float64) { + + args := make(map[string]interface{}) + + payload := rpcPayload{ + JSONRPC: "2.0", + Method: "getBalance", + Params: &args, + Password: rpcPassword, + ID: 1} + + payloadjson, err := json.Marshal(payload) + if err != nil { + log.Fatal("error json marshal: ", err) + } + + req, err := http.NewRequest("POST", rpcURL, bytes.NewBuffer(payloadjson)) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + log.Fatal("error http request: ", err) + } + defer resp.Body.Close() + + log.Info("response Status getBalance:", resp.Status) + responseBody, err := ioutil.ReadAll(resp.Body) + + if err != nil { + + log.Fatal("error reading result from rpc request getBalance:", err) + + } else { + + var responseBodyInterface interface{} + if err := json.Unmarshal(responseBody, &responseBodyInterface); err != nil { + + log.Fatal("JSON unmarshaling with interface failed:", err) + + } else { + + responseMap := responseBodyInterface.(map[string]interface{}) + + WalletAvailableBalance = responseMap["result"].(map[string]interface{})["availableBalance"].(float64) / 100 + walletLockedBalance = responseMap["result"].(map[string]interface{})["lockedAmount"].(float64) / 100 + walletTotalBalance = WalletAvailableBalance + walletLockedBalance + + return WalletAvailableBalance, walletLockedBalance, walletTotalBalance + + } + + } + + return 0, 0, 0 + +} + +// RequestAddress provides the address of the current wallet +func RequestAddress() string { + + args := make(map[string]interface{}) + + payload := rpcPayload{ + JSONRPC: "2.0", + Method: "getAddresses", + Params: &args, + Password: rpcPassword, + ID: 2} + + payloadjson, err := json.Marshal(payload) + if err != nil { + log.Fatal("error json marshal: ", err) + } + + req, err := http.NewRequest("POST", rpcURL, bytes.NewBuffer(payloadjson)) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + log.Fatal("error http request: ", err) + } + defer resp.Body.Close() + + log.Info("response Status getAddresses:", resp.Status) + responseBody, err := ioutil.ReadAll(resp.Body) + + if err != nil { + + log.Fatal("error reading result from rpc request getAddresses:", err) + + } else { + + var responseBodyInterface interface{} + if err := json.Unmarshal(responseBody, &responseBodyInterface); err != nil { + + log.Fatal("JSON unmarshaling with interface failed:", err) + + } else { + + responseMap := responseBodyInterface.(map[string]interface{}) + + walletAddresses := responseMap["result"].(map[string]interface{})["addresses"].([]interface{}) + + WalletAddress = walletAddresses[0].(string) + + return WalletAddress + + } + + } + + return "error displaying the address" + +} + +// RequestListTransactions provides the list of transactions of current wallet +func RequestListTransactions() (transfers []Transfer) { + + args := make(map[string]interface{}) + + walletBlockCount, _, _, err := requestStatus() + if err != nil { + log.Fatal("error getting block count: ", err) + } + + args["blockCount"] = walletBlockCount + args["firstBlockIndex"] = 1 + args["addresses"] = []string{WalletAddress} + + // Request all transactions related to our addresses from the wallet + // This returns a list of blocks with only our transactions populated in them + + payload := rpcPayload{ + JSONRPC: "2.0", + Method: "getTransactions", + Params: &args, + Password: rpcPassword, + ID: 3} + + payloadjson, err := json.Marshal(payload) + if err != nil { + log.Fatal("error json marshal: ", err) + } + + req, err := http.NewRequest("POST", rpcURL, bytes.NewBuffer(payloadjson)) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + log.Fatal("error http request: ", err) + } + defer resp.Body.Close() + + log.Info("response Status getTransactions:", resp.Status) + responseBody, err := ioutil.ReadAll(resp.Body) + + if err != nil { + + log.Fatal("error reading result from rpc request getAddresses:", err) + + } else { + + var responseBodyInterface interface{} + if err := json.Unmarshal(responseBody, &responseBodyInterface); err != nil { + + log.Fatal("JSON unmarshaling with interface failed:", err) + + } else { + + responseMap := responseBodyInterface.(map[string]interface{}) + + blocks := responseMap["result"].(map[string]interface{})["items"].([]interface{}) + + for _, block := range blocks { + + transactions := block.(map[string]interface{})["transactions"].([]interface{}) + + for _, transaction := range transactions { + + mapTransaction := transaction.(map[string]interface{}) + + var transfer Transfer + transfer.PaymentID = mapTransaction["paymentId"].(string) + transfer.TxID = mapTransaction["transactionHash"].(string) + transfer.Timestamp = time.Unix(int64(mapTransaction["timestamp"].(float64)), 0) + transfer.Amount = mapTransaction["amount"].(float64) / 100 + transfer.Fee = mapTransaction["fee"].(float64) / 100 + transfer.Block = int(mapTransaction["blockIndex"].(float64)) + transfer.Confirmations = walletBlockCount - transfer.Block + 1 + transfer.IsRecievingTransaction = transfer.Amount >= 0 + + transfers = append(transfers, transfer) + + } + + } + + return transfers + + } + + } + + return nil + +} + +func requestStatus() (blockCount int, knownBlockCount int, peerCount int, err error) { + + args := make(map[string]interface{}) + + payload := rpcPayload{ + JSONRPC: "2.0", + Method: "getStatus", + Params: &args, + Password: rpcPassword, + ID: 4} + + payloadjson, err := json.Marshal(payload) + if err != nil { + log.Error("error json marshal: ", err) + return 0, 0, 0, errors.New("error json marshal: " + err.Error()) + } + + req, err := http.NewRequest("POST", rpcURL, bytes.NewBuffer(payloadjson)) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + log.Error("error http request: ", err) + return 0, 0, 0, errors.New("error http request: " + err.Error()) + } + defer resp.Body.Close() + + log.Info("response Status getStatus:", resp.Status) + responseBody, err := ioutil.ReadAll(resp.Body) + + if err != nil { + + log.Error("error reading result from rpc request getAddresses:", err) + return 0, 0, 0, errors.New("error reading result from rpc request getAddresses:" + err.Error()) + + } + + var responseBodyInterface interface{} + if err := json.Unmarshal(responseBody, &responseBodyInterface); err != nil { + + log.Error("JSON unmarshaling with interface failed:", err) + return 0, 0, 0, errors.New("JSON unmarshaling with interface failed:" + err.Error()) + + } + + responseMap := responseBodyInterface.(map[string]interface{}) + + blockCount = int(responseMap["result"].(map[string]interface{})["blockCount"].(float64)) + knownBlockCount = int(responseMap["result"].(map[string]interface{})["knownBlockCount"].(float64)) + peerCount = int(responseMap["result"].(map[string]interface{})["peerCount"].(float64)) + + return blockCount, knownBlockCount, peerCount, nil + +} + +// SendTransaction makes a transfer with the provided information +func SendTransaction(transferAddress string, transferAmountString string, transferPaymentID string) (transactionHash string, err error) { + + if !strings.HasPrefix(transferAddress, "TRTL") || len(transferAddress) != 99 { + + return "", errors.New("address is invalid") + + } + + if transferAddress == WalletAddress { + + return "", errors.New("sending to yourself is not supported") + + } + + var transferFee float64 = 2 // transferFee is expressed in TRTL + transferMixin := 4 + + transferAmount, err := strconv.ParseFloat(transferAmountString, 64) // transferAmount is expressed in TRTL + + if err != nil { + + return "", errors.New("amount is invalid") + + } + + if transferAmount <= 0 { + + return "", errors.New("amount of TRTL to be sent should be greater than 0") + + } + + if transferAmount+transferFee > WalletAvailableBalance { + + return "", errors.New("your available balance is insufficient") + + } + + if transferAmount > 5000000 { + + return "", errors.New("for sending more than 5,000,000 TRTL to one address, you should split in multiple transfers of smaller amounts") + + } + + transferAmountInt := int(transferAmount * 100) // transferAmountInt is expressed in hundredth of TRTL + transferFeeInt := int(transferFee * 100) // transferFeeInt is expressed in hundredth of TRTL + + args := make(map[string]interface{}) + + args["fee"] = transferFeeInt + args["paymentId"] = transferPaymentID + args["anonymity"] = transferMixin + + var transfers [1]map[string]interface{} + transfer := make(map[string]interface{}) + transfer["amount"] = transferAmountInt + transfer["address"] = transferAddress + transfers[0] = transfer + args["transfers"] = transfers + + payload := rpcPayload{ + JSONRPC: "2.0", + Method: "sendTransaction", + Params: &args, + Password: rpcPassword, + ID: 5} + + payloadjson, err := json.Marshal(payload) + if err != nil { + log.Fatal("error json marshal: ", err) + } + + req, err := http.NewRequest("POST", rpcURL, bytes.NewBuffer(payloadjson)) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + log.Fatal("error http request: ", err) + } + defer resp.Body.Close() + + log.Info("response Status sendTransaction:", resp.Status) + responseBody, err := ioutil.ReadAll(resp.Body) + + if err != nil { + + log.Fatal("error reading result from rpc request sendTransaction:", err) + + } else { + + var responseBodyInterface interface{} + if err := json.Unmarshal(responseBody, &responseBodyInterface); err != nil { + + log.Fatal("JSON unmarshaling with interface failed:", err) + + } else { + + responseMap := responseBodyInterface.(map[string]interface{}) + + responseError := responseMap["error"] + + if responseError != nil { + + return "", errors.New(responseError.(map[string]interface{})["message"].(string)) + + } + + return responseMap["result"].(map[string]interface{})["transactionHash"].(string), nil + + } + + } + + return "", errors.New("unknown error") + +} + +// getPrivateViewKey provides the private view key of the current wallet +func getPrivateViewKey() (privateViewKey string, err error) { + + args := make(map[string]interface{}) + + payload := rpcPayload{ + JSONRPC: "2.0", + Method: "getViewKey", + Params: &args, + Password: rpcPassword, + ID: 6} + + payloadjson, err := json.Marshal(payload) + if err != nil { + log.Fatal("error json marshal: ", err) + } + + req, err := http.NewRequest("POST", rpcURL, bytes.NewBuffer(payloadjson)) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + log.Fatal("error http request: ", err) + } + defer resp.Body.Close() + + log.Info("response Status getViewKey:", resp.Status) + responseBody, err := ioutil.ReadAll(resp.Body) + + if err != nil { + + log.Fatal("error reading result from rpc request getViewKey:", err) + + } else { + + var responseBodyInterface interface{} + if err := json.Unmarshal(responseBody, &responseBodyInterface); err != nil { + + log.Fatal("JSON unmarshaling with interface failed:", err) + + } else { + + responseMap := responseBodyInterface.(map[string]interface{}) + + privateViewKey = responseMap["result"].(map[string]interface{})["viewSecretKey"].(string) + + return privateViewKey, nil + + } + + } + + return "", errors.New("unknown error") + +} + +// getPrivateSpendKey provides the private view of the current wallet +func getPrivateSpendKey() (privateSpendKey string, err error) { + + args := make(map[string]interface{}) + + args["address"] = WalletAddress + + payload := rpcPayload{ + JSONRPC: "2.0", + Method: "getSpendKeys", + Params: &args, + Password: rpcPassword, + ID: 7} + + payloadjson, err := json.Marshal(payload) + if err != nil { + log.Fatal("error json marshal: ", err) + } + + req, err := http.NewRequest("POST", rpcURL, bytes.NewBuffer(payloadjson)) + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + log.Fatal("error http request: ", err) + } + defer resp.Body.Close() + + log.Info("response Status getSpendKey:", resp.Status) + responseBody, err := ioutil.ReadAll(resp.Body) + + if err != nil { + + log.Fatal("error reading result from rpc request getSpendKey:", err) + + } else { + + var responseBodyInterface interface{} + if err := json.Unmarshal(responseBody, &responseBodyInterface); err != nil { + + log.Fatal("JSON unmarshaling with interface failed:", err) + + } else { + + responseMap := responseBodyInterface.(map[string]interface{}) + + privateSpendKey = responseMap["result"].(map[string]interface{})["spendSecretKey"].(string) + + return privateSpendKey, nil + + } + + } + + return "", errors.New("unknown error") + +} + +// GetPrivateViewKeyAndSpendKey provides the private view and spend keys of the current wallet +func GetPrivateViewKeyAndSpendKey() (privateViewKey string, privateSpendKey string, err error) { + + privateViewKey, err = getPrivateViewKey() + + if err != nil { + + return "", "", err + + } + + privateSpendKey, err = getPrivateSpendKey() + + if err != nil { + + return "", "", err + + } + + return privateViewKey, privateSpendKey, nil + +} + +// StartWalletd starts the walletd daemon with the set wallet info +// walletPath is the full path to the wallet +// walletPassword is the wallet password +func StartWalletd(walletPath string, walletPassword string) (err error) { + + fileExtension := filepath.Ext(walletPath) + + if fileExtension != ".wallet" { + + return errors.New("filename should end with .wallet") + + } + + WalletFilename = filepath.Base(walletPath) + + walletFilePath := filepath.Clean(walletPath) + + walletFilePath = strings.Replace(walletFilePath, "file:", "", 1) + + // setup current session log file (logs are added real time in this file) + walletdCurrentSessionLogFile, err := os.Create(walletdCurrentSessionLogFileFilename) + if err != nil { + log.Error(err) + } + defer walletdCurrentSessionLogFile.Close() + + rpcPassword = randStringBytesMaskImprSrc(20) + + cmdWalletd = exec.Command("./walletd", "-w", walletFilePath, "-p", walletPassword, "-l", walletdCurrentSessionLogFileFilename, "--local", "--rpc-password", rpcPassword) + + // setup all sessions log file (logs are added at the end of this file only after walletd has stopped) + // walletdLogFile, err := os.Open(walletdLogFileFilename) + walletdLogFile, err := os.OpenFile(walletdLogFileFilename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) + if err != nil { + log.Fatal(err) + } + cmdWalletd.Stdout = walletdLogFile + defer walletdLogFile.Close() + + err = cmdWalletd.Start() + + if err != nil { + log.Error(err) + return err + } + + time.Sleep(5 * time.Second) + + reader := bufio.NewReader(walletdCurrentSessionLogFile) + + var listWalletdErrors []string + + for { + + line, err := reader.ReadString('\n') + + if err != nil { + + if err != io.EOF { + + log.Error("Failed reading log file line by line: ", err) + + } + + break + } + + if strings.Contains(line, " ERROR ") { + + listWalletdErrors = append(listWalletdErrors, line) + + } + + } + + errorMessage := "Error opening the daemon walletd. Could be a problem with your wallet file, your password or walletd. More info in the file " + walletdLogFileFilename + "\n" + + if len(listWalletdErrors) > 0 { + + for _, line := range listWalletdErrors { + + errorMessage = errorMessage + line + + } + + } + + // check rpc connection with walletd + _, _, _, err = requestStatus() + + if err != nil { + + return errors.New(errorMessage) + + } + + WalletdOpenAndRunning = true + + return nil +} + +// StopWalletd stops the walletd daemon +func StopWalletd() { + + if WalletdOpenAndRunning && cmdWalletd != nil { + + if err := cmdWalletd.Process.Signal(syscall.SIGTERM); err != nil { + + log.Error("failed to kill: ", err) + + } else { + + log.Info("walletd killed without error") + + } + + } + + walletTotalBalance = 0 + WalletAvailableBalance = 0 + walletLockedBalance = 0 + WalletAddress = "" + WalletFilename = "" + Transfers = nil + cmdWalletd = nil + WalletdOpenAndRunning = false + +} + +// CreateWallet calls walletd to create a new wallet. If privateViewKey and privateSpendKey are empty strings, a new wallet will be generated. If they are not empty, a wallet will be generated from those keys (import) +// walletFilename is the filename chosen by the user. The created wallet file will be located in the same folder as walletd. +// walletPassword is the password of the new wallet. +// privateViewKey is the private view key of the wallet. +// privateSpendKey is the private spend key of the wallet. +func CreateWallet(walletFilename string, walletPassword string, privateViewKey string, privateSpendKey string) (err error) { + + if WalletdOpenAndRunning { + + return errors.New("walletd is already running. It should be stopped before being able to generate a new wallet") + + } + + if strings.Contains(walletFilename, "/") || strings.Contains(walletFilename, " ") || strings.Contains(walletFilename, ":") { + + return errors.New("you should avoid spaces and most special characters in the filename") + + } + + // setup current session log file (logs are added real time in this file) + walletdCurrentSessionLogFile, err := os.Create(walletdCurrentSessionLogFileFilename) + if err != nil { + log.Error(err) + } + defer walletdCurrentSessionLogFile.Close() + + if privateViewKey == "" && privateSpendKey == "" { + + // generate new wallet + cmdWalletd = exec.Command("./walletd", "-w", walletFilename, "-p", walletPassword, "-l", walletdCurrentSessionLogFileFilename, "-g") + + } else { + + // import wallet from private view and spend keys + cmdWalletd = exec.Command("./walletd", "-w", walletFilename, "-p", walletPassword, "--view-key", privateViewKey, "--spend-key", privateSpendKey, "-l", walletdCurrentSessionLogFileFilename, "-g") + + } + + // setup all sessions log file (logs are added at the end of this file only after walletd has stopped) + // walletdLogFile, err := os.Open(walletdLogFileFilename) + walletdLogFile, err := os.OpenFile(walletdLogFileFilename, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600) + if err != nil { + log.Fatal(err) + } + cmdWalletd.Stdout = walletdLogFile + defer walletdLogFile.Close() + + err = cmdWalletd.Start() + + if err != nil { + log.Error(err) + return err + } + + time.Sleep(5 * time.Second) + + reader := bufio.NewReader(walletdCurrentSessionLogFile) + + var listWalletdErrors []string + + successCreatingWallet := false + + for { + + line, err := reader.ReadString('\n') + + if err != nil { + + if err != io.EOF { + + log.Error("Failed reading log file line by line: ", err) + + } + + break + } + + if strings.Contains(line, " ERROR ") || strings.Contains(line, "error: ") { + + listWalletdErrors = append(listWalletdErrors, line) + + } + + if strings.Contains(line, "New wallet is generated. Address:") || strings.Contains(line, "New wallet added") { + + successCreatingWallet = true + + break + + } + + } + + errorMessage := "Error opening walletd and/or creating a wallet. More info in the file " + walletdLogFileFilename + "\n" + + if !successCreatingWallet { + + if len(listWalletdErrors) > 0 { + + for _, line := range listWalletdErrors { + + errorMessage = errorMessage + line + + } + + } + + return errors.New(errorMessage) + + } + + return nil +} + +// RequestConnectionInfo provides the blockchain sync status and the number of connected peers +func RequestConnectionInfo() (syncing string, blockCountString string, knownBlockCountString string, peerCountString string, err error) { + + blockCount, knownBlockCount, peerCount, err := requestStatus() + + if err != nil { + + return "", "", "", "", err + + } + + stringWait := " (Wait for being allowed to make a transfer)" + + if knownBlockCount == 0 { + + WalletdSynced = false + syncing = "Getting block count..." + stringWait + + } else if blockCount >= knownBlockCount-1 { + + WalletdSynced = true + syncing = "Wallet synced" + + } else { + + WalletdSynced = false + syncing = "Wallet syncing..." + stringWait + + } + + return syncing, strconv.Itoa(blockCount), strconv.Itoa(knownBlockCount), strconv.Itoa(peerCount), nil + +} + +// generate a random string with n characters. from https://stackoverflow.com/a/31832326/1668837 +func randStringBytesMaskImprSrc(n int) string { + + const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" + const letterIdxBits = 6 // 6 bits to represent a letter index + const letterIdxMask = 1<= 0; { + if remain == 0 { + cache, remain = src.Int63(), letterIdxMax + } + if idx := int(cache & letterIdxMask); idx < len(letterBytes) { + b[i] = letterBytes[idx] + i-- + } + cache >>= letterIdxBits + remain-- + } + + return string(b) +}