diff --git a/COPYING b/COPYING index 1ca0b94..db1e8d4 100644 --- a/COPYING +++ b/COPYING @@ -1,4 +1,8 @@ -Copyright (c) 2014-2015 Genius Developers +Copyright (c) 2015 Genius Developers +Copyright (c) 2015 Crave Developers +Copyright (c) 2014-2015 Shadowcash Developers +Copyright (c) 2014-2015 Dash Developers +Copyright (c) 2014-2015 Blackcoin Developers Copyright (c) 2013-2014 NovaCoin Developers Copyright (c) 2011-2012 PPCoin Developers Copyright (c) 2009-2015 Bitcoin Developers diff --git a/README.md b/README.md index e71ed36..813eee4 100644 --- a/README.md +++ b/README.md @@ -29,4 +29,4 @@ in this manner will have their corresponding issue labeled 'stagnant'. Issues with no commits will be given a similar warning, and closed after 15 days from their last activity. Issues closed in this manner will be -labeled 'stale'. +labeled 'stale'. \ No newline at end of file diff --git a/genius.pro b/genius.pro index 85e58c0..a84ea8d 100644 --- a/genius.pro +++ b/genius.pro @@ -1,8 +1,8 @@ TEMPLATE = app TARGET = genius-qt -VERSION = 1.0.0.0 -INCLUDEPATH += src src/json src/qt -QT += network +VERSION = 1.1.0.0 +INCLUDEPATH += src src/json src/qt src/qt/plugins/mrichtexteditor +QT += network printsupport DEFINES += ENABLE_WALLET DEFINES += BOOST_THREAD_USE_LIB BOOST_SPIRIT_THREADSAFE CONFIG += no_include_pwd @@ -13,6 +13,11 @@ greaterThan(QT_MAJOR_VERSION, 4) { DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0 } +linux { + SECP256K1_LIB_PATH = /usr/local/lib + SECP256K1_INCLUDE_PATH = /usr/local/include +} + # for boost 1.37, add -mt to the boost libraries # use: qmake BOOST_LIB_SUFFIX=-mt # for boost thread win32 with _win32 sufix @@ -46,7 +51,7 @@ QMAKE_LFLAGS *= -fstack-protector-all --param ssp-buffer-size=1 # This can be enabled for Windows, when we switch to MinGW >= 4.4.x. } # for extra security on Windows: enable ASLR and DEP via GCC linker flags -win32:QMAKE_LFLAGS *= -Wl,--dynamicbase -Wl,--nxcompat +win32:QMAKE_LFLAGS *= -Wl,--dynamicbase -Wl,--nxcompat -static win32:QMAKE_LFLAGS += -static-libgcc -static-libstdc++ # use: qmake "USE_QRCODE=1" @@ -89,6 +94,9 @@ contains(BITCOIN_NEED_QT_PLUGINS, 1) { QTPLUGIN += qcncodecs qjpcodecs qtwcodecs qkrcodecs qtaccessiblewidgets } +# LIBSEC256K1 SUPPORT +QMAKE_CXXFLAGS *= -DUSE_SECP256K1 + INCLUDEPATH += src/leveldb/include src/leveldb/helpers LIBS += $$PWD/src/leveldb/libleveldb.a $$PWD/src/leveldb/libmemenv.a SOURCES += src/txdb-leveldb.cpp @@ -165,20 +173,20 @@ HEADERS += src/qt/bitcoingui.h \ src/hash.h \ src/uint256.h \ src/kernel.h \ - src/scrypt.h \ src/pbkdf2.h \ src/serialize.h \ src/core.h \ src/main.h \ src/miner.h \ - src/irc.h \ src/net.h \ src/key.h \ + src/eckey.h \ src/db.h \ src/txdb.h \ src/txmempool.h \ src/walletdb.h \ src/script.h \ + src/scrypt.h \ src/init.h \ src/mruset.h \ src/json/json_spirit_writer_template.h \ @@ -227,7 +235,35 @@ HEADERS += src/qt/bitcoingui.h \ src/netbase.h \ src/clientversion.h \ src/threadsafety.h \ - src/tinyformat.h + src/tinyformat.h \ + src/stealth.h \ + src/qt/flowlayout.h \ + src/qt/darksendconfig.h \ + src/masternode.h \ + src/darksend.h \ + src/instantx.h \ + src/activemasternode.h \ + src/spork.h \ + src/crypto/common.h \ + src/crypto/hmac_sha256.h \ + src/crypto/hmac_sha512.h \ + src/crypto/rfc6979_hmac_sha256.h \ + src/crypto/ripemd160.h \ + src/crypto/sha1.h \ + src/crypto/sha256.h \ + src/crypto/sha512.h \ + src/eccryptoverify.h \ + src/qt/masternodemanager.h \ + src/qt/addeditadrenalinenode.h \ + src/qt/adrenalinenodeconfigdialog.h \ + src/qt/qcustomplot.h \ + src/smessage.h \ + src/qt/messagepage.h \ + src/qt/messagemodel.h \ + src/qt/sendmessagesdialog.h \ + src/qt/sendmessagesentry.h \ + src/qt/plugins/mrichtexteditor/mrichtextedit.h \ + src/qt/qvalidatedtextedit.h SOURCES += src/qt/bitcoin.cpp src/qt/bitcoingui.cpp \ src/qt/transactiontablemodel.cpp \ @@ -250,12 +286,16 @@ SOURCES += src/qt/bitcoin.cpp src/qt/bitcoingui.cpp \ src/hash.cpp \ src/netbase.cpp \ src/key.cpp \ + src/eckey.cpp \ src/script.cpp \ + src/scrypt-arm.S \ + src/scrypt-x86.S \ + src/scrypt-x86_64.S \ + src/scrypt.cpp \ src/core.cpp \ src/main.cpp \ src/miner.cpp \ src/init.cpp \ - src/irc.cpp \ src/net.cpp \ src/checkpoints.cpp \ src/addrman.cpp \ @@ -301,11 +341,38 @@ SOURCES += src/qt/bitcoin.cpp src/qt/bitcoingui.cpp \ src/qt/rpcconsole.cpp \ src/noui.cpp \ src/kernel.cpp \ - src/scrypt-arm.S \ - src/scrypt-x86.S \ - src/scrypt-x86_64.S \ - src/scrypt.cpp \ - src/pbkdf2.cpp + src/pbkdf2.cpp \ + src/stealth.cpp \ + src/qt/flowlayout.cpp \ + src/qt/darksendconfig.cpp \ + src/masternode.cpp \ + src/darksend.cpp \ + src/rpcdarksend.cpp \ + src/instantx.cpp \ + src/activemasternode.cpp \ + src/spork.cpp \ + src/masternodeconfig.cpp \ + src/crypto/hmac_sha256.cpp \ + src/crypto/hmac_sha512.cpp \ + src/crypto/rfc6979_hmac_sha256.cpp \ + src/crypto/ripemd160.cpp \ + src/crypto/sha1.cpp \ + src/crypto/sha256.cpp \ + src/crypto/sha512.cpp \ + src/eccryptoverify.cpp \ + src/qt/masternodemanager.cpp \ + src/qt/addeditadrenalinenode.cpp \ + src/qt/adrenalinenodeconfigdialog.cpp \ + src/qt/qcustomplot.cpp \ + src/smessage.cpp \ + src/qt/messagepage.cpp \ + src/qt/messagemodel.cpp \ + src/qt/sendmessagesdialog.cpp \ + src/qt/sendmessagesentry.cpp \ + src/qt/qvalidatedtextedit.cpp \ + src/qt/plugins/mrichtexteditor/mrichtextedit.cpp \ + src/rpcsmessage.cpp + RESOURCES += \ src/qt/bitcoin.qrc @@ -322,7 +389,15 @@ FORMS += \ src/qt/forms/sendcoinsentry.ui \ src/qt/forms/askpassphrasedialog.ui \ src/qt/forms/rpcconsole.ui \ - src/qt/forms/optionsdialog.ui + src/qt/forms/optionsdialog.ui \ + src/qt/forms/darksendconfig.ui \ + src/qt/forms/masternodemanager.ui \ + src/qt/forms/addeditadrenalinenode.ui \ + src/qt/forms/adrenalinenodeconfigdialog.ui \ + src/qt/forms/messagepage.ui \ + src/qt/forms/sendmessagesentry.ui \ + src/qt/forms/sendmessagesdialog.ui \ + src/qt/plugins/mrichtexteditor/mrichtextedit.ui contains(USE_QRCODE, 1) { HEADERS += src/qt/qrcodedialog.h @@ -410,11 +485,12 @@ macx:QMAKE_CXXFLAGS_THREAD += -pthread macx:QMAKE_INFO_PLIST = share/qt/Info.plist # Set libraries and includes at end, to use platform-defined defaults if not overridden -INCLUDEPATH += $$BOOST_INCLUDE_PATH $$BDB_INCLUDE_PATH $$OPENSSL_INCLUDE_PATH $$QRENCODE_INCLUDE_PATH -LIBS += $$join(BOOST_LIB_PATH,,-L,) $$join(BDB_LIB_PATH,,-L,) $$join(OPENSSL_LIB_PATH,,-L,) $$join(QRENCODE_LIB_PATH,,-L,) +INCLUDEPATH += $$SECP256K1_INCLUDE_PATH $$BOOST_INCLUDE_PATH $$BDB_INCLUDE_PATH $$OPENSSL_INCLUDE_PATH $$QRENCODE_INCLUDE_PATH +LIBS += $$join(SECP256K1_LIB_PATH,,-L,) $$join(BOOST_LIB_PATH,,-L,) $$join(BDB_LIB_PATH,,-L,) $$join(OPENSSL_LIB_PATH,,-L,) $$join(QRENCODE_LIB_PATH,,-L,) LIBS += -lssl -lcrypto -ldb_cxx$$BDB_LIB_SUFFIX # -lgdi32 has to happen after -lcrypto (see #681) windows:LIBS += -lws2_32 -lshlwapi -lmswsock -lole32 -loleaut32 -luuid -lgdi32 +LIBS += -lsecp256k1 LIBS += -lboost_system$$BOOST_LIB_SUFFIX -lboost_filesystem$$BOOST_LIB_SUFFIX -lboost_program_options$$BOOST_LIB_SUFFIX -lboost_thread$$BOOST_THREAD_LIB_SUFFIX windows:LIBS += -lboost_chrono$$BOOST_LIB_SUFFIX diff --git a/src/activemasternode.cpp b/src/activemasternode.cpp new file mode 100644 index 0000000..4f2aa71 --- /dev/null +++ b/src/activemasternode.cpp @@ -0,0 +1,473 @@ +// Copyright (c) 2009-2012 The Darkcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "protocol.h" +#include "activemasternode.h" +#include +#include "clientversion.h" + +// +// Bootup the masternode, look for a 5000 GENIUS input and register on the network +// +void CActiveMasternode::ManageStatus() +{ + std::string errorMessage; + + if(!fMasterNode) return; + + if (fDebug) LogPrintf("CActiveMasternode::ManageStatus() - Begin\n"); + + //need correct adjusted time to send ping + bool fIsInitialDownload = IsInitialBlockDownload(); + if(fIsInitialDownload) { + status = MASTERNODE_SYNC_IN_PROCESS; + LogPrintf("CActiveMasternode::ManageStatus() - Sync in progress. Must wait until sync is complete to start masternode.\n"); + return; + } + + if(status == MASTERNODE_INPUT_TOO_NEW || status == MASTERNODE_NOT_CAPABLE || status == MASTERNODE_SYNC_IN_PROCESS){ + status = MASTERNODE_NOT_PROCESSED; + } + + if(status == MASTERNODE_NOT_PROCESSED) { + if(strMasterNodeAddr.empty()) { + if(!GetLocal(service)) { + notCapableReason = "Can't detect external address. Please use the masternodeaddr configuration option."; + status = MASTERNODE_NOT_CAPABLE; + LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason.c_str()); + return; + } + } else { + service = CService(strMasterNodeAddr); + } + + LogPrintf("CActiveMasternode::ManageStatus() - Checking inbound connection to '%s'\n", service.ToString().c_str()); + + + if(!ConnectNode((CAddress)service, service.ToString().c_str())){ + notCapableReason = "Could not connect to " + service.ToString(); + status = MASTERNODE_NOT_CAPABLE; + LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason.c_str()); + return; + } + + + if(pwalletMain->IsLocked()){ + notCapableReason = "Wallet is locked."; + status = MASTERNODE_NOT_CAPABLE; + LogPrintf("CActiveMasternode::ManageStatus() - not capable: %s\n", notCapableReason.c_str()); + return; + } + + // Set defaults + status = MASTERNODE_NOT_CAPABLE; + notCapableReason = "Unknown. Check debug.log for more information.\n"; + + // Choose coins to use + CPubKey pubKeyCollateralAddress; + CKey keyCollateralAddress; + + if(GetMasterNodeVin(vin, pubKeyCollateralAddress, keyCollateralAddress)) { + + if(GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS){ + LogPrintf("CActiveMasternode::ManageStatus() - Input must have least %d confirmations - %d confirmations\n", MASTERNODE_MIN_CONFIRMATIONS, GetInputAge(vin)); + status = MASTERNODE_INPUT_TOO_NEW; + return; + } + + LogPrintf("CActiveMasternode::ManageStatus() - Is capable master node!\n"); + + status = MASTERNODE_IS_CAPABLE; + notCapableReason = ""; + + pwalletMain->LockCoin(vin.prevout); + + // send to all nodes + CPubKey pubKeyMasternode; + CKey keyMasternode; + + if(!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) + { + LogPrintf("Register::ManageStatus() - Error upon calling SetKey: %s\n", errorMessage.c_str()); + return; + } + + if(!Register(vin, service, keyCollateralAddress, pubKeyCollateralAddress, keyMasternode, pubKeyMasternode, errorMessage)) { + LogPrintf("CActiveMasternode::ManageStatus() - Error on Register: %s\n", errorMessage.c_str()); + } + + return; + } else { + LogPrintf("CActiveMasternode::ManageStatus() - Could not find suitable coins!\n"); + } + } + + //send to all peers + if(!Dseep(errorMessage)) { + LogPrintf("CActiveMasternode::ManageStatus() - Error on Ping: %s", errorMessage.c_str()); + } +} + +// Send stop dseep to network for remote masternode +bool CActiveMasternode::StopMasterNode(std::string strService, std::string strKeyMasternode, std::string& errorMessage) { + CTxIn vin; + CKey keyMasternode; + CPubKey pubKeyMasternode; + + if(!darkSendSigner.SetKey(strKeyMasternode, errorMessage, keyMasternode, pubKeyMasternode)) { + LogPrintf("CActiveMasternode::StopMasterNode() - Error: %s\n", errorMessage.c_str()); + return false; + } + + return StopMasterNode(vin, CService(strService), keyMasternode, pubKeyMasternode, errorMessage); +} + +// Send stop dseep to network for main masternode +bool CActiveMasternode::StopMasterNode(std::string& errorMessage) { + if(status != MASTERNODE_IS_CAPABLE && status != MASTERNODE_REMOTELY_ENABLED) { + errorMessage = "masternode is not in a running status"; + LogPrintf("CActiveMasternode::StopMasterNode() - Error: %s\n", errorMessage.c_str()); + return false; + } + + status = MASTERNODE_STOPPED; + + CPubKey pubKeyMasternode; + CKey keyMasternode; + + if(!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) + { + LogPrintf("Register::ManageStatus() - Error upon calling SetKey: %s\n", errorMessage.c_str()); + return false; + } + + return StopMasterNode(vin, service, keyMasternode, pubKeyMasternode, errorMessage); +} + +// Send stop dseep to network for any masternode +bool CActiveMasternode::StopMasterNode(CTxIn vin, CService service, CKey keyMasternode, CPubKey pubKeyMasternode, std::string& errorMessage) { + pwalletMain->UnlockCoin(vin.prevout); + return Dseep(vin, service, keyMasternode, pubKeyMasternode, errorMessage, true); +} + +bool CActiveMasternode::Dseep(std::string& errorMessage) { + if(status != MASTERNODE_IS_CAPABLE && status != MASTERNODE_REMOTELY_ENABLED) { + errorMessage = "masternode is not in a running status"; + LogPrintf("CActiveMasternode::Dseep() - Error: %s\n", errorMessage.c_str()); + return false; + } + + CPubKey pubKeyMasternode; + CKey keyMasternode; + + if(!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, keyMasternode, pubKeyMasternode)) + { + LogPrintf("Register::ManageStatus() - Error upon calling SetKey: %s\n", errorMessage.c_str()); + return false; + } + + return Dseep(vin, service, keyMasternode, pubKeyMasternode, errorMessage, false); +} + +bool CActiveMasternode::Dseep(CTxIn vin, CService service, CKey keyMasternode, CPubKey pubKeyMasternode, std::string &retErrorMessage, bool stop) { + std::string errorMessage; + std::vector vchMasterNodeSignature; + std::string strMasterNodeSignMessage; + int64_t masterNodeSignatureTime = GetAdjustedTime(); + + std::string strMessage = service.ToString() + boost::lexical_cast(masterNodeSignatureTime) + boost::lexical_cast(stop); + + if(!darkSendSigner.SignMessage(strMessage, errorMessage, vchMasterNodeSignature, keyMasternode)) { + retErrorMessage = "sign message failed: " + errorMessage; + LogPrintf("CActiveMasternode::Dseep() - Error: %s\n", retErrorMessage.c_str()); + return false; + } + + if(!darkSendSigner.VerifyMessage(pubKeyMasternode, vchMasterNodeSignature, strMessage, errorMessage)) { + retErrorMessage = "Verify message failed: " + errorMessage; + LogPrintf("CActiveMasternode::Dseep() - Error: %s\n", retErrorMessage.c_str()); + return false; + } + + // Update Last Seen timestamp in masternode list + bool found = false; + BOOST_FOREACH(CMasterNode& mn, vecMasternodes) { + //LogPrintf(" -- %s\n", mn.vin.ToString().c_str()); + if(mn.vin == vin) { + found = true; + mn.UpdateLastSeen(); + } + } + + if(!found){ + // Seems like we are trying to send a ping while the masternode is not registered in the network + retErrorMessage = "Darksend Masternode List doesn't include our masternode, Shutting down masternode pinging service! " + vin.ToString(); + LogPrintf("CActiveMasternode::Dseep() - Error: %s\n", retErrorMessage.c_str()); + status = MASTERNODE_NOT_CAPABLE; + notCapableReason = retErrorMessage; + return false; + } + + //send to all peers + LogPrintf("CActiveMasternode::Dseep() - SendDarkSendElectionEntryPing vin = %s\n", vin.ToString().c_str()); + SendDarkSendElectionEntryPing(vin, vchMasterNodeSignature, masterNodeSignatureTime, stop); + + return true; +} + +bool CActiveMasternode::RegisterByPubKey(std::string strService, std::string strKeyMasternode, std::string collateralAddress, std::string& errorMessage) { + CTxIn vin; + CPubKey pubKeyCollateralAddress; + CKey keyCollateralAddress; + CPubKey pubKeyMasternode; + CKey keyMasternode; + + if(!darkSendSigner.SetKey(strKeyMasternode, errorMessage, keyMasternode, pubKeyMasternode)) + { + LogPrintf("CActiveMasternode::RegisterByPubKey() - Error upon calling SetKey: %s\n", errorMessage.c_str()); + return false; + } + + if(!GetMasterNodeVinForPubKey(collateralAddress, vin, pubKeyCollateralAddress, keyCollateralAddress)) { + errorMessage = "could not allocate vin for collateralAddress"; + LogPrintf("Register::Register() - Error: %s\n", errorMessage.c_str()); + return false; + } + return Register(vin, CService(strService), keyCollateralAddress, pubKeyCollateralAddress, keyMasternode, pubKeyMasternode, errorMessage); +} + +bool CActiveMasternode::Register(std::string strService, std::string strKeyMasternode, std::string txHash, std::string strOutputIndex, std::string& errorMessage) { + CTxIn vin; + CPubKey pubKeyCollateralAddress; + CKey keyCollateralAddress; + CPubKey pubKeyMasternode; + CKey keyMasternode; + + if(!darkSendSigner.SetKey(strKeyMasternode, errorMessage, keyMasternode, pubKeyMasternode)) + { + LogPrintf("CActiveMasternode::Register() - Error upon calling SetKey: %s\n", errorMessage.c_str()); + return false; + } + + if(!GetMasterNodeVin(vin, pubKeyCollateralAddress, keyCollateralAddress, txHash, strOutputIndex)) { + errorMessage = "could not allocate vin"; + LogPrintf("Register::Register() - Error: %s\n", errorMessage.c_str()); + return false; + } + return Register(vin, CService(strService), keyCollateralAddress, pubKeyCollateralAddress, keyMasternode, pubKeyMasternode, errorMessage); +} + +bool CActiveMasternode::Register(CTxIn vin, CService service, CKey keyCollateralAddress, CPubKey pubKeyCollateralAddress, CKey keyMasternode, CPubKey pubKeyMasternode, std::string &retErrorMessage) { + std::string errorMessage; + std::vector vchMasterNodeSignature; + std::string strMasterNodeSignMessage; + int64_t masterNodeSignatureTime = GetAdjustedTime(); + + std::string vchPubKey(pubKeyCollateralAddress.begin(), pubKeyCollateralAddress.end()); + std::string vchPubKey2(pubKeyMasternode.begin(), pubKeyMasternode.end()); + + std::string strMessage = service.ToString() + boost::lexical_cast(masterNodeSignatureTime) + vchPubKey + vchPubKey2 + boost::lexical_cast(PROTOCOL_VERSION); + + if(!darkSendSigner.SignMessage(strMessage, errorMessage, vchMasterNodeSignature, keyCollateralAddress)) { + retErrorMessage = "sign message failed: " + errorMessage; + LogPrintf("CActiveMasternode::Register() - Error: %s\n", retErrorMessage.c_str()); + return false; + } + + if(!darkSendSigner.VerifyMessage(pubKeyCollateralAddress, vchMasterNodeSignature, strMessage, errorMessage)) { + retErrorMessage = "Verify message failed: " + errorMessage; + LogPrintf("CActiveMasternode::Register() - Error: %s\n", retErrorMessage.c_str()); + return false; + } + + bool found = false; + LOCK(cs_masternodes); + BOOST_FOREACH(CMasterNode& mn, vecMasternodes) + if(mn.vin == vin) + found = true; + + if(!found) { + LogPrintf("CActiveMasternode::Register() - Adding to masternode list service: %s - vin: %s\n", service.ToString().c_str(), vin.ToString().c_str()); + CMasterNode mn(service, vin, pubKeyCollateralAddress, vchMasterNodeSignature, masterNodeSignatureTime, pubKeyMasternode, PROTOCOL_VERSION); + mn.UpdateLastSeen(masterNodeSignatureTime); + vecMasternodes.push_back(mn); + } + + //send to all peers + LogPrintf("CActiveMasternode::Register() - SendDarkSendElectionEntry vin = %s\n", vin.ToString().c_str()); + SendDarkSendElectionEntry(vin, service, vchMasterNodeSignature, masterNodeSignatureTime, pubKeyCollateralAddress, pubKeyMasternode, -1, -1, masterNodeSignatureTime, PROTOCOL_VERSION); + + return true; +} + +bool CActiveMasternode::GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey) { + return GetMasterNodeVin(vin, pubkey, secretKey, "", ""); +} + +bool CActiveMasternode::GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex) { + CScript pubScript; + + // Find possible candidates + vector possibleCoins = SelectCoinsMasternode(); + COutput *selectedOutput; + + // Find the vin + if(!strTxHash.empty()) { + // Let's find it + uint256 txHash(strTxHash); + int outputIndex = boost::lexical_cast(strOutputIndex); + bool found = false; + BOOST_FOREACH(COutput& out, possibleCoins) { + if(out.tx->GetHash() == txHash && out.i == outputIndex) + { + selectedOutput = &out; + found = true; + break; + } + } + if(!found) { + LogPrintf("CActiveMasternode::GetMasterNodeVin - Could not locate valid vin\n"); + return false; + } + } else { + // No output specified, Select the first one + if(possibleCoins.size() > 0) { + selectedOutput = &possibleCoins[0]; + } else { + LogPrintf("CActiveMasternode::GetMasterNodeVin - Could not locate specified vin from possible list\n"); + return false; + } + } + + // At this point we have a selected output, retrieve the associated info + return GetVinFromOutput(*selectedOutput, vin, pubkey, secretKey); +} + +bool CActiveMasternode::GetMasterNodeVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey) { + return GetMasterNodeVinForPubKey(collateralAddress, vin, pubkey, secretKey, "", ""); +} + +bool CActiveMasternode::GetMasterNodeVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex) { + CScript pubScript; + + // Find possible candidates + vector possibleCoins = SelectCoinsMasternodeForPubKey(collateralAddress); + COutput *selectedOutput; + + // Find the vin + if(!strTxHash.empty()) { + // Let's find it + uint256 txHash(strTxHash); + int outputIndex = boost::lexical_cast(strOutputIndex); + bool found = false; + BOOST_FOREACH(COutput& out, possibleCoins) { + if(out.tx->GetHash() == txHash && out.i == outputIndex) + { + selectedOutput = &out; + found = true; + break; + } + } + if(!found) { + LogPrintf("CActiveMasternode::GetMasterNodeVinForPubKey - Could not locate valid vin\n"); + return false; + } + } else { + // No output specified, Select the first one + if(possibleCoins.size() > 0) { + selectedOutput = &possibleCoins[0]; + } else { + LogPrintf("CActiveMasternode::GetMasterNodeVinForPubKey - Could not locate specified vin from possible list\n"); + return false; + } + } + + // At this point we have a selected output, retrieve the associated info + return GetVinFromOutput(*selectedOutput, vin, pubkey, secretKey); +} + + +// Extract masternode vin information from output +bool CActiveMasternode::GetVinFromOutput(COutput out, CTxIn& vin, CPubKey& pubkey, CKey& secretKey) { + + CScript pubScript; + + vin = CTxIn(out.tx->GetHash(),out.i); + pubScript = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey + + CTxDestination address1; + ExtractDestination(pubScript, address1); + CBitcoinAddress address2(address1); + + CKeyID keyID; + if (!address2.GetKeyID(keyID)) { + LogPrintf("CActiveMasternode::GetMasterNodeVin - Address does not refer to a key\n"); + return false; + } + + if (!pwalletMain->GetKey(keyID, secretKey)) { + LogPrintf ("CActiveMasternode::GetMasterNodeVin - Private key for address is not known\n"); + return false; + } + + pubkey = secretKey.GetPubKey(); + return true; +} + +// get all possible outputs for running masternode +vector CActiveMasternode::SelectCoinsMasternode() +{ + vector vCoins; + vector filteredCoins; + + // Retrieve all possible outputs + pwalletMain->AvailableCoinsMN(vCoins); + + // Filter + BOOST_FOREACH(const COutput& out, vCoins) + { + if(out.tx->vout[out.i].nValue == 5000*COIN) { //exactly + filteredCoins.push_back(out); + } + } + return filteredCoins; +} + +// get all possible outputs for running masternode for a specific pubkey +vector CActiveMasternode::SelectCoinsMasternodeForPubKey(std::string collateralAddress) +{ + CBitcoinAddress address(collateralAddress); + CScript scriptPubKey; + scriptPubKey.SetDestination(address.Get()); + vector vCoins; + vector filteredCoins; + + // Retrieve all possible outputs + pwalletMain->AvailableCoins(vCoins); + + // Filter + BOOST_FOREACH(const COutput& out, vCoins) + { + if(out.tx->vout[out.i].scriptPubKey == scriptPubKey && out.tx->vout[out.i].nValue == 5000*COIN) { //exactly + filteredCoins.push_back(out); + } + } + return filteredCoins; +} + +// when starting a masternode, this can enable to run as a hot wallet with no funds +bool CActiveMasternode::EnableHotColdMasterNode(CTxIn& newVin, CService& newService) +{ + if(!fMasterNode) return false; + + status = MASTERNODE_REMOTELY_ENABLED; + + //The values below are needed for signing dseep messages going forward + this->vin = newVin; + this->service = newService; + + LogPrintf("CActiveMasternode::EnableHotColdMasterNode() - Enabled! You may shut down the cold daemon.\n"); + + return true; +} diff --git a/src/activemasternode.h b/src/activemasternode.h new file mode 100644 index 0000000..9efb3b3 --- /dev/null +++ b/src/activemasternode.h @@ -0,0 +1,64 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2012 The DarkCoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. +#ifndef ACTIVEMASTERNODE_H +#define ACTIVEMASTERNODE_H + +#include "uint256.h" +#include "sync.h" +#include "net.h" +#include "key.h" +//#include "primitives/transaction.h" +#include "main.h" +#include "init.h" +#include "wallet.h" +#include "darksend.h" + +// Responsible for activating the masternode and pinging the network +class CActiveMasternode +{ +public: + // Initialized by init.cpp + // Keys for the main masternode + CPubKey pubKeyMasternode; + + // Initialized while registering masternode + CTxIn vin; + CService service; + + int status; + std::string notCapableReason; + + CActiveMasternode() + { + status = MASTERNODE_NOT_PROCESSED; + } + + void ManageStatus(); // manage status of main masternode + + bool Dseep(std::string& errorMessage); // ping for main masternode + bool Dseep(CTxIn vin, CService service, CKey key, CPubKey pubKey, std::string &retErrorMessage, bool stop); // ping for any masternode + + bool StopMasterNode(std::string& errorMessage); // stop main masternode + bool StopMasterNode(std::string strService, std::string strKeyMasternode, std::string& errorMessage); // stop remote masternode + bool StopMasterNode(CTxIn vin, CService service, CKey key, CPubKey pubKey, std::string& errorMessage); // stop any masternode + + bool Register(std::string strService, std::string strKey, std::string txHash, std::string strOutputIndex, std::string& errorMessage); // register remote masternode + bool Register(CTxIn vin, CService service, CKey key, CPubKey pubKey, CKey keyMasternode, CPubKey pubKeyMasternode, std::string &retErrorMessage); // register any masternode + bool RegisterByPubKey(std::string strService, std::string strKeyMasternode, std::string collateralAddress, std::string& errorMessage); // register for a specific collateral address + + // get 5000000GENIUS input that can be used for the masternode + bool GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey); + bool GetMasterNodeVin(CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex); + bool GetMasterNodeVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey); + bool GetMasterNodeVinForPubKey(std::string collateralAddress, CTxIn& vin, CPubKey& pubkey, CKey& secretKey, std::string strTxHash, std::string strOutputIndex); + vector SelectCoinsMasternode(); + vector SelectCoinsMasternodeForPubKey(std::string collateralAddress); + bool GetVinFromOutput(COutput out, CTxIn& vin, CPubKey& pubkey, CKey& secretKey); + + // enable hot wallet mode (run a masternode with no funds) + bool EnableHotColdMasterNode(CTxIn& vin, CService& addr); +}; + +#endif diff --git a/src/base58.h b/src/base58.h index f7a550b..bee8e10 100644 --- a/src/base58.h +++ b/src/base58.h @@ -266,6 +266,7 @@ class CBitcoinAddressVisitor : public boost::static_visitor CBitcoinAddressVisitor(CBitcoinAddress *addrIn) : addr(addrIn) { } bool operator()(const CKeyID &id) const; bool operator()(const CScriptID &id) const; + bool operator()(const CStealthAddress &stxAddr) const; bool operator()(const CNoDestination &no) const; }; @@ -343,6 +344,7 @@ class CBitcoinAddress : public CBase58Data bool inline CBitcoinAddressVisitor::operator()(const CKeyID &id) const { return addr->Set(id); } bool inline CBitcoinAddressVisitor::operator()(const CScriptID &id) const { return addr->Set(id); } +bool inline CBitcoinAddressVisitor::operator()(const CStealthAddress &stxAddr) const { return false; } bool inline CBitcoinAddressVisitor::operator()(const CNoDestination &id) const { return false; } /** A base58-encoded secret key */ diff --git a/src/chainparams.cpp b/src/chainparams.cpp index 214f3dc..35ee443 100644 --- a/src/chainparams.cpp +++ b/src/chainparams.cpp @@ -57,6 +57,7 @@ class CMainParams : public CChainParams { nRPCPort = 32222; bnProofOfWorkLimit = CBigNum(~uint256(0) >> 16); + // Build the genesis block. Note that the output of the genesis coinbase cannot // be spent as it did not originally exist in the database. // @@ -84,10 +85,6 @@ class CMainParams : public CChainParams { assert(hashGenesisBlock == uint256("0x0000b17c2900f27ed9cbe5f59373cd6d83d3791c2066a39d59a838801f8d2401")); assert(genesis.hashMerkleRoot == uint256("0x67d4e46e07afb6bb43cc6b9ddbf9511e80db13797a595db8033eef2940fcf886")); - - - - base58Prefixes[PUBKEY_ADDRESS] = list_of(3); base58Prefixes[SCRIPT_ADDRESS] = list_of(85); diff --git a/src/checkpoints.cpp b/src/checkpoints.cpp index 5e09482..4655d70 100644 --- a/src/checkpoints.cpp +++ b/src/checkpoints.cpp @@ -27,8 +27,9 @@ namespace Checkpoints // static MapCheckpoints mapCheckpoints = boost::assign::map_list_of - ( 0, uint256("0x0000b17c2900f27ed9cbe5f59373cd6d83d3791c2066a39d59a838801f8d2401") ) - + ( 0, uint256("0x0000b17c2900f27ed9cbe5f59373cd6d83d3791c2066a39d59a838801f8d2401") ) + ( 4000, uint256("0x2591b57eaf27a75a9cff7366e647dbbc2faef6cfe32d7469cbbf66ed5aae44ca") ) + ; // TestNet has no checkpoints diff --git a/src/clientversion.h b/src/clientversion.h index 8e0c7b9..94f2efd 100644 --- a/src/clientversion.h +++ b/src/clientversion.h @@ -7,7 +7,7 @@ // These need to be macros, as version.cpp's and bitcoin-qt.rc's voodoo requires it #define CLIENT_VERSION_MAJOR 1 -#define CLIENT_VERSION_MINOR 0 +#define CLIENT_VERSION_MINOR 1 #define CLIENT_VERSION_REVISION 0 #define CLIENT_VERSION_BUILD 0 diff --git a/src/core.h b/src/core.h index 4d73632..76db627 100644 --- a/src/core.h +++ b/src/core.h @@ -12,6 +12,7 @@ #include +class CScript; class CTransaction; /** An outpoint - a combination of a transaction hash and an index n into its vout */ @@ -70,6 +71,7 @@ class CTxIn public: COutPoint prevout; CScript scriptSig; + CScript prevPubKey; unsigned int nSequence; CTxIn() @@ -84,7 +86,7 @@ class CTxIn nSequence = nSequenceIn; } - CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits::max()) + explicit CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits::max()) { prevout = COutPoint(hashPrevTx, nOut); scriptSig = scriptSigIn; diff --git a/src/crypter.cpp b/src/crypter.cpp index 0898aa0..a057d28 100644 --- a/src/crypter.cpp +++ b/src/crypter.cpp @@ -10,8 +10,13 @@ #include #include #include +#include +#include +#include +#include #include #include +#include #ifdef WIN32 #include #endif @@ -137,6 +142,73 @@ bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector &vchCiphertext); bool DecryptSecret(const CKeyingMaterial& vMasterKey, const std::vector& vchCiphertext, const uint256& nIV, CKeyingMaterial& vchPlaintext); +bool EncryptAES256(const SecureString& sKey, const SecureString& sPlaintext, const std::string& sIV, std::string& sCiphertext); +bool DecryptAES256(const SecureString& sKey, const std::string& sCiphertext, const std::string& sIV, SecureString& sPlaintext); + /** Keystore which keeps the private keys encrypted. * It derives from the basic key store, which is used if no encryption is active. */ class CCryptoKeyStore : public CBasicKeyStore { private: - CryptedKeyMap mapCryptedKeys; - - CKeyingMaterial vMasterKey; - // if fUseCrypto is true, mapKeys must be empty // if fUseCrypto is false, vMasterKey must be empty bool fUseCrypto; protected: + CryptedKeyMap mapCryptedKeys; + CKeyingMaterial vMasterKey; + bool SetCrypted(); // will encrypt previously unencrypted keys @@ -169,7 +171,7 @@ class CCryptoKeyStore : public CBasicKeyStore return result; } - bool Lock(); + bool LockKeyStore(); virtual bool AddCryptedKey(const CPubKey &vchPubKey, const std::vector &vchCryptedSecret); bool AddKeyPubKey(const CKey& key, const CPubKey &pubkey); @@ -207,4 +209,7 @@ class CCryptoKeyStore : public CBasicKeyStore boost::signals2::signal NotifyStatusChanged; }; + + + #endif diff --git a/src/crypto/common.h b/src/crypto/common.h new file mode 100644 index 0000000..d890667 --- /dev/null +++ b/src/crypto/common.h @@ -0,0 +1,116 @@ +// Copyright (c) 2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef GENIUS_CRYPTO_COMMON_H +#define GENIUS_CRYPTO_COMMON_H + +#include + +#if defined(HAVE_ENDIAN_H) +#include +#endif + +uint32_t static inline ReadLE32(const unsigned char* ptr) +{ +#if HAVE_DECL_LE32TOH == 1 + return le32toh(*((uint32_t*)ptr)); +#elif !defined(WORDS_BIGENDIAN) + return *((uint32_t*)ptr); +#else + return ((uint32_t)ptr[3] << 24 | (uint32_t)ptr[2] << 16 | (uint32_t)ptr[1] << 8 | (uint32_t)ptr[0]); +#endif +} + +uint64_t static inline ReadLE64(const unsigned char* ptr) +{ +#if HAVE_DECL_LE64TOH == 1 + return le64toh(*((uint64_t*)ptr)); +#elif !defined(WORDS_BIGENDIAN) + return *((uint64_t*)ptr); +#else + return ((uint64_t)ptr[7] << 56 | (uint64_t)ptr[6] << 48 | (uint64_t)ptr[5] << 40 | (uint64_t)ptr[4] << 32 | + (uint64_t)ptr[3] << 24 | (uint64_t)ptr[2] << 16 | (uint64_t)ptr[1] << 8 | (uint64_t)ptr[0]); +#endif +} + +void static inline WriteLE32(unsigned char* ptr, uint32_t x) +{ +#if HAVE_DECL_HTOLE32 == 1 + *((uint32_t*)ptr) = htole32(x); +#elif !defined(WORDS_BIGENDIAN) + *((uint32_t*)ptr) = x; +#else + ptr[3] = x >> 24; + ptr[2] = x >> 16; + ptr[1] = x >> 8; + ptr[0] = x; +#endif +} + +void static inline WriteLE64(unsigned char* ptr, uint64_t x) +{ +#if HAVE_DECL_HTOLE64 == 1 + *((uint64_t*)ptr) = htole64(x); +#elif !defined(WORDS_BIGENDIAN) + *((uint64_t*)ptr) = x; +#else + ptr[7] = x >> 56; + ptr[6] = x >> 48; + ptr[5] = x >> 40; + ptr[4] = x >> 32; + ptr[3] = x >> 24; + ptr[2] = x >> 16; + ptr[1] = x >> 8; + ptr[0] = x; +#endif +} + +uint32_t static inline ReadBE32(const unsigned char* ptr) +{ +#if HAVE_DECL_BE32TOH == 1 + return be32toh(*((uint32_t*)ptr)); +#else + return ((uint32_t)ptr[0] << 24 | (uint32_t)ptr[1] << 16 | (uint32_t)ptr[2] << 8 | (uint32_t)ptr[3]); +#endif +} + +uint64_t static inline ReadBE64(const unsigned char* ptr) +{ +#if HAVE_DECL_BE64TOH == 1 + return be64toh(*((uint64_t*)ptr)); +#else + return ((uint64_t)ptr[0] << 56 | (uint64_t)ptr[1] << 48 | (uint64_t)ptr[2] << 40 | (uint64_t)ptr[3] << 32 | + (uint64_t)ptr[4] << 24 | (uint64_t)ptr[5] << 16 | (uint64_t)ptr[6] << 8 | (uint64_t)ptr[7]); +#endif +} + +void static inline WriteBE32(unsigned char* ptr, uint32_t x) +{ +#if HAVE_DECL_HTOBE32 == 1 + *((uint32_t*)ptr) = htobe32(x); +#else + ptr[0] = x >> 24; + ptr[1] = x >> 16; + ptr[2] = x >> 8; + ptr[3] = x; +#endif +} + +void static inline WriteBE64(unsigned char* ptr, uint64_t x) +{ +#if HAVE_DECL_HTOBE64 == 1 + *((uint64_t*)ptr) = htobe64(x); +#else + ptr[0] = x >> 56; + ptr[1] = x >> 48; + ptr[2] = x >> 40; + ptr[3] = x >> 32; + ptr[4] = x >> 24; + ptr[5] = x >> 16; + ptr[6] = x >> 8; + ptr[7] = x; +#endif +} + +#endif // GENIUS_CRYPTO_COMMON_H diff --git a/src/crypto/hmac_sha256.cpp b/src/crypto/hmac_sha256.cpp new file mode 100644 index 0000000..3c79162 --- /dev/null +++ b/src/crypto/hmac_sha256.cpp @@ -0,0 +1,34 @@ +// Copyright (c) 2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "crypto/hmac_sha256.h" + +#include + +CHMAC_SHA256::CHMAC_SHA256(const unsigned char* key, size_t keylen) +{ + unsigned char rkey[64]; + if (keylen <= 64) { + memcpy(rkey, key, keylen); + memset(rkey + keylen, 0, 64 - keylen); + } else { + CSHA256().Write(key, keylen).Finalize(rkey); + memset(rkey + 32, 0, 32); + } + + for (int n = 0; n < 64; n++) + rkey[n] ^= 0x5c; + outer.Write(rkey, 64); + + for (int n = 0; n < 64; n++) + rkey[n] ^= 0x5c ^ 0x36; + inner.Write(rkey, 64); +} + +void CHMAC_SHA256::Finalize(unsigned char hash[OUTPUT_SIZE]) +{ + unsigned char temp[32]; + inner.Finalize(temp); + outer.Write(temp, 32).Finalize(hash); +} diff --git a/src/crypto/hmac_sha256.h b/src/crypto/hmac_sha256.h new file mode 100644 index 0000000..1519c14 --- /dev/null +++ b/src/crypto/hmac_sha256.h @@ -0,0 +1,32 @@ +// Copyright (c) 2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_CRYPTO_HMAC_SHA256_H +#define BITCOIN_CRYPTO_HMAC_SHA256_H + +#include "crypto/sha256.h" + +#include +#include + +/** A hasher class for HMAC-SHA-512. */ +class CHMAC_SHA256 +{ +private: + CSHA256 outer; + CSHA256 inner; + +public: + static const size_t OUTPUT_SIZE = 32; + + CHMAC_SHA256(const unsigned char* key, size_t keylen); + CHMAC_SHA256& Write(const unsigned char* data, size_t len) + { + inner.Write(data, len); + return *this; + } + void Finalize(unsigned char hash[OUTPUT_SIZE]); +}; + +#endif // BITCOIN_CRYPTO_HMAC_SHA256_H diff --git a/src/crypto/hmac_sha512.cpp b/src/crypto/hmac_sha512.cpp new file mode 100644 index 0000000..5939c6e --- /dev/null +++ b/src/crypto/hmac_sha512.cpp @@ -0,0 +1,34 @@ +// Copyright (c) 2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "crypto/hmac_sha512.h" + +#include + +CHMAC_SHA512::CHMAC_SHA512(const unsigned char* key, size_t keylen) +{ + unsigned char rkey[128]; + if (keylen <= 128) { + memcpy(rkey, key, keylen); + memset(rkey + keylen, 0, 128 - keylen); + } else { + CSHA512().Write(key, keylen).Finalize(rkey); + memset(rkey + 64, 0, 64); + } + + for (int n = 0; n < 128; n++) + rkey[n] ^= 0x5c; + outer.Write(rkey, 128); + + for (int n = 0; n < 128; n++) + rkey[n] ^= 0x5c ^ 0x36; + inner.Write(rkey, 128); +} + +void CHMAC_SHA512::Finalize(unsigned char hash[OUTPUT_SIZE]) +{ + unsigned char temp[64]; + inner.Finalize(temp); + outer.Write(temp, 64).Finalize(hash); +} diff --git a/src/crypto/hmac_sha512.h b/src/crypto/hmac_sha512.h new file mode 100644 index 0000000..17dee61 --- /dev/null +++ b/src/crypto/hmac_sha512.h @@ -0,0 +1,32 @@ +// Copyright (c) 2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_CRYPTO_HMAC_SHA512_H +#define BITCOIN_CRYPTO_HMAC_SHA512_H + +#include "crypto/sha512.h" + +#include +#include + +/** A hasher class for HMAC-SHA-512. */ +class CHMAC_SHA512 +{ +private: + CSHA512 outer; + CSHA512 inner; + +public: + static const size_t OUTPUT_SIZE = 64; + + CHMAC_SHA512(const unsigned char* key, size_t keylen); + CHMAC_SHA512& Write(const unsigned char* data, size_t len) + { + inner.Write(data, len); + return *this; + } + void Finalize(unsigned char hash[OUTPUT_SIZE]); +}; + +#endif // BITCOIN_CRYPTO_HMAC_SHA512_H diff --git a/src/crypto/rfc6979_hmac_sha256.cpp b/src/crypto/rfc6979_hmac_sha256.cpp new file mode 100644 index 0000000..a8c971c --- /dev/null +++ b/src/crypto/rfc6979_hmac_sha256.cpp @@ -0,0 +1,47 @@ +// Copyright (c) 2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "crypto/rfc6979_hmac_sha256.h" + +#include + +#include + +static const unsigned char zero[1] = {0x00}; +static const unsigned char one[1] = {0x01}; + +RFC6979_HMAC_SHA256::RFC6979_HMAC_SHA256(const unsigned char* key, size_t keylen, const unsigned char* msg, size_t msglen) : retry(false) +{ + memset(V, 0x01, sizeof(V)); + memset(K, 0x00, sizeof(K)); + + CHMAC_SHA256(K, sizeof(K)).Write(V, sizeof(V)).Write(zero, sizeof(zero)).Write(key, keylen).Write(msg, msglen).Finalize(K); + CHMAC_SHA256(K, sizeof(K)).Write(V, sizeof(V)).Finalize(V); + CHMAC_SHA256(K, sizeof(K)).Write(V, sizeof(V)).Write(one, sizeof(one)).Write(key, keylen).Write(msg, msglen).Finalize(K); + CHMAC_SHA256(K, sizeof(K)).Write(V, sizeof(V)).Finalize(V); +} + +RFC6979_HMAC_SHA256::~RFC6979_HMAC_SHA256() +{ + memset(V, 0x01, sizeof(V)); + memset(K, 0x00, sizeof(K)); +} + +void RFC6979_HMAC_SHA256::Generate(unsigned char* output, size_t outputlen) +{ + if (retry) { + CHMAC_SHA256(K, sizeof(K)).Write(V, sizeof(V)).Write(zero, sizeof(zero)).Finalize(K); + CHMAC_SHA256(K, sizeof(K)).Write(V, sizeof(V)).Finalize(V); + } + + while (outputlen > 0) { + CHMAC_SHA256(K, sizeof(K)).Write(V, sizeof(V)).Finalize(V); + size_t len = std::min(outputlen, sizeof(V)); + memcpy(output, V, len); + output += len; + outputlen -= len; + } + + retry = true; +} diff --git a/src/crypto/rfc6979_hmac_sha256.h b/src/crypto/rfc6979_hmac_sha256.h new file mode 100644 index 0000000..f3a54a5 --- /dev/null +++ b/src/crypto/rfc6979_hmac_sha256.h @@ -0,0 +1,36 @@ +// Copyright (c) 2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_RFC6979_HMAC_SHA256_H +#define BITCOIN_RFC6979_HMAC_SHA256_H + +#include "crypto/hmac_sha256.h" + +#include +#include + +/** The RFC 6979 PRNG using HMAC-SHA256. */ +class RFC6979_HMAC_SHA256 +{ +private: + unsigned char V[CHMAC_SHA256::OUTPUT_SIZE]; + unsigned char K[CHMAC_SHA256::OUTPUT_SIZE]; + bool retry; + +public: + /** + * Construct a new RFC6979 PRNG, using the given key and message. + * The message is assumed to be already hashed. + */ + RFC6979_HMAC_SHA256(const unsigned char* key, size_t keylen, const unsigned char* msg, size_t msglen); + + /** + * Generate a byte array. + */ + void Generate(unsigned char* output, size_t outputlen); + + ~RFC6979_HMAC_SHA256(); +}; + +#endif // BITCOIN_RFC6979_HMAC_SHA256_H diff --git a/src/crypto/ripemd160.cpp b/src/crypto/ripemd160.cpp new file mode 100644 index 0000000..77c9acf --- /dev/null +++ b/src/crypto/ripemd160.cpp @@ -0,0 +1,292 @@ +// Copyright (c) 2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "crypto/ripemd160.h" + +#include "crypto/common.h" + +#include + +// Internal implementation code. +namespace +{ +/// Internal RIPEMD-160 implementation. +namespace ripemd160 +{ +uint32_t inline f1(uint32_t x, uint32_t y, uint32_t z) { return x ^ y ^ z; } +uint32_t inline f2(uint32_t x, uint32_t y, uint32_t z) { return (x & y) | (~x & z); } +uint32_t inline f3(uint32_t x, uint32_t y, uint32_t z) { return (x | ~y) ^ z; } +uint32_t inline f4(uint32_t x, uint32_t y, uint32_t z) { return (x & z) | (y & ~z); } +uint32_t inline f5(uint32_t x, uint32_t y, uint32_t z) { return x ^ (y | ~z); } + +/** Initialize RIPEMD-160 state. */ +void inline Initialize(uint32_t* s) +{ + s[0] = 0x67452301ul; + s[1] = 0xEFCDAB89ul; + s[2] = 0x98BADCFEul; + s[3] = 0x10325476ul; + s[4] = 0xC3D2E1F0ul; +} + +uint32_t inline rol(uint32_t x, int i) { return (x << i) | (x >> (32 - i)); } + +void inline Round(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t f, uint32_t x, uint32_t k, int r) +{ + a = rol(a + f + x + k, r) + e; + c = rol(c, 10); +} + +void inline R11(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f1(b, c, d), x, 0, r); } +void inline R21(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f2(b, c, d), x, 0x5A827999ul, r); } +void inline R31(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f3(b, c, d), x, 0x6ED9EBA1ul, r); } +void inline R41(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f4(b, c, d), x, 0x8F1BBCDCul, r); } +void inline R51(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f5(b, c, d), x, 0xA953FD4Eul, r); } + +void inline R12(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f5(b, c, d), x, 0x50A28BE6ul, r); } +void inline R22(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f4(b, c, d), x, 0x5C4DD124ul, r); } +void inline R32(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f3(b, c, d), x, 0x6D703EF3ul, r); } +void inline R42(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f2(b, c, d), x, 0x7A6D76E9ul, r); } +void inline R52(uint32_t& a, uint32_t b, uint32_t& c, uint32_t d, uint32_t e, uint32_t x, int r) { Round(a, b, c, d, e, f1(b, c, d), x, 0, r); } + +/** Perform a RIPEMD-160 transformation, processing a 64-byte chunk. */ +void Transform(uint32_t* s, const unsigned char* chunk) +{ + uint32_t a1 = s[0], b1 = s[1], c1 = s[2], d1 = s[3], e1 = s[4]; + uint32_t a2 = a1, b2 = b1, c2 = c1, d2 = d1, e2 = e1; + uint32_t w0 = ReadLE32(chunk + 0), w1 = ReadLE32(chunk + 4), w2 = ReadLE32(chunk + 8), w3 = ReadLE32(chunk + 12); + uint32_t w4 = ReadLE32(chunk + 16), w5 = ReadLE32(chunk + 20), w6 = ReadLE32(chunk + 24), w7 = ReadLE32(chunk + 28); + uint32_t w8 = ReadLE32(chunk + 32), w9 = ReadLE32(chunk + 36), w10 = ReadLE32(chunk + 40), w11 = ReadLE32(chunk + 44); + uint32_t w12 = ReadLE32(chunk + 48), w13 = ReadLE32(chunk + 52), w14 = ReadLE32(chunk + 56), w15 = ReadLE32(chunk + 60); + + R11(a1, b1, c1, d1, e1, w0, 11); + R12(a2, b2, c2, d2, e2, w5, 8); + R11(e1, a1, b1, c1, d1, w1, 14); + R12(e2, a2, b2, c2, d2, w14, 9); + R11(d1, e1, a1, b1, c1, w2, 15); + R12(d2, e2, a2, b2, c2, w7, 9); + R11(c1, d1, e1, a1, b1, w3, 12); + R12(c2, d2, e2, a2, b2, w0, 11); + R11(b1, c1, d1, e1, a1, w4, 5); + R12(b2, c2, d2, e2, a2, w9, 13); + R11(a1, b1, c1, d1, e1, w5, 8); + R12(a2, b2, c2, d2, e2, w2, 15); + R11(e1, a1, b1, c1, d1, w6, 7); + R12(e2, a2, b2, c2, d2, w11, 15); + R11(d1, e1, a1, b1, c1, w7, 9); + R12(d2, e2, a2, b2, c2, w4, 5); + R11(c1, d1, e1, a1, b1, w8, 11); + R12(c2, d2, e2, a2, b2, w13, 7); + R11(b1, c1, d1, e1, a1, w9, 13); + R12(b2, c2, d2, e2, a2, w6, 7); + R11(a1, b1, c1, d1, e1, w10, 14); + R12(a2, b2, c2, d2, e2, w15, 8); + R11(e1, a1, b1, c1, d1, w11, 15); + R12(e2, a2, b2, c2, d2, w8, 11); + R11(d1, e1, a1, b1, c1, w12, 6); + R12(d2, e2, a2, b2, c2, w1, 14); + R11(c1, d1, e1, a1, b1, w13, 7); + R12(c2, d2, e2, a2, b2, w10, 14); + R11(b1, c1, d1, e1, a1, w14, 9); + R12(b2, c2, d2, e2, a2, w3, 12); + R11(a1, b1, c1, d1, e1, w15, 8); + R12(a2, b2, c2, d2, e2, w12, 6); + + R21(e1, a1, b1, c1, d1, w7, 7); + R22(e2, a2, b2, c2, d2, w6, 9); + R21(d1, e1, a1, b1, c1, w4, 6); + R22(d2, e2, a2, b2, c2, w11, 13); + R21(c1, d1, e1, a1, b1, w13, 8); + R22(c2, d2, e2, a2, b2, w3, 15); + R21(b1, c1, d1, e1, a1, w1, 13); + R22(b2, c2, d2, e2, a2, w7, 7); + R21(a1, b1, c1, d1, e1, w10, 11); + R22(a2, b2, c2, d2, e2, w0, 12); + R21(e1, a1, b1, c1, d1, w6, 9); + R22(e2, a2, b2, c2, d2, w13, 8); + R21(d1, e1, a1, b1, c1, w15, 7); + R22(d2, e2, a2, b2, c2, w5, 9); + R21(c1, d1, e1, a1, b1, w3, 15); + R22(c2, d2, e2, a2, b2, w10, 11); + R21(b1, c1, d1, e1, a1, w12, 7); + R22(b2, c2, d2, e2, a2, w14, 7); + R21(a1, b1, c1, d1, e1, w0, 12); + R22(a2, b2, c2, d2, e2, w15, 7); + R21(e1, a1, b1, c1, d1, w9, 15); + R22(e2, a2, b2, c2, d2, w8, 12); + R21(d1, e1, a1, b1, c1, w5, 9); + R22(d2, e2, a2, b2, c2, w12, 7); + R21(c1, d1, e1, a1, b1, w2, 11); + R22(c2, d2, e2, a2, b2, w4, 6); + R21(b1, c1, d1, e1, a1, w14, 7); + R22(b2, c2, d2, e2, a2, w9, 15); + R21(a1, b1, c1, d1, e1, w11, 13); + R22(a2, b2, c2, d2, e2, w1, 13); + R21(e1, a1, b1, c1, d1, w8, 12); + R22(e2, a2, b2, c2, d2, w2, 11); + + R31(d1, e1, a1, b1, c1, w3, 11); + R32(d2, e2, a2, b2, c2, w15, 9); + R31(c1, d1, e1, a1, b1, w10, 13); + R32(c2, d2, e2, a2, b2, w5, 7); + R31(b1, c1, d1, e1, a1, w14, 6); + R32(b2, c2, d2, e2, a2, w1, 15); + R31(a1, b1, c1, d1, e1, w4, 7); + R32(a2, b2, c2, d2, e2, w3, 11); + R31(e1, a1, b1, c1, d1, w9, 14); + R32(e2, a2, b2, c2, d2, w7, 8); + R31(d1, e1, a1, b1, c1, w15, 9); + R32(d2, e2, a2, b2, c2, w14, 6); + R31(c1, d1, e1, a1, b1, w8, 13); + R32(c2, d2, e2, a2, b2, w6, 6); + R31(b1, c1, d1, e1, a1, w1, 15); + R32(b2, c2, d2, e2, a2, w9, 14); + R31(a1, b1, c1, d1, e1, w2, 14); + R32(a2, b2, c2, d2, e2, w11, 12); + R31(e1, a1, b1, c1, d1, w7, 8); + R32(e2, a2, b2, c2, d2, w8, 13); + R31(d1, e1, a1, b1, c1, w0, 13); + R32(d2, e2, a2, b2, c2, w12, 5); + R31(c1, d1, e1, a1, b1, w6, 6); + R32(c2, d2, e2, a2, b2, w2, 14); + R31(b1, c1, d1, e1, a1, w13, 5); + R32(b2, c2, d2, e2, a2, w10, 13); + R31(a1, b1, c1, d1, e1, w11, 12); + R32(a2, b2, c2, d2, e2, w0, 13); + R31(e1, a1, b1, c1, d1, w5, 7); + R32(e2, a2, b2, c2, d2, w4, 7); + R31(d1, e1, a1, b1, c1, w12, 5); + R32(d2, e2, a2, b2, c2, w13, 5); + + R41(c1, d1, e1, a1, b1, w1, 11); + R42(c2, d2, e2, a2, b2, w8, 15); + R41(b1, c1, d1, e1, a1, w9, 12); + R42(b2, c2, d2, e2, a2, w6, 5); + R41(a1, b1, c1, d1, e1, w11, 14); + R42(a2, b2, c2, d2, e2, w4, 8); + R41(e1, a1, b1, c1, d1, w10, 15); + R42(e2, a2, b2, c2, d2, w1, 11); + R41(d1, e1, a1, b1, c1, w0, 14); + R42(d2, e2, a2, b2, c2, w3, 14); + R41(c1, d1, e1, a1, b1, w8, 15); + R42(c2, d2, e2, a2, b2, w11, 14); + R41(b1, c1, d1, e1, a1, w12, 9); + R42(b2, c2, d2, e2, a2, w15, 6); + R41(a1, b1, c1, d1, e1, w4, 8); + R42(a2, b2, c2, d2, e2, w0, 14); + R41(e1, a1, b1, c1, d1, w13, 9); + R42(e2, a2, b2, c2, d2, w5, 6); + R41(d1, e1, a1, b1, c1, w3, 14); + R42(d2, e2, a2, b2, c2, w12, 9); + R41(c1, d1, e1, a1, b1, w7, 5); + R42(c2, d2, e2, a2, b2, w2, 12); + R41(b1, c1, d1, e1, a1, w15, 6); + R42(b2, c2, d2, e2, a2, w13, 9); + R41(a1, b1, c1, d1, e1, w14, 8); + R42(a2, b2, c2, d2, e2, w9, 12); + R41(e1, a1, b1, c1, d1, w5, 6); + R42(e2, a2, b2, c2, d2, w7, 5); + R41(d1, e1, a1, b1, c1, w6, 5); + R42(d2, e2, a2, b2, c2, w10, 15); + R41(c1, d1, e1, a1, b1, w2, 12); + R42(c2, d2, e2, a2, b2, w14, 8); + + R51(b1, c1, d1, e1, a1, w4, 9); + R52(b2, c2, d2, e2, a2, w12, 8); + R51(a1, b1, c1, d1, e1, w0, 15); + R52(a2, b2, c2, d2, e2, w15, 5); + R51(e1, a1, b1, c1, d1, w5, 5); + R52(e2, a2, b2, c2, d2, w10, 12); + R51(d1, e1, a1, b1, c1, w9, 11); + R52(d2, e2, a2, b2, c2, w4, 9); + R51(c1, d1, e1, a1, b1, w7, 6); + R52(c2, d2, e2, a2, b2, w1, 12); + R51(b1, c1, d1, e1, a1, w12, 8); + R52(b2, c2, d2, e2, a2, w5, 5); + R51(a1, b1, c1, d1, e1, w2, 13); + R52(a2, b2, c2, d2, e2, w8, 14); + R51(e1, a1, b1, c1, d1, w10, 12); + R52(e2, a2, b2, c2, d2, w7, 6); + R51(d1, e1, a1, b1, c1, w14, 5); + R52(d2, e2, a2, b2, c2, w6, 8); + R51(c1, d1, e1, a1, b1, w1, 12); + R52(c2, d2, e2, a2, b2, w2, 13); + R51(b1, c1, d1, e1, a1, w3, 13); + R52(b2, c2, d2, e2, a2, w13, 6); + R51(a1, b1, c1, d1, e1, w8, 14); + R52(a2, b2, c2, d2, e2, w14, 5); + R51(e1, a1, b1, c1, d1, w11, 11); + R52(e2, a2, b2, c2, d2, w0, 15); + R51(d1, e1, a1, b1, c1, w6, 8); + R52(d2, e2, a2, b2, c2, w3, 13); + R51(c1, d1, e1, a1, b1, w15, 5); + R52(c2, d2, e2, a2, b2, w9, 11); + R51(b1, c1, d1, e1, a1, w13, 6); + R52(b2, c2, d2, e2, a2, w11, 11); + + uint32_t t = s[0]; + s[0] = s[1] + c1 + d2; + s[1] = s[2] + d1 + e2; + s[2] = s[3] + e1 + a2; + s[3] = s[4] + a1 + b2; + s[4] = t + b1 + c2; +} + +} // namespace ripemd160 + +} // namespace + +////// RIPEMD160 + +CRIPEMD160::CRIPEMD160() : bytes(0) +{ + ripemd160::Initialize(s); +} + +CRIPEMD160& CRIPEMD160::Write(const unsigned char* data, size_t len) +{ + const unsigned char* end = data + len; + size_t bufsize = bytes % 64; + if (bufsize && bufsize + len >= 64) { + // Fill the buffer, and process it. + memcpy(buf + bufsize, data, 64 - bufsize); + bytes += 64 - bufsize; + data += 64 - bufsize; + ripemd160::Transform(s, buf); + bufsize = 0; + } + while (end >= data + 64) { + // Process full chunks directly from the source. + ripemd160::Transform(s, data); + bytes += 64; + data += 64; + } + if (end > data) { + // Fill the buffer with what remains. + memcpy(buf + bufsize, data, end - data); + bytes += end - data; + } + return *this; +} + +void CRIPEMD160::Finalize(unsigned char hash[OUTPUT_SIZE]) +{ + static const unsigned char pad[64] = {0x80}; + unsigned char sizedesc[8]; + WriteLE64(sizedesc, bytes << 3); + Write(pad, 1 + ((119 - (bytes % 64)) % 64)); + Write(sizedesc, 8); + WriteLE32(hash, s[0]); + WriteLE32(hash + 4, s[1]); + WriteLE32(hash + 8, s[2]); + WriteLE32(hash + 12, s[3]); + WriteLE32(hash + 16, s[4]); +} + +CRIPEMD160& CRIPEMD160::Reset() +{ + bytes = 0; + ripemd160::Initialize(s); + return *this; +} diff --git a/src/crypto/ripemd160.h b/src/crypto/ripemd160.h new file mode 100644 index 0000000..687204f --- /dev/null +++ b/src/crypto/ripemd160.h @@ -0,0 +1,28 @@ +// Copyright (c) 2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_CRYPTO_RIPEMD160_H +#define BITCOIN_CRYPTO_RIPEMD160_H + +#include +#include + +/** A hasher class for RIPEMD-160. */ +class CRIPEMD160 +{ +private: + uint32_t s[5]; + unsigned char buf[64]; + size_t bytes; + +public: + static const size_t OUTPUT_SIZE = 20; + + CRIPEMD160(); + CRIPEMD160& Write(const unsigned char* data, size_t len); + void Finalize(unsigned char hash[OUTPUT_SIZE]); + CRIPEMD160& Reset(); +}; + +#endif // BITCOIN_CRYPTO_RIPEMD160_H diff --git a/src/crypto/sha1.cpp b/src/crypto/sha1.cpp new file mode 100644 index 0000000..0b895b3 --- /dev/null +++ b/src/crypto/sha1.cpp @@ -0,0 +1,199 @@ +// Copyright (c) 2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "crypto/sha1.h" + +#include "crypto/common.h" + +#include + +// Internal implementation code. +namespace +{ +/// Internal SHA-1 implementation. +namespace sha1 +{ +/** One round of SHA-1. */ +void inline Round(uint32_t a, uint32_t& b, uint32_t c, uint32_t d, uint32_t& e, uint32_t f, uint32_t k, uint32_t w) +{ + e += ((a << 5) | (a >> 27)) + f + k + w; + b = (b << 30) | (b >> 2); +} + +uint32_t inline f1(uint32_t b, uint32_t c, uint32_t d) { return d ^ (b & (c ^ d)); } +uint32_t inline f2(uint32_t b, uint32_t c, uint32_t d) { return b ^ c ^ d; } +uint32_t inline f3(uint32_t b, uint32_t c, uint32_t d) { return (b & c) | (d & (b | c)); } + +uint32_t inline left(uint32_t x) { return (x << 1) | (x >> 31); } + +/** Initialize SHA-1 state. */ +void inline Initialize(uint32_t* s) +{ + s[0] = 0x67452301ul; + s[1] = 0xEFCDAB89ul; + s[2] = 0x98BADCFEul; + s[3] = 0x10325476ul; + s[4] = 0xC3D2E1F0ul; +} + +const uint32_t k1 = 0x5A827999ul; +const uint32_t k2 = 0x6ED9EBA1ul; +const uint32_t k3 = 0x8F1BBCDCul; +const uint32_t k4 = 0xCA62C1D6ul; + +/** Perform a SHA-1 transformation, processing a 64-byte chunk. */ +void Transform(uint32_t* s, const unsigned char* chunk) +{ + uint32_t a = s[0], b = s[1], c = s[2], d = s[3], e = s[4]; + uint32_t w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15; + + Round(a, b, c, d, e, f1(b, c, d), k1, w0 = ReadBE32(chunk + 0)); + Round(e, a, b, c, d, f1(a, b, c), k1, w1 = ReadBE32(chunk + 4)); + Round(d, e, a, b, c, f1(e, a, b), k1, w2 = ReadBE32(chunk + 8)); + Round(c, d, e, a, b, f1(d, e, a), k1, w3 = ReadBE32(chunk + 12)); + Round(b, c, d, e, a, f1(c, d, e), k1, w4 = ReadBE32(chunk + 16)); + Round(a, b, c, d, e, f1(b, c, d), k1, w5 = ReadBE32(chunk + 20)); + Round(e, a, b, c, d, f1(a, b, c), k1, w6 = ReadBE32(chunk + 24)); + Round(d, e, a, b, c, f1(e, a, b), k1, w7 = ReadBE32(chunk + 28)); + Round(c, d, e, a, b, f1(d, e, a), k1, w8 = ReadBE32(chunk + 32)); + Round(b, c, d, e, a, f1(c, d, e), k1, w9 = ReadBE32(chunk + 36)); + Round(a, b, c, d, e, f1(b, c, d), k1, w10 = ReadBE32(chunk + 40)); + Round(e, a, b, c, d, f1(a, b, c), k1, w11 = ReadBE32(chunk + 44)); + Round(d, e, a, b, c, f1(e, a, b), k1, w12 = ReadBE32(chunk + 48)); + Round(c, d, e, a, b, f1(d, e, a), k1, w13 = ReadBE32(chunk + 52)); + Round(b, c, d, e, a, f1(c, d, e), k1, w14 = ReadBE32(chunk + 56)); + Round(a, b, c, d, e, f1(b, c, d), k1, w15 = ReadBE32(chunk + 60)); + + Round(e, a, b, c, d, f1(a, b, c), k1, w0 = left(w0 ^ w13 ^ w8 ^ w2)); + Round(d, e, a, b, c, f1(e, a, b), k1, w1 = left(w1 ^ w14 ^ w9 ^ w3)); + Round(c, d, e, a, b, f1(d, e, a), k1, w2 = left(w2 ^ w15 ^ w10 ^ w4)); + Round(b, c, d, e, a, f1(c, d, e), k1, w3 = left(w3 ^ w0 ^ w11 ^ w5)); + Round(a, b, c, d, e, f2(b, c, d), k2, w4 = left(w4 ^ w1 ^ w12 ^ w6)); + Round(e, a, b, c, d, f2(a, b, c), k2, w5 = left(w5 ^ w2 ^ w13 ^ w7)); + Round(d, e, a, b, c, f2(e, a, b), k2, w6 = left(w6 ^ w3 ^ w14 ^ w8)); + Round(c, d, e, a, b, f2(d, e, a), k2, w7 = left(w7 ^ w4 ^ w15 ^ w9)); + Round(b, c, d, e, a, f2(c, d, e), k2, w8 = left(w8 ^ w5 ^ w0 ^ w10)); + Round(a, b, c, d, e, f2(b, c, d), k2, w9 = left(w9 ^ w6 ^ w1 ^ w11)); + Round(e, a, b, c, d, f2(a, b, c), k2, w10 = left(w10 ^ w7 ^ w2 ^ w12)); + Round(d, e, a, b, c, f2(e, a, b), k2, w11 = left(w11 ^ w8 ^ w3 ^ w13)); + Round(c, d, e, a, b, f2(d, e, a), k2, w12 = left(w12 ^ w9 ^ w4 ^ w14)); + Round(b, c, d, e, a, f2(c, d, e), k2, w13 = left(w13 ^ w10 ^ w5 ^ w15)); + Round(a, b, c, d, e, f2(b, c, d), k2, w14 = left(w14 ^ w11 ^ w6 ^ w0)); + Round(e, a, b, c, d, f2(a, b, c), k2, w15 = left(w15 ^ w12 ^ w7 ^ w1)); + + Round(d, e, a, b, c, f2(e, a, b), k2, w0 = left(w0 ^ w13 ^ w8 ^ w2)); + Round(c, d, e, a, b, f2(d, e, a), k2, w1 = left(w1 ^ w14 ^ w9 ^ w3)); + Round(b, c, d, e, a, f2(c, d, e), k2, w2 = left(w2 ^ w15 ^ w10 ^ w4)); + Round(a, b, c, d, e, f2(b, c, d), k2, w3 = left(w3 ^ w0 ^ w11 ^ w5)); + Round(e, a, b, c, d, f2(a, b, c), k2, w4 = left(w4 ^ w1 ^ w12 ^ w6)); + Round(d, e, a, b, c, f2(e, a, b), k2, w5 = left(w5 ^ w2 ^ w13 ^ w7)); + Round(c, d, e, a, b, f2(d, e, a), k2, w6 = left(w6 ^ w3 ^ w14 ^ w8)); + Round(b, c, d, e, a, f2(c, d, e), k2, w7 = left(w7 ^ w4 ^ w15 ^ w9)); + Round(a, b, c, d, e, f3(b, c, d), k3, w8 = left(w8 ^ w5 ^ w0 ^ w10)); + Round(e, a, b, c, d, f3(a, b, c), k3, w9 = left(w9 ^ w6 ^ w1 ^ w11)); + Round(d, e, a, b, c, f3(e, a, b), k3, w10 = left(w10 ^ w7 ^ w2 ^ w12)); + Round(c, d, e, a, b, f3(d, e, a), k3, w11 = left(w11 ^ w8 ^ w3 ^ w13)); + Round(b, c, d, e, a, f3(c, d, e), k3, w12 = left(w12 ^ w9 ^ w4 ^ w14)); + Round(a, b, c, d, e, f3(b, c, d), k3, w13 = left(w13 ^ w10 ^ w5 ^ w15)); + Round(e, a, b, c, d, f3(a, b, c), k3, w14 = left(w14 ^ w11 ^ w6 ^ w0)); + Round(d, e, a, b, c, f3(e, a, b), k3, w15 = left(w15 ^ w12 ^ w7 ^ w1)); + + Round(c, d, e, a, b, f3(d, e, a), k3, w0 = left(w0 ^ w13 ^ w8 ^ w2)); + Round(b, c, d, e, a, f3(c, d, e), k3, w1 = left(w1 ^ w14 ^ w9 ^ w3)); + Round(a, b, c, d, e, f3(b, c, d), k3, w2 = left(w2 ^ w15 ^ w10 ^ w4)); + Round(e, a, b, c, d, f3(a, b, c), k3, w3 = left(w3 ^ w0 ^ w11 ^ w5)); + Round(d, e, a, b, c, f3(e, a, b), k3, w4 = left(w4 ^ w1 ^ w12 ^ w6)); + Round(c, d, e, a, b, f3(d, e, a), k3, w5 = left(w5 ^ w2 ^ w13 ^ w7)); + Round(b, c, d, e, a, f3(c, d, e), k3, w6 = left(w6 ^ w3 ^ w14 ^ w8)); + Round(a, b, c, d, e, f3(b, c, d), k3, w7 = left(w7 ^ w4 ^ w15 ^ w9)); + Round(e, a, b, c, d, f3(a, b, c), k3, w8 = left(w8 ^ w5 ^ w0 ^ w10)); + Round(d, e, a, b, c, f3(e, a, b), k3, w9 = left(w9 ^ w6 ^ w1 ^ w11)); + Round(c, d, e, a, b, f3(d, e, a), k3, w10 = left(w10 ^ w7 ^ w2 ^ w12)); + Round(b, c, d, e, a, f3(c, d, e), k3, w11 = left(w11 ^ w8 ^ w3 ^ w13)); + Round(a, b, c, d, e, f2(b, c, d), k4, w12 = left(w12 ^ w9 ^ w4 ^ w14)); + Round(e, a, b, c, d, f2(a, b, c), k4, w13 = left(w13 ^ w10 ^ w5 ^ w15)); + Round(d, e, a, b, c, f2(e, a, b), k4, w14 = left(w14 ^ w11 ^ w6 ^ w0)); + Round(c, d, e, a, b, f2(d, e, a), k4, w15 = left(w15 ^ w12 ^ w7 ^ w1)); + + Round(b, c, d, e, a, f2(c, d, e), k4, w0 = left(w0 ^ w13 ^ w8 ^ w2)); + Round(a, b, c, d, e, f2(b, c, d), k4, w1 = left(w1 ^ w14 ^ w9 ^ w3)); + Round(e, a, b, c, d, f2(a, b, c), k4, w2 = left(w2 ^ w15 ^ w10 ^ w4)); + Round(d, e, a, b, c, f2(e, a, b), k4, w3 = left(w3 ^ w0 ^ w11 ^ w5)); + Round(c, d, e, a, b, f2(d, e, a), k4, w4 = left(w4 ^ w1 ^ w12 ^ w6)); + Round(b, c, d, e, a, f2(c, d, e), k4, w5 = left(w5 ^ w2 ^ w13 ^ w7)); + Round(a, b, c, d, e, f2(b, c, d), k4, w6 = left(w6 ^ w3 ^ w14 ^ w8)); + Round(e, a, b, c, d, f2(a, b, c), k4, w7 = left(w7 ^ w4 ^ w15 ^ w9)); + Round(d, e, a, b, c, f2(e, a, b), k4, w8 = left(w8 ^ w5 ^ w0 ^ w10)); + Round(c, d, e, a, b, f2(d, e, a), k4, w9 = left(w9 ^ w6 ^ w1 ^ w11)); + Round(b, c, d, e, a, f2(c, d, e), k4, w10 = left(w10 ^ w7 ^ w2 ^ w12)); + Round(a, b, c, d, e, f2(b, c, d), k4, w11 = left(w11 ^ w8 ^ w3 ^ w13)); + Round(e, a, b, c, d, f2(a, b, c), k4, w12 = left(w12 ^ w9 ^ w4 ^ w14)); + Round(d, e, a, b, c, f2(e, a, b), k4, left(w13 ^ w10 ^ w5 ^ w15)); + Round(c, d, e, a, b, f2(d, e, a), k4, left(w14 ^ w11 ^ w6 ^ w0)); + Round(b, c, d, e, a, f2(c, d, e), k4, left(w15 ^ w12 ^ w7 ^ w1)); + + s[0] += a; + s[1] += b; + s[2] += c; + s[3] += d; + s[4] += e; +} + +} // namespace sha1 + +} // namespace + +////// SHA1 + +CSHA1::CSHA1() : bytes(0) +{ + sha1::Initialize(s); +} + +CSHA1& CSHA1::Write(const unsigned char* data, size_t len) +{ + const unsigned char* end = data + len; + size_t bufsize = bytes % 64; + if (bufsize && bufsize + len >= 64) { + // Fill the buffer, and process it. + memcpy(buf + bufsize, data, 64 - bufsize); + bytes += 64 - bufsize; + data += 64 - bufsize; + sha1::Transform(s, buf); + bufsize = 0; + } + while (end >= data + 64) { + // Process full chunks directly from the source. + sha1::Transform(s, data); + bytes += 64; + data += 64; + } + if (end > data) { + // Fill the buffer with what remains. + memcpy(buf + bufsize, data, end - data); + bytes += end - data; + } + return *this; +} + +void CSHA1::Finalize(unsigned char hash[OUTPUT_SIZE]) +{ + static const unsigned char pad[64] = {0x80}; + unsigned char sizedesc[8]; + WriteBE64(sizedesc, bytes << 3); + Write(pad, 1 + ((119 - (bytes % 64)) % 64)); + Write(sizedesc, 8); + WriteBE32(hash, s[0]); + WriteBE32(hash + 4, s[1]); + WriteBE32(hash + 8, s[2]); + WriteBE32(hash + 12, s[3]); + WriteBE32(hash + 16, s[4]); +} + +CSHA1& CSHA1::Reset() +{ + bytes = 0; + sha1::Initialize(s); + return *this; +} diff --git a/src/crypto/sha1.h b/src/crypto/sha1.h new file mode 100644 index 0000000..7b2a21b --- /dev/null +++ b/src/crypto/sha1.h @@ -0,0 +1,28 @@ +// Copyright (c) 2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_CRYPTO_SHA1_H +#define BITCOIN_CRYPTO_SHA1_H + +#include +#include + +/** A hasher class for SHA1. */ +class CSHA1 +{ +private: + uint32_t s[5]; + unsigned char buf[64]; + size_t bytes; + +public: + static const size_t OUTPUT_SIZE = 20; + + CSHA1(); + CSHA1& Write(const unsigned char* data, size_t len); + void Finalize(unsigned char hash[OUTPUT_SIZE]); + CSHA1& Reset(); +}; + +#endif // BITCOIN_CRYPTO_SHA1_H diff --git a/src/crypto/sha256.cpp b/src/crypto/sha256.cpp new file mode 100644 index 0000000..5b9f00a --- /dev/null +++ b/src/crypto/sha256.cpp @@ -0,0 +1,189 @@ +// Copyright (c) 2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "crypto/sha256.h" + +#include "crypto/common.h" + +#include + +// Internal implementation code. +namespace +{ +/// Internal SHA-256 implementation. +namespace sha256 +{ +uint32_t inline Ch(uint32_t x, uint32_t y, uint32_t z) { return z ^ (x & (y ^ z)); } +uint32_t inline Maj(uint32_t x, uint32_t y, uint32_t z) { return (x & y) | (z & (x | y)); } +uint32_t inline Sigma0(uint32_t x) { return (x >> 2 | x << 30) ^ (x >> 13 | x << 19) ^ (x >> 22 | x << 10); } +uint32_t inline Sigma1(uint32_t x) { return (x >> 6 | x << 26) ^ (x >> 11 | x << 21) ^ (x >> 25 | x << 7); } +uint32_t inline sigma0(uint32_t x) { return (x >> 7 | x << 25) ^ (x >> 18 | x << 14) ^ (x >> 3); } +uint32_t inline sigma1(uint32_t x) { return (x >> 17 | x << 15) ^ (x >> 19 | x << 13) ^ (x >> 10); } + +/** One round of SHA-256. */ +void inline Round(uint32_t a, uint32_t b, uint32_t c, uint32_t& d, uint32_t e, uint32_t f, uint32_t g, uint32_t& h, uint32_t k, uint32_t w) +{ + uint32_t t1 = h + Sigma1(e) + Ch(e, f, g) + k + w; + uint32_t t2 = Sigma0(a) + Maj(a, b, c); + d += t1; + h = t1 + t2; +} + +/** Initialize SHA-256 state. */ +void inline Initialize(uint32_t* s) +{ + s[0] = 0x6a09e667ul; + s[1] = 0xbb67ae85ul; + s[2] = 0x3c6ef372ul; + s[3] = 0xa54ff53aul; + s[4] = 0x510e527ful; + s[5] = 0x9b05688cul; + s[6] = 0x1f83d9abul; + s[7] = 0x5be0cd19ul; +} + +/** Perform one SHA-256 transformation, processing a 64-byte chunk. */ +void Transform(uint32_t* s, const unsigned char* chunk) +{ + uint32_t a = s[0], b = s[1], c = s[2], d = s[3], e = s[4], f = s[5], g = s[6], h = s[7]; + uint32_t w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15; + + Round(a, b, c, d, e, f, g, h, 0x428a2f98, w0 = ReadBE32(chunk + 0)); + Round(h, a, b, c, d, e, f, g, 0x71374491, w1 = ReadBE32(chunk + 4)); + Round(g, h, a, b, c, d, e, f, 0xb5c0fbcf, w2 = ReadBE32(chunk + 8)); + Round(f, g, h, a, b, c, d, e, 0xe9b5dba5, w3 = ReadBE32(chunk + 12)); + Round(e, f, g, h, a, b, c, d, 0x3956c25b, w4 = ReadBE32(chunk + 16)); + Round(d, e, f, g, h, a, b, c, 0x59f111f1, w5 = ReadBE32(chunk + 20)); + Round(c, d, e, f, g, h, a, b, 0x923f82a4, w6 = ReadBE32(chunk + 24)); + Round(b, c, d, e, f, g, h, a, 0xab1c5ed5, w7 = ReadBE32(chunk + 28)); + Round(a, b, c, d, e, f, g, h, 0xd807aa98, w8 = ReadBE32(chunk + 32)); + Round(h, a, b, c, d, e, f, g, 0x12835b01, w9 = ReadBE32(chunk + 36)); + Round(g, h, a, b, c, d, e, f, 0x243185be, w10 = ReadBE32(chunk + 40)); + Round(f, g, h, a, b, c, d, e, 0x550c7dc3, w11 = ReadBE32(chunk + 44)); + Round(e, f, g, h, a, b, c, d, 0x72be5d74, w12 = ReadBE32(chunk + 48)); + Round(d, e, f, g, h, a, b, c, 0x80deb1fe, w13 = ReadBE32(chunk + 52)); + Round(c, d, e, f, g, h, a, b, 0x9bdc06a7, w14 = ReadBE32(chunk + 56)); + Round(b, c, d, e, f, g, h, a, 0xc19bf174, w15 = ReadBE32(chunk + 60)); + + Round(a, b, c, d, e, f, g, h, 0xe49b69c1, w0 += sigma1(w14) + w9 + sigma0(w1)); + Round(h, a, b, c, d, e, f, g, 0xefbe4786, w1 += sigma1(w15) + w10 + sigma0(w2)); + Round(g, h, a, b, c, d, e, f, 0x0fc19dc6, w2 += sigma1(w0) + w11 + sigma0(w3)); + Round(f, g, h, a, b, c, d, e, 0x240ca1cc, w3 += sigma1(w1) + w12 + sigma0(w4)); + Round(e, f, g, h, a, b, c, d, 0x2de92c6f, w4 += sigma1(w2) + w13 + sigma0(w5)); + Round(d, e, f, g, h, a, b, c, 0x4a7484aa, w5 += sigma1(w3) + w14 + sigma0(w6)); + Round(c, d, e, f, g, h, a, b, 0x5cb0a9dc, w6 += sigma1(w4) + w15 + sigma0(w7)); + Round(b, c, d, e, f, g, h, a, 0x76f988da, w7 += sigma1(w5) + w0 + sigma0(w8)); + Round(a, b, c, d, e, f, g, h, 0x983e5152, w8 += sigma1(w6) + w1 + sigma0(w9)); + Round(h, a, b, c, d, e, f, g, 0xa831c66d, w9 += sigma1(w7) + w2 + sigma0(w10)); + Round(g, h, a, b, c, d, e, f, 0xb00327c8, w10 += sigma1(w8) + w3 + sigma0(w11)); + Round(f, g, h, a, b, c, d, e, 0xbf597fc7, w11 += sigma1(w9) + w4 + sigma0(w12)); + Round(e, f, g, h, a, b, c, d, 0xc6e00bf3, w12 += sigma1(w10) + w5 + sigma0(w13)); + Round(d, e, f, g, h, a, b, c, 0xd5a79147, w13 += sigma1(w11) + w6 + sigma0(w14)); + Round(c, d, e, f, g, h, a, b, 0x06ca6351, w14 += sigma1(w12) + w7 + sigma0(w15)); + Round(b, c, d, e, f, g, h, a, 0x14292967, w15 += sigma1(w13) + w8 + sigma0(w0)); + + Round(a, b, c, d, e, f, g, h, 0x27b70a85, w0 += sigma1(w14) + w9 + sigma0(w1)); + Round(h, a, b, c, d, e, f, g, 0x2e1b2138, w1 += sigma1(w15) + w10 + sigma0(w2)); + Round(g, h, a, b, c, d, e, f, 0x4d2c6dfc, w2 += sigma1(w0) + w11 + sigma0(w3)); + Round(f, g, h, a, b, c, d, e, 0x53380d13, w3 += sigma1(w1) + w12 + sigma0(w4)); + Round(e, f, g, h, a, b, c, d, 0x650a7354, w4 += sigma1(w2) + w13 + sigma0(w5)); + Round(d, e, f, g, h, a, b, c, 0x766a0abb, w5 += sigma1(w3) + w14 + sigma0(w6)); + Round(c, d, e, f, g, h, a, b, 0x81c2c92e, w6 += sigma1(w4) + w15 + sigma0(w7)); + Round(b, c, d, e, f, g, h, a, 0x92722c85, w7 += sigma1(w5) + w0 + sigma0(w8)); + Round(a, b, c, d, e, f, g, h, 0xa2bfe8a1, w8 += sigma1(w6) + w1 + sigma0(w9)); + Round(h, a, b, c, d, e, f, g, 0xa81a664b, w9 += sigma1(w7) + w2 + sigma0(w10)); + Round(g, h, a, b, c, d, e, f, 0xc24b8b70, w10 += sigma1(w8) + w3 + sigma0(w11)); + Round(f, g, h, a, b, c, d, e, 0xc76c51a3, w11 += sigma1(w9) + w4 + sigma0(w12)); + Round(e, f, g, h, a, b, c, d, 0xd192e819, w12 += sigma1(w10) + w5 + sigma0(w13)); + Round(d, e, f, g, h, a, b, c, 0xd6990624, w13 += sigma1(w11) + w6 + sigma0(w14)); + Round(c, d, e, f, g, h, a, b, 0xf40e3585, w14 += sigma1(w12) + w7 + sigma0(w15)); + Round(b, c, d, e, f, g, h, a, 0x106aa070, w15 += sigma1(w13) + w8 + sigma0(w0)); + + Round(a, b, c, d, e, f, g, h, 0x19a4c116, w0 += sigma1(w14) + w9 + sigma0(w1)); + Round(h, a, b, c, d, e, f, g, 0x1e376c08, w1 += sigma1(w15) + w10 + sigma0(w2)); + Round(g, h, a, b, c, d, e, f, 0x2748774c, w2 += sigma1(w0) + w11 + sigma0(w3)); + Round(f, g, h, a, b, c, d, e, 0x34b0bcb5, w3 += sigma1(w1) + w12 + sigma0(w4)); + Round(e, f, g, h, a, b, c, d, 0x391c0cb3, w4 += sigma1(w2) + w13 + sigma0(w5)); + Round(d, e, f, g, h, a, b, c, 0x4ed8aa4a, w5 += sigma1(w3) + w14 + sigma0(w6)); + Round(c, d, e, f, g, h, a, b, 0x5b9cca4f, w6 += sigma1(w4) + w15 + sigma0(w7)); + Round(b, c, d, e, f, g, h, a, 0x682e6ff3, w7 += sigma1(w5) + w0 + sigma0(w8)); + Round(a, b, c, d, e, f, g, h, 0x748f82ee, w8 += sigma1(w6) + w1 + sigma0(w9)); + Round(h, a, b, c, d, e, f, g, 0x78a5636f, w9 += sigma1(w7) + w2 + sigma0(w10)); + Round(g, h, a, b, c, d, e, f, 0x84c87814, w10 += sigma1(w8) + w3 + sigma0(w11)); + Round(f, g, h, a, b, c, d, e, 0x8cc70208, w11 += sigma1(w9) + w4 + sigma0(w12)); + Round(e, f, g, h, a, b, c, d, 0x90befffa, w12 += sigma1(w10) + w5 + sigma0(w13)); + Round(d, e, f, g, h, a, b, c, 0xa4506ceb, w13 += sigma1(w11) + w6 + sigma0(w14)); + Round(c, d, e, f, g, h, a, b, 0xbef9a3f7, w14 + sigma1(w12) + w7 + sigma0(w15)); + Round(b, c, d, e, f, g, h, a, 0xc67178f2, w15 + sigma1(w13) + w8 + sigma0(w0)); + + s[0] += a; + s[1] += b; + s[2] += c; + s[3] += d; + s[4] += e; + s[5] += f; + s[6] += g; + s[7] += h; +} + +} // namespace sha256 +} // namespace + + +////// SHA-256 + +CSHA256::CSHA256() : bytes(0) +{ + sha256::Initialize(s); +} + +CSHA256& CSHA256::Write(const unsigned char* data, size_t len) +{ + const unsigned char* end = data + len; + size_t bufsize = bytes % 64; + if (bufsize && bufsize + len >= 64) { + // Fill the buffer, and process it. + memcpy(buf + bufsize, data, 64 - bufsize); + bytes += 64 - bufsize; + data += 64 - bufsize; + sha256::Transform(s, buf); + bufsize = 0; + } + while (end >= data + 64) { + // Process full chunks directly from the source. + sha256::Transform(s, data); + bytes += 64; + data += 64; + } + if (end > data) { + // Fill the buffer with what remains. + memcpy(buf + bufsize, data, end - data); + bytes += end - data; + } + return *this; +} + +void CSHA256::Finalize(unsigned char hash[OUTPUT_SIZE]) +{ + static const unsigned char pad[64] = {0x80}; + unsigned char sizedesc[8]; + WriteBE64(sizedesc, bytes << 3); + Write(pad, 1 + ((119 - (bytes % 64)) % 64)); + Write(sizedesc, 8); + WriteBE32(hash, s[0]); + WriteBE32(hash + 4, s[1]); + WriteBE32(hash + 8, s[2]); + WriteBE32(hash + 12, s[3]); + WriteBE32(hash + 16, s[4]); + WriteBE32(hash + 20, s[5]); + WriteBE32(hash + 24, s[6]); + WriteBE32(hash + 28, s[7]); +} + +CSHA256& CSHA256::Reset() +{ + bytes = 0; + sha256::Initialize(s); + return *this; +} diff --git a/src/crypto/sha256.h b/src/crypto/sha256.h new file mode 100644 index 0000000..85cf337 --- /dev/null +++ b/src/crypto/sha256.h @@ -0,0 +1,28 @@ +// Copyright (c) 2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_CRYPTO_SHA256_H +#define BITCOIN_CRYPTO_SHA256_H + +#include +#include + +/** A hasher class for SHA-256. */ +class CSHA256 +{ +private: + uint32_t s[8]; + unsigned char buf[64]; + size_t bytes; + +public: + static const size_t OUTPUT_SIZE = 32; + + CSHA256(); + CSHA256& Write(const unsigned char* data, size_t len); + void Finalize(unsigned char hash[OUTPUT_SIZE]); + CSHA256& Reset(); +}; + +#endif // BITCOIN_CRYPTO_SHA256_H diff --git a/src/crypto/sha512.cpp b/src/crypto/sha512.cpp new file mode 100644 index 0000000..564127c --- /dev/null +++ b/src/crypto/sha512.cpp @@ -0,0 +1,207 @@ +// Copyright (c) 2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "crypto/sha512.h" + +#include "crypto/common.h" + +#include + +// Internal implementation code. +namespace +{ +/// Internal SHA-512 implementation. +namespace sha512 +{ +uint64_t inline Ch(uint64_t x, uint64_t y, uint64_t z) { return z ^ (x & (y ^ z)); } +uint64_t inline Maj(uint64_t x, uint64_t y, uint64_t z) { return (x & y) | (z & (x | y)); } +uint64_t inline Sigma0(uint64_t x) { return (x >> 28 | x << 36) ^ (x >> 34 | x << 30) ^ (x >> 39 | x << 25); } +uint64_t inline Sigma1(uint64_t x) { return (x >> 14 | x << 50) ^ (x >> 18 | x << 46) ^ (x >> 41 | x << 23); } +uint64_t inline sigma0(uint64_t x) { return (x >> 1 | x << 63) ^ (x >> 8 | x << 56) ^ (x >> 7); } +uint64_t inline sigma1(uint64_t x) { return (x >> 19 | x << 45) ^ (x >> 61 | x << 3) ^ (x >> 6); } + +/** One round of SHA-512. */ +void inline Round(uint64_t a, uint64_t b, uint64_t c, uint64_t& d, uint64_t e, uint64_t f, uint64_t g, uint64_t& h, uint64_t k, uint64_t w) +{ + uint64_t t1 = h + Sigma1(e) + Ch(e, f, g) + k + w; + uint64_t t2 = Sigma0(a) + Maj(a, b, c); + d += t1; + h = t1 + t2; +} + +/** Initialize SHA-256 state. */ +void inline Initialize(uint64_t* s) +{ + s[0] = 0x6a09e667f3bcc908ull; + s[1] = 0xbb67ae8584caa73bull; + s[2] = 0x3c6ef372fe94f82bull; + s[3] = 0xa54ff53a5f1d36f1ull; + s[4] = 0x510e527fade682d1ull; + s[5] = 0x9b05688c2b3e6c1full; + s[6] = 0x1f83d9abfb41bd6bull; + s[7] = 0x5be0cd19137e2179ull; +} + +/** Perform one SHA-512 transformation, processing a 128-byte chunk. */ +void Transform(uint64_t* s, const unsigned char* chunk) +{ + uint64_t a = s[0], b = s[1], c = s[2], d = s[3], e = s[4], f = s[5], g = s[6], h = s[7]; + uint64_t w0, w1, w2, w3, w4, w5, w6, w7, w8, w9, w10, w11, w12, w13, w14, w15; + + Round(a, b, c, d, e, f, g, h, 0x428a2f98d728ae22ull, w0 = ReadBE64(chunk + 0)); + Round(h, a, b, c, d, e, f, g, 0x7137449123ef65cdull, w1 = ReadBE64(chunk + 8)); + Round(g, h, a, b, c, d, e, f, 0xb5c0fbcfec4d3b2full, w2 = ReadBE64(chunk + 16)); + Round(f, g, h, a, b, c, d, e, 0xe9b5dba58189dbbcull, w3 = ReadBE64(chunk + 24)); + Round(e, f, g, h, a, b, c, d, 0x3956c25bf348b538ull, w4 = ReadBE64(chunk + 32)); + Round(d, e, f, g, h, a, b, c, 0x59f111f1b605d019ull, w5 = ReadBE64(chunk + 40)); + Round(c, d, e, f, g, h, a, b, 0x923f82a4af194f9bull, w6 = ReadBE64(chunk + 48)); + Round(b, c, d, e, f, g, h, a, 0xab1c5ed5da6d8118ull, w7 = ReadBE64(chunk + 56)); + Round(a, b, c, d, e, f, g, h, 0xd807aa98a3030242ull, w8 = ReadBE64(chunk + 64)); + Round(h, a, b, c, d, e, f, g, 0x12835b0145706fbeull, w9 = ReadBE64(chunk + 72)); + Round(g, h, a, b, c, d, e, f, 0x243185be4ee4b28cull, w10 = ReadBE64(chunk + 80)); + Round(f, g, h, a, b, c, d, e, 0x550c7dc3d5ffb4e2ull, w11 = ReadBE64(chunk + 88)); + Round(e, f, g, h, a, b, c, d, 0x72be5d74f27b896full, w12 = ReadBE64(chunk + 96)); + Round(d, e, f, g, h, a, b, c, 0x80deb1fe3b1696b1ull, w13 = ReadBE64(chunk + 104)); + Round(c, d, e, f, g, h, a, b, 0x9bdc06a725c71235ull, w14 = ReadBE64(chunk + 112)); + Round(b, c, d, e, f, g, h, a, 0xc19bf174cf692694ull, w15 = ReadBE64(chunk + 120)); + + Round(a, b, c, d, e, f, g, h, 0xe49b69c19ef14ad2ull, w0 += sigma1(w14) + w9 + sigma0(w1)); + Round(h, a, b, c, d, e, f, g, 0xefbe4786384f25e3ull, w1 += sigma1(w15) + w10 + sigma0(w2)); + Round(g, h, a, b, c, d, e, f, 0x0fc19dc68b8cd5b5ull, w2 += sigma1(w0) + w11 + sigma0(w3)); + Round(f, g, h, a, b, c, d, e, 0x240ca1cc77ac9c65ull, w3 += sigma1(w1) + w12 + sigma0(w4)); + Round(e, f, g, h, a, b, c, d, 0x2de92c6f592b0275ull, w4 += sigma1(w2) + w13 + sigma0(w5)); + Round(d, e, f, g, h, a, b, c, 0x4a7484aa6ea6e483ull, w5 += sigma1(w3) + w14 + sigma0(w6)); + Round(c, d, e, f, g, h, a, b, 0x5cb0a9dcbd41fbd4ull, w6 += sigma1(w4) + w15 + sigma0(w7)); + Round(b, c, d, e, f, g, h, a, 0x76f988da831153b5ull, w7 += sigma1(w5) + w0 + sigma0(w8)); + Round(a, b, c, d, e, f, g, h, 0x983e5152ee66dfabull, w8 += sigma1(w6) + w1 + sigma0(w9)); + Round(h, a, b, c, d, e, f, g, 0xa831c66d2db43210ull, w9 += sigma1(w7) + w2 + sigma0(w10)); + Round(g, h, a, b, c, d, e, f, 0xb00327c898fb213full, w10 += sigma1(w8) + w3 + sigma0(w11)); + Round(f, g, h, a, b, c, d, e, 0xbf597fc7beef0ee4ull, w11 += sigma1(w9) + w4 + sigma0(w12)); + Round(e, f, g, h, a, b, c, d, 0xc6e00bf33da88fc2ull, w12 += sigma1(w10) + w5 + sigma0(w13)); + Round(d, e, f, g, h, a, b, c, 0xd5a79147930aa725ull, w13 += sigma1(w11) + w6 + sigma0(w14)); + Round(c, d, e, f, g, h, a, b, 0x06ca6351e003826full, w14 += sigma1(w12) + w7 + sigma0(w15)); + Round(b, c, d, e, f, g, h, a, 0x142929670a0e6e70ull, w15 += sigma1(w13) + w8 + sigma0(w0)); + + Round(a, b, c, d, e, f, g, h, 0x27b70a8546d22ffcull, w0 += sigma1(w14) + w9 + sigma0(w1)); + Round(h, a, b, c, d, e, f, g, 0x2e1b21385c26c926ull, w1 += sigma1(w15) + w10 + sigma0(w2)); + Round(g, h, a, b, c, d, e, f, 0x4d2c6dfc5ac42aedull, w2 += sigma1(w0) + w11 + sigma0(w3)); + Round(f, g, h, a, b, c, d, e, 0x53380d139d95b3dfull, w3 += sigma1(w1) + w12 + sigma0(w4)); + Round(e, f, g, h, a, b, c, d, 0x650a73548baf63deull, w4 += sigma1(w2) + w13 + sigma0(w5)); + Round(d, e, f, g, h, a, b, c, 0x766a0abb3c77b2a8ull, w5 += sigma1(w3) + w14 + sigma0(w6)); + Round(c, d, e, f, g, h, a, b, 0x81c2c92e47edaee6ull, w6 += sigma1(w4) + w15 + sigma0(w7)); + Round(b, c, d, e, f, g, h, a, 0x92722c851482353bull, w7 += sigma1(w5) + w0 + sigma0(w8)); + Round(a, b, c, d, e, f, g, h, 0xa2bfe8a14cf10364ull, w8 += sigma1(w6) + w1 + sigma0(w9)); + Round(h, a, b, c, d, e, f, g, 0xa81a664bbc423001ull, w9 += sigma1(w7) + w2 + sigma0(w10)); + Round(g, h, a, b, c, d, e, f, 0xc24b8b70d0f89791ull, w10 += sigma1(w8) + w3 + sigma0(w11)); + Round(f, g, h, a, b, c, d, e, 0xc76c51a30654be30ull, w11 += sigma1(w9) + w4 + sigma0(w12)); + Round(e, f, g, h, a, b, c, d, 0xd192e819d6ef5218ull, w12 += sigma1(w10) + w5 + sigma0(w13)); + Round(d, e, f, g, h, a, b, c, 0xd69906245565a910ull, w13 += sigma1(w11) + w6 + sigma0(w14)); + Round(c, d, e, f, g, h, a, b, 0xf40e35855771202aull, w14 += sigma1(w12) + w7 + sigma0(w15)); + Round(b, c, d, e, f, g, h, a, 0x106aa07032bbd1b8ull, w15 += sigma1(w13) + w8 + sigma0(w0)); + + Round(a, b, c, d, e, f, g, h, 0x19a4c116b8d2d0c8ull, w0 += sigma1(w14) + w9 + sigma0(w1)); + Round(h, a, b, c, d, e, f, g, 0x1e376c085141ab53ull, w1 += sigma1(w15) + w10 + sigma0(w2)); + Round(g, h, a, b, c, d, e, f, 0x2748774cdf8eeb99ull, w2 += sigma1(w0) + w11 + sigma0(w3)); + Round(f, g, h, a, b, c, d, e, 0x34b0bcb5e19b48a8ull, w3 += sigma1(w1) + w12 + sigma0(w4)); + Round(e, f, g, h, a, b, c, d, 0x391c0cb3c5c95a63ull, w4 += sigma1(w2) + w13 + sigma0(w5)); + Round(d, e, f, g, h, a, b, c, 0x4ed8aa4ae3418acbull, w5 += sigma1(w3) + w14 + sigma0(w6)); + Round(c, d, e, f, g, h, a, b, 0x5b9cca4f7763e373ull, w6 += sigma1(w4) + w15 + sigma0(w7)); + Round(b, c, d, e, f, g, h, a, 0x682e6ff3d6b2b8a3ull, w7 += sigma1(w5) + w0 + sigma0(w8)); + Round(a, b, c, d, e, f, g, h, 0x748f82ee5defb2fcull, w8 += sigma1(w6) + w1 + sigma0(w9)); + Round(h, a, b, c, d, e, f, g, 0x78a5636f43172f60ull, w9 += sigma1(w7) + w2 + sigma0(w10)); + Round(g, h, a, b, c, d, e, f, 0x84c87814a1f0ab72ull, w10 += sigma1(w8) + w3 + sigma0(w11)); + Round(f, g, h, a, b, c, d, e, 0x8cc702081a6439ecull, w11 += sigma1(w9) + w4 + sigma0(w12)); + Round(e, f, g, h, a, b, c, d, 0x90befffa23631e28ull, w12 += sigma1(w10) + w5 + sigma0(w13)); + Round(d, e, f, g, h, a, b, c, 0xa4506cebde82bde9ull, w13 += sigma1(w11) + w6 + sigma0(w14)); + Round(c, d, e, f, g, h, a, b, 0xbef9a3f7b2c67915ull, w14 += sigma1(w12) + w7 + sigma0(w15)); + Round(b, c, d, e, f, g, h, a, 0xc67178f2e372532bull, w15 += sigma1(w13) + w8 + sigma0(w0)); + + Round(a, b, c, d, e, f, g, h, 0xca273eceea26619cull, w0 += sigma1(w14) + w9 + sigma0(w1)); + Round(h, a, b, c, d, e, f, g, 0xd186b8c721c0c207ull, w1 += sigma1(w15) + w10 + sigma0(w2)); + Round(g, h, a, b, c, d, e, f, 0xeada7dd6cde0eb1eull, w2 += sigma1(w0) + w11 + sigma0(w3)); + Round(f, g, h, a, b, c, d, e, 0xf57d4f7fee6ed178ull, w3 += sigma1(w1) + w12 + sigma0(w4)); + Round(e, f, g, h, a, b, c, d, 0x06f067aa72176fbaull, w4 += sigma1(w2) + w13 + sigma0(w5)); + Round(d, e, f, g, h, a, b, c, 0x0a637dc5a2c898a6ull, w5 += sigma1(w3) + w14 + sigma0(w6)); + Round(c, d, e, f, g, h, a, b, 0x113f9804bef90daeull, w6 += sigma1(w4) + w15 + sigma0(w7)); + Round(b, c, d, e, f, g, h, a, 0x1b710b35131c471bull, w7 += sigma1(w5) + w0 + sigma0(w8)); + Round(a, b, c, d, e, f, g, h, 0x28db77f523047d84ull, w8 += sigma1(w6) + w1 + sigma0(w9)); + Round(h, a, b, c, d, e, f, g, 0x32caab7b40c72493ull, w9 += sigma1(w7) + w2 + sigma0(w10)); + Round(g, h, a, b, c, d, e, f, 0x3c9ebe0a15c9bebcull, w10 += sigma1(w8) + w3 + sigma0(w11)); + Round(f, g, h, a, b, c, d, e, 0x431d67c49c100d4cull, w11 += sigma1(w9) + w4 + sigma0(w12)); + Round(e, f, g, h, a, b, c, d, 0x4cc5d4becb3e42b6ull, w12 += sigma1(w10) + w5 + sigma0(w13)); + Round(d, e, f, g, h, a, b, c, 0x597f299cfc657e2aull, w13 += sigma1(w11) + w6 + sigma0(w14)); + Round(c, d, e, f, g, h, a, b, 0x5fcb6fab3ad6faecull, w14 + sigma1(w12) + w7 + sigma0(w15)); + Round(b, c, d, e, f, g, h, a, 0x6c44198c4a475817ull, w15 + sigma1(w13) + w8 + sigma0(w0)); + + s[0] += a; + s[1] += b; + s[2] += c; + s[3] += d; + s[4] += e; + s[5] += f; + s[6] += g; + s[7] += h; +} + +} // namespace sha512 + +} // namespace + + +////// SHA-512 + +CSHA512::CSHA512() : bytes(0) +{ + sha512::Initialize(s); +} + +CSHA512& CSHA512::Write(const unsigned char* data, size_t len) +{ + const unsigned char* end = data + len; + size_t bufsize = bytes % 128; + if (bufsize && bufsize + len >= 128) { + // Fill the buffer, and process it. + memcpy(buf + bufsize, data, 128 - bufsize); + bytes += 128 - bufsize; + data += 128 - bufsize; + sha512::Transform(s, buf); + bufsize = 0; + } + while (end >= data + 128) { + // Process full chunks directly from the source. + sha512::Transform(s, data); + data += 128; + bytes += 128; + } + if (end > data) { + // Fill the buffer with what remains. + memcpy(buf + bufsize, data, end - data); + bytes += end - data; + } + return *this; +} + +void CSHA512::Finalize(unsigned char hash[OUTPUT_SIZE]) +{ + static const unsigned char pad[128] = {0x80}; + unsigned char sizedesc[16] = {0x00}; + WriteBE64(sizedesc + 8, bytes << 3); + Write(pad, 1 + ((239 - (bytes % 128)) % 128)); + Write(sizedesc, 16); + WriteBE64(hash, s[0]); + WriteBE64(hash + 8, s[1]); + WriteBE64(hash + 16, s[2]); + WriteBE64(hash + 24, s[3]); + WriteBE64(hash + 32, s[4]); + WriteBE64(hash + 40, s[5]); + WriteBE64(hash + 48, s[6]); + WriteBE64(hash + 56, s[7]); +} + +CSHA512& CSHA512::Reset() +{ + bytes = 0; + sha512::Initialize(s); + return *this; +} diff --git a/src/crypto/sha512.h b/src/crypto/sha512.h new file mode 100644 index 0000000..f1f17ca --- /dev/null +++ b/src/crypto/sha512.h @@ -0,0 +1,28 @@ +// Copyright (c) 2014 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_CRYPTO_SHA512_H +#define BITCOIN_CRYPTO_SHA512_H + +#include +#include + +/** A hasher class for SHA-512. */ +class CSHA512 +{ +private: + uint64_t s[8]; + unsigned char buf[128]; + size_t bytes; + +public: + static const size_t OUTPUT_SIZE = 64; + + CSHA512(); + CSHA512& Write(const unsigned char* data, size_t len); + void Finalize(unsigned char hash[OUTPUT_SIZE]); + CSHA512& Reset(); +}; + +#endif // BITCOIN_CRYPTO_SHA512_H diff --git a/src/darksend.cpp b/src/darksend.cpp new file mode 100644 index 0000000..ef5cf70 --- /dev/null +++ b/src/darksend.cpp @@ -0,0 +1,2227 @@ +// Copyright (c) 2014-2015 The Darkcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + + +#include "darksend.h" +#include "main.h" +#include "init.h" +//#include "script/sign.h" +#include "util.h" +#include "masternode.h" +#include "instantx.h" +#include "ui_interface.h" +//#include "random.h" + +#include + +#include +#include +#include +#include + +#include +#include + +using namespace std; +using namespace boost; + +CCriticalSection cs_darksend; + +/** The main object for accessing darksend */ +CDarkSendPool darkSendPool; +/** A helper object for signing messages from masternodes */ +CDarkSendSigner darkSendSigner; +/** The current darksends in progress on the network */ +std::vector vecDarksendQueue; +/** Keep track of the used masternodes */ +std::vector vecMasternodesUsed; +// keep track of the scanning errors I've seen +map mapDarksendBroadcastTxes; +// +CActiveMasternode activeMasternode; + +// count peers we've requested the list from +int RequestedMasterNodeList = 0; + +/* *** BEGIN DARKSEND MAGIC ********** + Copyright 2014, Darkcoin Developers + eduffield - evan@darkcoin.io +*/ + +void ProcessMessageDarksend(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) +{ + if(fLiteMode) return; //disable all darksend/masternode related functionality + + if (strCommand == "dsf") { //DarkSend Final tx + if (pfrom->nVersion < darkSendPool.MIN_PEER_PROTO_VERSION) { + return; + } + + if((CNetAddr)darkSendPool.submittedToMasternode != (CNetAddr)pfrom->addr){ + //LogPrintf("dsc - message doesn't match current masternode - %s != %s\n", darkSendPool.submittedToMasternode.ToString().c_str(), pfrom->addr.ToString().c_str()); + return; + } + + int sessionID; + CTransaction txNew; + vRecv >> sessionID >> txNew; + + if(darkSendPool.sessionID != sessionID){ + if (fDebug) LogPrintf("dsf - message doesn't match current darksend session %d %d\n", darkSendPool.sessionID, sessionID); + return; + } + + //check to see if input is spent already? (and probably not confirmed) + darkSendPool.SignFinalTransaction(txNew, pfrom); + } + + else if (strCommand == "dsc") { //DarkSend Complete + if (pfrom->nVersion < darkSendPool.MIN_PEER_PROTO_VERSION) { + return; + } + + if((CNetAddr)darkSendPool.submittedToMasternode != (CNetAddr)pfrom->addr){ + //LogPrintf("dsc - message doesn't match current masternode - %s != %s\n", darkSendPool.submittedToMasternode.ToString().c_str(), pfrom->addr.ToString().c_str()); + return; + } + + int sessionID; + bool error; + std::string lastMessage; + vRecv >> sessionID >> error >> lastMessage; + + if(darkSendPool.sessionID != sessionID){ + if (fDebug) LogPrintf("dsc - message doesn't match current darksend session %d %d\n", darkSendPool.sessionID, sessionID); + return; + } + + darkSendPool.CompletedTransaction(error, lastMessage); + } + + else if (strCommand == "dsa") { //DarkSend Acceptable + + if (pfrom->nVersion < darkSendPool.MIN_PEER_PROTO_VERSION) { + std::string strError = _("Incompatible version."); + LogPrintf("dsa -- incompatible version! \n"); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, strError); + + return; + } + + if(!fMasterNode){ + std::string strError = _("This is not a masternode."); + LogPrintf("dsa -- not a masternode! \n"); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, strError); + + return; + } + + int nDenom; + CTransaction txCollateral; + vRecv >> nDenom >> txCollateral; + + std::string error = ""; + int mn = GetMasternodeByVin(activeMasternode.vin); + if(mn == -1){ + std::string strError = _("Not in the masternode list."); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, strError); + return; + } + + if(darkSendPool.sessionUsers == 0) { + if(vecMasternodes[mn].nLastDsq != 0 && + vecMasternodes[mn].nLastDsq + CountMasternodesAboveProtocol(darkSendPool.MIN_PEER_PROTO_VERSION)/5 > darkSendPool.nDsqCount){ + //LogPrintf("dsa -- last dsq too recent, must wait. %s \n", vecMasternodes[mn].addr.ToString().c_str()); + std::string strError = _("Last Darksend was too recent."); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, strError); + return; + } + } + + if(!darkSendPool.IsCompatibleWithSession(nDenom, txCollateral, error)) + { + LogPrintf("dsa -- not compatible with existing transactions! \n"); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, error); + return; + } else { + LogPrintf("dsa -- is compatible, please submit! \n"); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_ACCEPTED, error); + return; + } + } else if (strCommand == "dsq") { //DarkSend Queue + + if (pfrom->nVersion < darkSendPool.MIN_PEER_PROTO_VERSION) { + return; + } + + CDarksendQueue dsq; + vRecv >> dsq; + + + CService addr; + if(!dsq.GetAddress(addr)) return; + if(!dsq.CheckSignature()) return; + + if(dsq.IsExpired()) return; + + int mn = GetMasternodeByVin(dsq.vin); + if(mn == -1) return; + + // if the queue is ready, submit if we can + if(dsq.ready) { + if((CNetAddr)darkSendPool.submittedToMasternode != (CNetAddr)addr){ + LogPrintf("dsq - message doesn't match current masternode - %s != %s\n", darkSendPool.submittedToMasternode.ToString().c_str(), pfrom->addr.ToString().c_str()); + return; + } + + if (fDebug) LogPrintf("darksend queue is ready - %s\n", addr.ToString().c_str()); + darkSendPool.PrepareDarksendDenominate(); + } else { + BOOST_FOREACH(CDarksendQueue q, vecDarksendQueue){ + if(q.vin == dsq.vin) return; + } + + if(fDebug) LogPrintf("dsq last %d last2 %d count %d\n", vecMasternodes[mn].nLastDsq, vecMasternodes[mn].nLastDsq + (int)vecMasternodes.size()/5, darkSendPool.nDsqCount); + //don't allow a few nodes to dominate the queuing process + if(vecMasternodes[mn].nLastDsq != 0 && + vecMasternodes[mn].nLastDsq + CountMasternodesAboveProtocol(darkSendPool.MIN_PEER_PROTO_VERSION)/5 > darkSendPool.nDsqCount){ + if(fDebug) LogPrintf("dsq -- masternode sending too many dsq messages. %s \n", vecMasternodes[mn].addr.ToString().c_str()); + return; + } + darkSendPool.nDsqCount++; + vecMasternodes[mn].nLastDsq = darkSendPool.nDsqCount; + vecMasternodes[mn].allowFreeTx = true; + + if(fDebug) LogPrintf("dsq - new darksend queue object - %s\n", addr.ToString().c_str()); + vecDarksendQueue.push_back(dsq); + dsq.Relay(); + dsq.time = GetTime(); + } + + } else if (strCommand == "dsi") { //DarkSend vIn + std::string error = ""; + if (pfrom->nVersion < darkSendPool.MIN_PEER_PROTO_VERSION) { + LogPrintf("dsi -- incompatible version! \n"); + error = _("Incompatible version."); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, error); + + return; + } + + if(!fMasterNode){ + LogPrintf("dsi -- not a masternode! \n"); + error = _("This is not a masternode."); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, error); + + return; + } + + std::vector in; + int64_t nAmount; + CTransaction txCollateral; + std::vector out; + vRecv >> in >> nAmount >> txCollateral >> out; + + //do we have enough users in the current session? + if(!darkSendPool.IsSessionReady()){ + LogPrintf("dsi -- session not complete! \n"); + error = _("Session not complete!"); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, error); + return; + } + + //do we have the same denominations as the current session? + if(!darkSendPool.IsCompatibleWithEntries(out)) + { + LogPrintf("dsi -- not compatible with existing transactions! \n"); + error = _("Not compatible with existing transactions."); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, error); + return; + } + + //check it like a transaction + { + int64_t nValueIn = 0; + int64_t nValueOut = 0; + bool missingTx = false; + + CValidationState state; + CTransaction tx; + + BOOST_FOREACH(CTxOut o, out){ + nValueOut += o.nValue; + tx.vout.push_back(o); + + if(o.scriptPubKey.size() != 25){ + LogPrintf("dsi - non-standard pubkey detected! %s\n", o.scriptPubKey.ToString().c_str()); + error = _("Non-standard public key detected."); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, error); + return; + } + if(!o.scriptPubKey.IsNormalPaymentScript()){ + LogPrintf("dsi - invalid script! %s\n", o.scriptPubKey.ToString().c_str()); + error = _("Invalid script detected."); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, error); + return; + } + } + + BOOST_FOREACH(const CTxIn i, in){ + tx.vin.push_back(i); + + if(fDebug) LogPrintf("dsi -- tx in %s\n", i.ToString().c_str()); + + CTransaction tx2; + uint256 hash; + //if(GetTransaction(i.prevout.hash, tx2, hash, true)){ + if(GetTransaction(i.prevout.hash, tx2, hash)){ + if(tx2.vout.size() > i.prevout.n) { + nValueIn += tx2.vout[i.prevout.n].nValue; + } + } else{ + missingTx = true; + } + } + + if (nValueIn > DARKSEND_POOL_MAX) { + LogPrintf("dsi -- more than darksend pool max! %s\n", tx.ToString().c_str()); + error = _("Value more than Darksend pool maximum allows."); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, error); + return; + } + + if(!missingTx){ + if (nValueIn-nValueOut > nValueIn*.01) { + LogPrintf("dsi -- fees are too high! %s\n", tx.ToString().c_str()); + error = _("Transaction fees are too high."); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, error); + return; + } + } else { + LogPrintf("dsi -- missing input tx! %s\n", tx.ToString().c_str()); + error = _("Missing input transaction information."); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, error); + return; + } + + //if(!AcceptableInputs(mempool, state, tx)){ + bool* pfMissingInputs; + if(!AcceptableInputs(mempool, tx, false, pfMissingInputs)){ + LogPrintf("dsi -- transaction not valid! \n"); + error = _("Transaction not valid."); + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, error); + return; + } + } + + if(darkSendPool.AddEntry(in, nAmount, txCollateral, out, error)){ + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_ACCEPTED, error); + darkSendPool.Check(); + + RelayDarkSendStatus(darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_RESET); + } else { + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_REJECTED, error); + } + } + + else if (strCommand == "dssub") { //DarkSend Subscribe To + if (pfrom->nVersion < darkSendPool.MIN_PEER_PROTO_VERSION) { + return; + } + + if(!fMasterNode) return; + + std::string error = ""; + pfrom->PushMessage("dssu", darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_RESET, error); + return; + } + + else if (strCommand == "dssu") { //DarkSend status update + + if (pfrom->nVersion < darkSendPool.MIN_PEER_PROTO_VERSION) { + return; + } + + if((CNetAddr)darkSendPool.submittedToMasternode != (CNetAddr)pfrom->addr){ + //LogPrintf("dssu - message doesn't match current masternode - %s != %s\n", darkSendPool.submittedToMasternode.ToString().c_str(), pfrom->addr.ToString().c_str()); + return; + } + + int sessionID; + int state; + int entriesCount; + int accepted; + std::string error; + vRecv >> sessionID >> state >> entriesCount >> accepted >> error; + + if(fDebug) LogPrintf("dssu - state: %i entriesCount: %i accepted: %i error: %s \n", state, entriesCount, accepted, error.c_str()); + + if((accepted != 1 && accepted != 0) && darkSendPool.sessionID != sessionID){ + LogPrintf("dssu - message doesn't match current darksend session %d %d\n", darkSendPool.sessionID, sessionID); + return; + } + + darkSendPool.StatusUpdate(state, entriesCount, accepted, error, sessionID); + + } + + else if (strCommand == "dss") { //DarkSend Sign Final Tx + if (pfrom->nVersion < darkSendPool.MIN_PEER_PROTO_VERSION) { + return; + } + + vector sigs; + vRecv >> sigs; + + bool success = false; + int count = 0; + + LogPrintf(" -- sigs count %d %d\n", (int)sigs.size(), count); + + BOOST_FOREACH(const CTxIn item, sigs) + { + if(darkSendPool.AddScriptSig(item)) success = true; + if(fDebug) LogPrintf(" -- sigs count %d %d\n", (int)sigs.size(), count); + count++; + } + + if(success){ + darkSendPool.Check(); + RelayDarkSendStatus(darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_RESET); + } + } + +} + +int randomizeList (int i) { return std::rand()%i;} + +// Recursively determine the rounds of a given input (How deep is the darksend chain for a given input) +int GetInputDarksendRounds(CTxIn in, int rounds) +{ + if(rounds >= 17) return rounds; + + std::string padding = ""; + padding.insert(0, ((rounds+1)*5)+3, ' '); + + CWalletTx tx; + if(pwalletMain->GetTransaction(in.prevout.hash,tx)) + { + // bounds check + if(in.prevout.n >= tx.vout.size()) return -4; + + if(tx.vout[in.prevout.n].nValue == DARKSEND_FEE) return -3; + + //make sure the final output is non-denominate + if(rounds == 0 && !pwalletMain->IsDenominatedAmount(tx.vout[in.prevout.n].nValue)) return -2; //NOT DENOM + + bool found = false; + BOOST_FOREACH(CTxOut out, tx.vout) + { + found = pwalletMain->IsDenominatedAmount(out.nValue); + if(found) break; // no need to loop more + } + if(!found) return rounds - 1; //NOT FOUND, "-1" because of the pre-mixing creation of denominated amounts + + // find my vin and look that up + BOOST_FOREACH(CTxIn in2, tx.vin) + { + if(pwalletMain->IsMine(in2)) + { + //LogPrintf("rounds :: %s %s %d NEXT\n", padding.c_str(), in.ToString().c_str(), rounds); + int n = GetInputDarksendRounds(in2, rounds+1); + if(n != -3) return n; + } + } + } + + return rounds-1; +} + +void CDarkSendPool::Reset(){ + cachedLastSuccess = 0; + vecMasternodesUsed.clear(); + UnlockCoins(); + SetNull(); +} + +void CDarkSendPool::SetNull(bool clearEverything){ + finalTransaction.vin.clear(); + finalTransaction.vout.clear(); + + entries.clear(); + + state = POOL_STATUS_ACCEPTING_ENTRIES; + + lastTimeChanged = GetTimeMillis(); + + entriesCount = 0; + lastEntryAccepted = 0; + countEntriesAccepted = 0; + lastNewBlock = 0; + + sessionUsers = 0; + sessionDenom = 0; + sessionFoundMasternode = false; + vecSessionCollateral.clear(); + txCollateral = CTransaction(); + + if(clearEverything){ + myEntries.clear(); + + if(fMasterNode){ + sessionID = 1 + (rand() % 999999); + } else { + sessionID = 0; + } + } + + // -- seed random number generator (used for ordering output lists) + unsigned int seed = 0; + GetRandBytes((unsigned char*)&seed, sizeof(seed)); + std::srand(seed); +} + +bool CDarkSendPool::SetCollateralAddress(std::string strAddress){ + CBitcoinAddress address; + if (!address.SetString(strAddress)) + { + LogPrintf("CDarkSendPool::SetCollateralAddress - Invalid DarkSend collateral address\n"); + return false; + } + collateralPubKey= GetScriptForDestination(address.Get()); + return true; +} + +// +// Unlock coins after Darksend fails or succeeds +// +void CDarkSendPool::UnlockCoins(){ + BOOST_FOREACH(CTxIn v, lockedCoins) + pwalletMain->UnlockCoin(v.prevout); + + lockedCoins.clear(); +} + +// +// Check the Darksend progress and send client updates if a masternode +// +void CDarkSendPool::Check() +{ + if(fDebug) LogPrintf("CDarkSendPool::Check()\n"); + if(fDebug) LogPrintf("CDarkSendPool::Check() - entries count %lu\n", entries.size()); + + // If entries is full, then move on to the next phase + if(state == POOL_STATUS_ACCEPTING_ENTRIES && (int)entries.size() >= GetMaxPoolTransactions()) + { + if(fDebug) LogPrintf("CDarkSendPool::Check() -- ACCEPTING OUTPUTS\n"); + UpdateState(POOL_STATUS_FINALIZE_TRANSACTION); + } + + // create the finalized transaction for distribution to the clients + if(state == POOL_STATUS_FINALIZE_TRANSACTION && finalTransaction.vin.empty() && finalTransaction.vout.empty()) { + if(fDebug) LogPrintf("CDarkSendPool::Check() -- FINALIZE TRANSACTIONS\n"); + UpdateState(POOL_STATUS_SIGNING); + + if (fMasterNode) { + // make our new transaction + CTransaction txNew; + for(unsigned int i = 0; i < entries.size(); i++){ + BOOST_FOREACH(const CTxOut v, entries[i].vout) + txNew.vout.push_back(v); + + BOOST_FOREACH(const CDarkSendEntryVin s, entries[i].sev) + txNew.vin.push_back(s.vin); + } + // shuffle the outputs for improved anonymity + std::random_shuffle ( txNew.vout.begin(), txNew.vout.end(), randomizeList); + + if(fDebug) LogPrintf("Transaction 1: %s\n", txNew.ToString().c_str()); + + SignFinalTransaction(txNew, NULL); + + // request signatures from clients + RelayDarkSendFinalTransaction(sessionID, txNew); + } + } + + // collect signatures from clients + + // If we have all of the signatures, try to compile the transaction + if(state == POOL_STATUS_SIGNING && SignaturesComplete()) { + if(fDebug) LogPrintf("CDarkSendPool::Check() -- SIGNING\n"); + UpdateState(POOL_STATUS_TRANSMISSION); + + CWalletTx txNew = CWalletTx(pwalletMain, finalTransaction); + + LOCK2(cs_main, pwalletMain->cs_wallet); + { + if (fMasterNode) { //only the main node is master atm + if(fDebug) LogPrintf("Transaction 2: %s\n", txNew.ToString().c_str()); + + // See if the transaction is valid + if (!txNew.AcceptToMemoryPool(true)) + { + LogPrintf("CDarkSendPool::Check() - CommitTransaction : Error: Transaction not valid\n"); + SetNull(); + pwalletMain->Lock(); + + // not much we can do in this case + UpdateState(POOL_STATUS_ACCEPTING_ENTRIES); + RelayDarkSendCompletedTransaction(sessionID, true, "Transaction not valid, please try again"); + return; + } + + LogPrintf("CDarkSendPool::Check() -- IS MASTER -- TRANSMITTING DARKSEND\n"); + + // sign a message + + int64_t sigTime = GetAdjustedTime(); + std::string strMessage = txNew.GetHash().ToString() + boost::lexical_cast(sigTime); + std::string strError = ""; + std::vector vchSig; + CKey key2; + CPubKey pubkey2; + + if(!darkSendSigner.SetKey(strMasterNodePrivKey, strError, key2, pubkey2)) + { + LogPrintf("CDarkSendPool::Check() - ERROR: Invalid masternodeprivkey: '%s'\n", strError.c_str()); + return; + } + + if(!darkSendSigner.SignMessage(strMessage, strError, vchSig, key2)) { + LogPrintf("CDarkSendPool::Check() - Sign message failed\n"); + return; + } + + if(!darkSendSigner.VerifyMessage(pubkey2, vchSig, strMessage, strError)) { + LogPrintf("CDarkSendPool::Check() - Verify message failed\n"); + return; + } + + if(!mapDarksendBroadcastTxes.count(txNew.GetHash())){ + CDarksendBroadcastTx dstx; + dstx.tx = txNew; + dstx.vin = activeMasternode.vin; + dstx.vchSig = vchSig; + dstx.sigTime = sigTime; + + mapDarksendBroadcastTxes.insert(make_pair(txNew.GetHash(), dstx)); + } + + // Broadcast the transaction to the network + txNew.fTimeReceivedIsTxTime = true; + txNew.RelayWalletTransaction(); + + // Tell the clients it was successful + RelayDarkSendCompletedTransaction(sessionID, false, _("Transaction created successfully.")); + + // Randomly charge clients + ChargeRandomFees(); + } + } + } + + // move on to next phase, allow 3 seconds incase the masternode wants to send us anything else + if((state == POOL_STATUS_TRANSMISSION && fMasterNode) || (state == POOL_STATUS_SIGNING && completedTransaction) ) { + if(fDebug) LogPrintf("CDarkSendPool::Check() -- COMPLETED -- RESETTING \n"); + SetNull(true); + UnlockCoins(); + if(fMasterNode) RelayDarkSendStatus(darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_RESET); + pwalletMain->Lock(); + } + + // reset if we're here for 10 seconds + if((state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) && GetTimeMillis()-lastTimeChanged >= 10000) { + if(fDebug) LogPrintf("CDarkSendPool::Check() -- RESETTING MESSAGE \n"); + SetNull(true); + if(fMasterNode) RelayDarkSendStatus(darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_RESET); + UnlockCoins(); + } +} + +// +// Charge clients a fee if they're abusive +// +// Why bother? Darksend uses collateral to ensure abuse to the process is kept to a minimum. +// The submission and signing stages in darksend are completely separate. In the cases where +// a client submits a transaction then refused to sign, there must be a cost. Otherwise they +// would be able to do this over and over again and bring the mixing to a hault. +// +// How does this work? Messages to masternodes come in via "dsi", these require a valid collateral +// transaction for the client to be able to enter the pool. This transaction is kept by the masternode +// until the transaction is either complete or fails. +// +void CDarkSendPool::ChargeFees(){ + if(fMasterNode) { + //we don't need to charge collateral for every offence. + int offences = 0; + int r = rand()%100; + if(r > 33) return; + + if(state == POOL_STATUS_ACCEPTING_ENTRIES){ + BOOST_FOREACH(const CTransaction& txCollateral, vecSessionCollateral) { + bool found = false; + BOOST_FOREACH(const CDarkSendEntry& v, entries) { + if(v.collateral == txCollateral) { + found = true; + } + } + + // This queue entry didn't send us the promised transaction + if(!found){ + LogPrintf("CDarkSendPool::ChargeFees -- found uncooperative node (didn't send transaction). Found offence.\n"); + offences++; + } + } + } + + if(state == POOL_STATUS_SIGNING) { + // who didn't sign? + BOOST_FOREACH(const CDarkSendEntry v, entries) { + BOOST_FOREACH(const CDarkSendEntryVin s, v.sev) { + if(!s.isSigSet){ + LogPrintf("CDarkSendPool::ChargeFees -- found uncooperative node (didn't sign). Found offence\n"); + offences++; + } + } + } + } + + r = rand()%100; + int target = 0; + + //mostly offending? + if(offences >= POOL_MAX_TRANSACTIONS-1 && r > 33) return; + + //everyone is an offender? That's not right + if(offences >= POOL_MAX_TRANSACTIONS) return; + + //charge one of the offenders randomly + if(offences > 1) target = 50; + + //pick random client to charge + r = rand()%100; + + if(state == POOL_STATUS_ACCEPTING_ENTRIES){ + BOOST_FOREACH(const CTransaction& txCollateral, vecSessionCollateral) { + bool found = false; + BOOST_FOREACH(const CDarkSendEntry& v, entries) { + if(v.collateral == txCollateral) { + found = true; + } + } + + // This queue entry didn't send us the promised transaction + if(!found && r > target){ + LogPrintf("CDarkSendPool::ChargeFees -- found uncooperative node (didn't send transaction). charging fees.\n"); + + CWalletTx wtxCollateral = CWalletTx(pwalletMain, txCollateral); + + // Broadcast + if (!wtxCollateral.AcceptToMemoryPool(true)) + { + // This must not fail. The transaction has already been signed and recorded. + LogPrintf("CDarkSendPool::ChargeFees() : Error: Transaction not valid"); + } + wtxCollateral.RelayWalletTransaction(); + return; + } + } + } + + if(state == POOL_STATUS_SIGNING) { + // who didn't sign? + BOOST_FOREACH(const CDarkSendEntry v, entries) { + BOOST_FOREACH(const CDarkSendEntryVin s, v.sev) { + if(!s.isSigSet && r > target){ + LogPrintf("CDarkSendPool::ChargeFees -- found uncooperative node (didn't sign). charging fees.\n"); + + CWalletTx wtxCollateral = CWalletTx(pwalletMain, v.collateral); + + // Broadcast + if (!wtxCollateral.AcceptToMemoryPool(true)) + { + // This must not fail. The transaction has already been signed and recorded. + LogPrintf("CDarkSendPool::ChargeFees() : Error: Transaction not valid"); + } + wtxCollateral.RelayWalletTransaction(); + return; + } + } + } + } + } +} + +// charge the collateral randomly +// - Darksend is completely free, to pay miners we randomly pay the collateral of users. +void CDarkSendPool::ChargeRandomFees(){ + if(fMasterNode) { + int i = 0; + + BOOST_FOREACH(const CTransaction& txCollateral, vecSessionCollateral) { + int r = rand()%1000; + + /* + Collateral Fee Charges: + + Being that DarkSend has "no fees" we need to have some kind of cost associated + with using it to stop abuse. Otherwise it could serve as an attack vector and + allow endless transaction that would bloat Genius and make it unusable. To + stop these kinds of attacks 1 in 50 successful transactions are charged. This + adds up to a cost of 0.002GENIUS per transaction on average. + */ + if(r <= 20) + { + LogPrintf("CDarkSendPool::ChargeRandomFees -- charging random fees. %u\n", i); + + CWalletTx wtxCollateral = CWalletTx(pwalletMain, txCollateral); + + // Broadcast + if (!wtxCollateral.AcceptToMemoryPool(true)) + { + // This must not fail. The transaction has already been signed and recorded. + LogPrintf("CDarkSendPool::ChargeRandomFees() : Error: Transaction not valid"); + } + wtxCollateral.RelayWalletTransaction(); + } + } + } +} + +// +// Check for various timeouts (queue objects, darksend, etc) +// +void CDarkSendPool::CheckTimeout(){ + if(!fEnableDarksend && !fMasterNode) return; + + // catching hanging sessions + if(!fMasterNode) { + if(state == POOL_STATUS_TRANSMISSION) { + if(fDebug) LogPrintf("CDarkSendPool::CheckTimeout() -- Session complete -- Running Check()\n"); + Check(); + } + } + + // check darksend queue objects for timeouts + int c = 0; + vector::iterator it; + for(it=vecDarksendQueue.begin();it *vec = &myEntries; + if(fMasterNode) vec = &entries; + + // check for a timeout and reset if needed + vector::iterator it2; + for(it2=vec->begin();it2end();it2++){ + if((*it2).IsExpired()){ + if(fDebug) LogPrintf("CDarkSendPool::CheckTimeout() : Removing expired entry - %d\n", c); + vec->erase(it2); + if(entries.size() == 0 && myEntries.size() == 0){ + SetNull(true); + UnlockCoins(); + } + if(fMasterNode){ + RelayDarkSendStatus(darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_RESET); + } + break; + } + c++; + } + + if(GetTimeMillis()-lastTimeChanged >= (DARKSEND_QUEUE_TIMEOUT*1000)+addLagTime){ + lastTimeChanged = GetTimeMillis(); + + ChargeFees(); + // reset session information for the queue query stage (before entering a masternode, clients will send a queue request to make sure they're compatible denomination wise) + sessionUsers = 0; + sessionDenom = 0; + sessionFoundMasternode = false; + vecSessionCollateral.clear(); + + UpdateState(POOL_STATUS_ACCEPTING_ENTRIES); + } + } else if(GetTimeMillis()-lastTimeChanged >= (DARKSEND_QUEUE_TIMEOUT*1000)+addLagTime){ + if(fDebug) LogPrintf("CDarkSendPool::CheckTimeout() -- Session timed out (30s) -- resetting\n"); + SetNull(); + UnlockCoins(); + + UpdateState(POOL_STATUS_ERROR); + lastMessage = _("Session timed out (30 seconds), please resubmit."); + } + + if(state == POOL_STATUS_SIGNING && GetTimeMillis()-lastTimeChanged >= (DARKSEND_SIGNING_TIMEOUT*1000)+addLagTime ) { + if(fDebug) LogPrintf("CDarkSendPool::CheckTimeout() -- Session timed out -- restting\n"); + ChargeFees(); + SetNull(); + UnlockCoins(); + //add my transactions to the new session + + UpdateState(POOL_STATUS_ERROR); + lastMessage = _("Signing timed out, please resubmit."); + } +} + +// check to see if the signature is valid +bool CDarkSendPool::SignatureValid(const CScript& newSig, const CTxIn& newVin){ + CTransaction txNew; + txNew.vin.clear(); + txNew.vout.clear(); + + int found = -1; + CScript sigPubKey = CScript(); + unsigned int i = 0; + + BOOST_FOREACH(CDarkSendEntry e, entries) { + BOOST_FOREACH(const CTxOut out, e.vout) + txNew.vout.push_back(out); + + BOOST_FOREACH(const CDarkSendEntryVin s, e.sev){ + txNew.vin.push_back(s.vin); + + if(s.vin == newVin){ + found = i; + sigPubKey = s.vin.prevPubKey; + } + i++; + } + } + + if(found >= 0){ //might have to do this one input at a time? + int n = found; + txNew.vin[n].scriptSig = newSig; + if(fDebug) LogPrintf("CDarkSendPool::SignatureValid() - Sign with sig %s\n", newSig.ToString().substr(0,24).c_str()); + if (!VerifyScript(txNew.vin[n].scriptSig, sigPubKey, SCRIPT_VERIFY_P2SH | SCRIPT_VERIFY_STRICTENC, SignatureChecker(txNew, i))){ + if(fDebug) LogPrintf("CDarkSendPool::SignatureValid() - Signing - Error signing input %u\n", n); + return false; + } + } + + if(fDebug) LogPrintf("CDarkSendPool::SignatureValid() - Signing - Succesfully signed input\n"); + return true; +} + +// check to make sure the collateral provided by the client is valid +bool CDarkSendPool::IsCollateralValid(const CTransaction& txCollateral){ + if(txCollateral.vout.size() < 1) return false; + if(txCollateral.nLockTime != 0) return false; + + int64_t nValueIn = 0; + int64_t nValueOut = 0; + bool missingTx = false; + + BOOST_FOREACH(const CTxOut o, txCollateral.vout){ + nValueOut += o.nValue; + + if(!o.scriptPubKey.IsNormalPaymentScript()){ + LogPrintf ("CDarkSendPool::IsCollateralValid - Invalid Script %s\n", txCollateral.ToString().c_str()); + return false; + } + } + + BOOST_FOREACH(const CTxIn i, txCollateral.vin){ + CTransaction tx2; + uint256 hash; + //if(GetTransaction(i.prevout.hash, tx2, hash, true)){ + if(GetTransaction(i.prevout.hash, tx2, hash)){ + if(tx2.vout.size() > i.prevout.n) { + nValueIn += tx2.vout[i.prevout.n].nValue; + } + } else{ + missingTx = true; + } + } + + if(missingTx){ + if(fDebug) LogPrintf ("CDarkSendPool::IsCollateralValid - Unknown inputs in collateral transaction - %s\n", txCollateral.ToString().c_str()); + return false; + } + + //collateral transactions are required to pay out DARKSEND_COLLATERAL as a fee to the miners + if(nValueIn-nValueOut < DARKSEND_COLLATERAL) { + if(fDebug) LogPrintf ("CDarkSendPool::IsCollateralValid - did not include enough fees in transaction %d\n%s\n", nValueOut-nValueIn, txCollateral.ToString().c_str()); + return false; + } + + if(fDebug) LogPrintf("CDarkSendPool::IsCollateralValid %s\n", txCollateral.ToString().c_str()); + + CValidationState state; + //if(!AcceptableInputs(mempool, state, txCollateral)){ + bool* pfMissingInputs = false; + if(!AcceptableInputs(mempool, txCollateral, false, pfMissingInputs)){ + if(fDebug) LogPrintf ("CDarkSendPool::IsCollateralValid - didn't pass IsAcceptable\n"); + return false; + } + + return true; +} + + +// +// Add a clients transaction to the pool +// +bool CDarkSendPool::AddEntry(const std::vector& newInput, const int64_t& nAmount, const CTransaction& txCollateral, const std::vector& newOutput, std::string& error){ + if (!fMasterNode) return false; + + BOOST_FOREACH(CTxIn in, newInput) { + if (in.prevout.IsNull() || nAmount < 0) { + if(fDebug) LogPrintf ("CDarkSendPool::AddEntry - input not valid!\n"); + error = _("Input is not valid."); + sessionUsers--; + return false; + } + } + + if (!IsCollateralValid(txCollateral)){ + if(fDebug) LogPrintf ("CDarkSendPool::AddEntry - collateral not valid!\n"); + error = _("Collateral is not valid."); + sessionUsers--; + return false; + } + + if((int)entries.size() >= GetMaxPoolTransactions()){ + if(fDebug) LogPrintf ("CDarkSendPool::AddEntry - entries is full!\n"); + error = _("Entries are full."); + sessionUsers--; + return false; + } + + BOOST_FOREACH(CTxIn in, newInput) { + if(fDebug) LogPrintf("looking for vin -- %s\n", in.ToString().c_str()); + BOOST_FOREACH(const CDarkSendEntry v, entries) { + BOOST_FOREACH(const CDarkSendEntryVin s, v.sev){ + if(s.vin == in) { + if(fDebug) LogPrintf ("CDarkSendPool::AddEntry - found in vin\n"); + error = _("Already have that input."); + sessionUsers--; + return false; + } + } + } + } + + if(state == POOL_STATUS_ACCEPTING_ENTRIES) { + CDarkSendEntry v; + v.Add(newInput, nAmount, txCollateral, newOutput); + entries.push_back(v); + + if(fDebug) LogPrintf("CDarkSendPool::AddEntry -- adding %s\n", newInput[0].ToString().c_str()); + error = ""; + + return true; + } + + if(fDebug) LogPrintf ("CDarkSendPool::AddEntry - can't accept new entry, wrong state!\n"); + error = _("Wrong state."); + sessionUsers--; + return false; +} + +bool CDarkSendPool::AddScriptSig(const CTxIn newVin){ + if(fDebug) LogPrintf("CDarkSendPool::AddScriptSig -- new sig %s\n", newVin.scriptSig.ToString().substr(0,24).c_str()); + + BOOST_FOREACH(const CDarkSendEntry v, entries) { + BOOST_FOREACH(const CDarkSendEntryVin s, v.sev){ + if(s.vin.scriptSig == newVin.scriptSig) { + LogPrintf("CDarkSendPool::AddScriptSig - already exists \n"); + return false; + } + } + } + + if(!SignatureValid(newVin.scriptSig, newVin)){ + if(fDebug) LogPrintf("CDarkSendPool::AddScriptSig - Invalid Sig\n"); + return false; + } + + if(fDebug) LogPrintf("CDarkSendPool::AddScriptSig -- sig %s\n", newVin.ToString().c_str()); + + if(state == POOL_STATUS_SIGNING) { + BOOST_FOREACH(CTxIn& vin, finalTransaction.vin){ + if(newVin.prevout == vin.prevout && vin.nSequence == newVin.nSequence){ + vin.scriptSig = newVin.scriptSig; + vin.prevPubKey = newVin.prevPubKey; + if(fDebug) LogPrintf("CDarkSendPool::AddScriptSig -- adding to finalTransaction %s\n", newVin.scriptSig.ToString().substr(0,24).c_str()); + } + } + for(unsigned int i = 0; i < entries.size(); i++){ + if(entries[i].AddSig(newVin)){ + if(fDebug) LogPrintf("CDarkSendPool::AddScriptSig -- adding %s\n", newVin.scriptSig.ToString().substr(0,24).c_str()); + return true; + } + } + } + + LogPrintf("CDarkSendPool::AddScriptSig -- Couldn't set sig!\n" ); + return false; +} + +// check to make sure everything is signed +bool CDarkSendPool::SignaturesComplete(){ + BOOST_FOREACH(const CDarkSendEntry v, entries) { + BOOST_FOREACH(const CDarkSendEntryVin s, v.sev){ + if(!s.isSigSet) return false; + } + } + return true; +} + +// +// Execute a darksend denomination via a masternode. +// This is only ran from clients +// +void CDarkSendPool::SendDarksendDenominate(std::vector& vin, std::vector& vout, int64_t amount){ + if(darkSendPool.txCollateral == CTransaction()){ + LogPrintf ("CDarksendPool:SendDarksendDenominate() - Darksend collateral not set"); + return; + } + + // lock the funds we're going to use + BOOST_FOREACH(CTxIn in, txCollateral.vin) + lockedCoins.push_back(in); + + BOOST_FOREACH(CTxIn in, vin) + lockedCoins.push_back(in); + + //BOOST_FOREACH(CTxOut o, vout) + // LogPrintf(" vout - %s\n", o.ToString().c_str()); + + + // we should already be connected to a masternode + if(!sessionFoundMasternode){ + LogPrintf("CDarkSendPool::SendDarksendDenominate() - No masternode has been selected yet.\n"); + UnlockCoins(); + SetNull(true); + return; + } + + if (!CheckDiskSpace()) + return; + + if(fMasterNode) { + LogPrintf("CDarkSendPool::SendDarksendDenominate() - DarkSend from a masternode is not supported currently.\n"); + return; + } + + UpdateState(POOL_STATUS_ACCEPTING_ENTRIES); + + LogPrintf("CDarkSendPool::SendDarksendDenominate() - Added transaction to pool.\n"); + + ClearLastMessage(); + + //check it against the memory pool to make sure it's valid + { + int64_t nValueOut = 0; + + CValidationState state; + CTransaction tx; + + BOOST_FOREACH(const CTxOut o, vout){ + nValueOut += o.nValue; + tx.vout.push_back(o); + } + + BOOST_FOREACH(const CTxIn i, vin){ + tx.vin.push_back(i); + + if(fDebug) LogPrintf("dsi -- tx in %s\n", i.ToString().c_str()); + } + + //if(!AcceptableInputs(mempool, state, tx)){ + bool* pfMissingInputs; + if(!AcceptableInputs(mempool, tx, false, pfMissingInputs)){ + LogPrintf("dsi -- transaction not valid! %s \n", tx.ToString().c_str()); + return; + } + } + + // store our entry for later use + CDarkSendEntry e; + e.Add(vin, amount, txCollateral, vout); + myEntries.push_back(e); + + // relay our entry to the master node + RelayDarkSendIn(vin, amount, txCollateral, vout); + Check(); +} + +// Incoming message from masternode updating the progress of darksend +// newAccepted: -1 mean's it'n not a "transaction accepted/not accepted" message, just a standard update +// 0 means transaction was not accepted +// 1 means transaction was accepted + +bool CDarkSendPool::StatusUpdate(int newState, int newEntriesCount, int newAccepted, std::string& error, int newSessionID){ + if(fMasterNode) return false; + if(state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) return false; + + UpdateState(newState); + entriesCount = newEntriesCount; + + if(error.size() > 0) strAutoDenomResult = _("Masternode:") + " " + error; + + if(newAccepted != -1) { + lastEntryAccepted = newAccepted; + countEntriesAccepted += newAccepted; + if(newAccepted == 0){ + UpdateState(POOL_STATUS_ERROR); + lastMessage = error; + } + + if(newAccepted == 1) { + sessionID = newSessionID; + LogPrintf("CDarkSendPool::StatusUpdate - set sessionID to %d\n", sessionID); + sessionFoundMasternode = true; + } + } + + if(newState == POOL_STATUS_ACCEPTING_ENTRIES){ + if(newAccepted == 1){ + LogPrintf("CDarkSendPool::StatusUpdate - entry accepted! \n"); + sessionFoundMasternode = true; + //wait for other users. Masternode will report when ready + UpdateState(POOL_STATUS_QUEUE); + } else if (newAccepted == 0 && sessionID == 0 && !sessionFoundMasternode) { + LogPrintf("CDarkSendPool::StatusUpdate - entry not accepted by masternode \n"); + UnlockCoins(); + UpdateState(POOL_STATUS_ACCEPTING_ENTRIES); + DoAutomaticDenominating(); //try another masternode + } + if(sessionFoundMasternode) return true; + } + + return true; +} + +// +// After we receive the finalized transaction from the masternode, we must +// check it to make sure it's what we want, then sign it if we agree. +// If we refuse to sign, it's possible we'll be charged collateral +// +bool CDarkSendPool::SignFinalTransaction(CTransaction& finalTransactionNew, CNode* node){ + if(fDebug) LogPrintf("CDarkSendPool::AddFinalTransaction - Got Finalized Transaction\n"); + + if(!finalTransaction.vin.empty()){ + LogPrintf("CDarkSendPool::AddFinalTransaction - Rejected Final Transaction!\n"); + return false; + } + + finalTransaction = finalTransactionNew; + LogPrintf("CDarkSendPool::SignFinalTransaction %s\n", finalTransaction.ToString().c_str()); + + vector sigs; + + //make sure my inputs/outputs are present, otherwise refuse to sign + BOOST_FOREACH(const CDarkSendEntry e, myEntries) { + BOOST_FOREACH(const CDarkSendEntryVin s, e.sev) { + /* Sign my transaction and all outputs */ + int mine = -1; + CScript prevPubKey = CScript(); + CTxIn vin = CTxIn(); + + for(unsigned int i = 0; i < finalTransaction.vin.size(); i++){ + if(finalTransaction.vin[i] == s.vin){ + mine = i; + prevPubKey = s.vin.prevPubKey; + vin = s.vin; + } + } + + if(mine >= 0){ //might have to do this one input at a time? + int foundOutputs = 0; + int64_t nValue1 = 0; + int64_t nValue2 = 0; + + for(unsigned int i = 0; i < finalTransaction.vout.size(); i++){ + BOOST_FOREACH(const CTxOut o, e.vout) { + if(finalTransaction.vout[i] == o){ + foundOutputs++; + nValue1 += finalTransaction.vout[i].nValue; + } + } + } + + BOOST_FOREACH(const CTxOut o, e.vout) + nValue2 += o.nValue; + + int targetOuputs = e.vout.size(); + if(foundOutputs < targetOuputs || nValue1 != nValue2) { + // in this case, something went wrong and we'll refuse to sign. It's possible we'll be charged collateral. But that's + // better then signing if the transaction doesn't look like what we wanted. + LogPrintf("CDarkSendPool::Sign - My entries are not correct! Refusing to sign. %d entries %d target. \n", foundOutputs, targetOuputs); + return false; + } + + if(fDebug) LogPrintf("CDarkSendPool::Sign - Signing my input %i\n", mine); + if(!SignSignature(*pwalletMain, prevPubKey, finalTransaction, mine, int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))) { // changes scriptSig + if(fDebug) LogPrintf("CDarkSendPool::Sign - Unable to sign my own transaction! \n"); + // not sure what to do here, it will timeout...? + } + + sigs.push_back(finalTransaction.vin[mine]); + if(fDebug) LogPrintf(" -- dss %d %d %s\n", mine, (int)sigs.size(), finalTransaction.vin[mine].scriptSig.ToString().c_str()); + } + + } + + if(fDebug) LogPrintf("CDarkSendPool::Sign - txNew:\n%s", finalTransaction.ToString().c_str()); + } + + // push all of our signatures to the masternode + if(sigs.size() > 0 && node != NULL) + node->PushMessage("dss", sigs); + + return true; +} + +void CDarkSendPool::NewBlock() +{ + if(fDebug) LogPrintf("CDarkSendPool::NewBlock \n"); + + //we we're processing lots of blocks, we'll just leave + if(GetTime() - lastNewBlock < 10) return; + lastNewBlock = GetTime(); + + darkSendPool.CheckTimeout(); + + if(!fEnableDarksend) return; + + if(!fMasterNode){ + //denominate all non-denominated inputs every 25 minutes. + if(pindexBest->nHeight % 10 == 0) UnlockCoins(); + ProcessMasternodeConnections(); + } +} + +// Darksend transaction was completed (failed or successed) +void CDarkSendPool::CompletedTransaction(bool error, std::string lastMessageNew) +{ + if(fMasterNode) return; + + if(error){ + LogPrintf("CompletedTransaction -- error \n"); + UpdateState(POOL_STATUS_ERROR); + } else { + LogPrintf("CompletedTransaction -- success \n"); + UpdateState(POOL_STATUS_SUCCESS); + + myEntries.clear(); + + // To avoid race conditions, we'll only let DS run once per block + cachedLastSuccess = pindexBest->nHeight; + } + lastMessage = lastMessageNew; + + completedTransaction = true; + Check(); + UnlockCoins(); +} + +void CDarkSendPool::ClearLastMessage() +{ + lastMessage = ""; +} + +// +// Passively run Darksend in the background to anonymize funds based on the given configuration. +// +// This does NOT run by default for daemons, only for QT. +// +bool CDarkSendPool::DoAutomaticDenominating(bool fDryRun, bool ready) +{ + LOCK(cs_darksend); + + if(IsInitialBlockDownload()) return false; + + if(fMasterNode) return false; + if(state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) return false; + + if(pindexBest->nHeight - cachedLastSuccess < minBlockSpacing) { + LogPrintf("CDarkSendPool::DoAutomaticDenominating - Last successful darksend action was too recent\n"); + strAutoDenomResult = _("Last successful darksend action was too recent."); + return false; + } + if(!fEnableDarksend) { + if(fDebug) LogPrintf("CDarkSendPool::DoAutomaticDenominating - Darksend is disabled\n"); + strAutoDenomResult = _("Darksend is disabled."); + return false; + } + + if (!fDryRun && pwalletMain->IsLocked()){ + strAutoDenomResult = _("Wallet is locked."); + return false; + } + + if(darkSendPool.GetState() != POOL_STATUS_ERROR && darkSendPool.GetState() != POOL_STATUS_SUCCESS){ + if(darkSendPool.GetMyTransactionCount() > 0){ + return true; + } + } + + if(vecMasternodes.size() == 0){ + if(fDebug) LogPrintf("CDarkSendPool::DoAutomaticDenominating - No masternodes detected\n"); + strAutoDenomResult = _("No masternodes detected."); + return false; + } + + // ** find the coins we'll use + std::vector vCoins; + std::vector vCoins2; + int64_t nValueMin = CENT; + int64_t nValueIn = 0; + + // should not be less than fees in DARKSEND_FEE + few (lets say 5) smallest denoms + int64_t nLowestDenom = DARKSEND_FEE + darkSendDenominations[darkSendDenominations.size() - 1]*5; + + // if there are no DS collateral inputs yet + if(!pwalletMain->HasCollateralInputs()) + // should have some additional amount for them + nLowestDenom += (DARKSEND_COLLATERAL*4)+DARKSEND_FEE*2; + + int64_t nBalanceNeedsAnonymized = nAnonymizeGeniusAmount*COIN - pwalletMain->GetAnonymizedBalance(); + + // if balanceNeedsAnonymized is more than pool max, take the pool max + if(nBalanceNeedsAnonymized > DARKSEND_POOL_MAX) nBalanceNeedsAnonymized = DARKSEND_POOL_MAX; + + // if balanceNeedsAnonymized is more than non-anonymized, take non-anonymized + int64_t nBalanceNotYetAnonymized = pwalletMain->GetBalance() - pwalletMain->GetAnonymizedBalance(); + if(nBalanceNeedsAnonymized > nBalanceNotYetAnonymized) nBalanceNeedsAnonymized = nBalanceNotYetAnonymized; + + if(nBalanceNeedsAnonymized < nLowestDenom) + { +// if(nBalanceNeedsAnonymized > nValueMin) +// nBalanceNeedsAnonymized = nLowestDenom; +// else +// { + LogPrintf("DoAutomaticDenominating : No funds detected in need of denominating \n"); + strAutoDenomResult = _("No funds detected in need of denominating."); + return false; +// } + } + + if (fDebug) LogPrintf("DoAutomaticDenominating : nLowestDenom=%d, nBalanceNeedsAnonymized=%d\n", nLowestDenom, nBalanceNeedsAnonymized); + + // select coins that should be given to the pool + if (!pwalletMain->SelectCoinsDark(nValueMin, nBalanceNeedsAnonymized, vCoins, nValueIn, 0, nDarksendRounds)) + { + nValueIn = 0; + vCoins.clear(); + + if (pwalletMain->SelectCoinsDark(nValueMin, 9999999*COIN, vCoins, nValueIn, -2, 0)) + { + if(!fDryRun) return CreateDenominated(nBalanceNeedsAnonymized); + return true; + } else { + LogPrintf("DoAutomaticDenominating : Can't denominate - no compatible inputs left\n"); + strAutoDenomResult = _("Can't denominate: no compatible inputs left."); + return false; + } + + } + + //check to see if we have the collateral sized inputs, it requires these + if(!pwalletMain->HasCollateralInputs()){ + if(!fDryRun) MakeCollateralAmounts(); + return true; + } + + if(fDryRun) return true; + + // initial phase, find a masternode + if(!sessionFoundMasternode){ + int nUseQueue = rand()%100; + + sessionTotalValue = pwalletMain->GetTotalValue(vCoins); + + //randomize the amounts we mix + if(sessionTotalValue > nBalanceNeedsAnonymized) sessionTotalValue = nBalanceNeedsAnonymized; + + double fGeniusSubmitted = (sessionTotalValue / CENT); + LogPrintf("Submitting Darksend for %f GENIUS CENT - sessionTotalValue %d\n", fGeniusSubmitted, sessionTotalValue); + + if(pwalletMain->GetDenominatedBalance(true, true) > 0){ //get denominated unconfirmed inputs + LogPrintf("DoAutomaticDenominating -- Found unconfirmed denominated outputs, will wait till they confirm to continue.\n"); + strAutoDenomResult = _("Found unconfirmed denominated outputs, will wait till they confirm to continue."); + return false; + } + + //don't use the queues all of the time for mixing + if(nUseQueue > 33){ + + // Look through the queues and see if anything matches + BOOST_FOREACH(CDarksendQueue& dsq, vecDarksendQueue){ + CService addr; + if(dsq.time == 0) continue; + + if(!dsq.GetAddress(addr)) continue; + if(dsq.IsExpired()) continue; + + int protocolVersion; + if(!dsq.GetProtocolVersion(protocolVersion)) continue; + if(protocolVersion < MIN_PEER_PROTO_VERSION) continue; + + //non-denom's are incompatible + if((dsq.nDenom & (1 << 4))) continue; + + //don't reuse masternodes + BOOST_FOREACH(CTxIn usedVin, vecMasternodesUsed){ + if(dsq.vin == usedVin) { + continue; + } + } + + // Try to match their denominations if possible + if (!pwalletMain->SelectCoinsByDenominations(dsq.nDenom, nValueMin, nBalanceNeedsAnonymized, vCoins, vCoins2, nValueIn, 0, nDarksendRounds)){ + LogPrintf("DoAutomaticDenominating - Couldn't match denominations %d\n", dsq.nDenom); + continue; + } + + // connect to masternode and submit the queue request + if(ConnectNode((CAddress)addr, NULL, true)){ + submittedToMasternode = addr; + + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + if((CNetAddr)pnode->addr != (CNetAddr)submittedToMasternode) continue; + + std::string strReason; + if(txCollateral == CTransaction()){ + if(!pwalletMain->CreateCollateralTransaction(txCollateral, strReason)){ + LogPrintf("DoAutomaticDenominating -- dsa error:%s\n", strReason.c_str()); + return false; + } + } + + vecMasternodesUsed.push_back(dsq.vin); + sessionDenom = dsq.nDenom; + + pnode->PushMessage("dsa", sessionDenom, txCollateral); + LogPrintf("DoAutomaticDenominating --- connected (from queue), sending dsa for %d %d - %s\n", sessionDenom, GetDenominationsByAmount(sessionTotalValue), pnode->addr.ToString().c_str()); + strAutoDenomResult = ""; + return true; + } + } else { + LogPrintf("DoAutomaticDenominating --- error connecting \n"); + strAutoDenomResult = _("Error connecting to masternode."); + return DoAutomaticDenominating(); + } + + dsq.time = 0; //remove node + } + } + + //shuffle masternodes around before we try to connect + std::random_shuffle ( vecMasternodes.begin(), vecMasternodes.end() ); + int i = 0; + + // otherwise, try one randomly + while(i < 10) + { + //don't reuse masternodes + BOOST_FOREACH(CTxIn usedVin, vecMasternodesUsed) { + if(vecMasternodes[i].vin == usedVin){ + i++; + continue; + } + } + if(vecMasternodes[i].protocolVersion < MIN_PEER_PROTO_VERSION) { + i++; + continue; + } + + if(vecMasternodes[i].nLastDsq != 0 && + vecMasternodes[i].nLastDsq + CountMasternodesAboveProtocol(darkSendPool.MIN_PEER_PROTO_VERSION)/5 > darkSendPool.nDsqCount){ + i++; + continue; + } + + lastTimeChanged = GetTimeMillis(); + LogPrintf("DoAutomaticDenominating -- attempt %d connection to masternode %s\n", i, vecMasternodes[i].addr.ToString().c_str()); + if(ConnectNode((CAddress)vecMasternodes[i].addr, NULL, true)){ + submittedToMasternode = vecMasternodes[i].addr; + + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + if((CNetAddr)pnode->addr != (CNetAddr)vecMasternodes[i].addr) continue; + + std::string strReason; + if(txCollateral == CTransaction()){ + if(!pwalletMain->CreateCollateralTransaction(txCollateral, strReason)){ + LogPrintf("DoAutomaticDenominating -- create collateral error:%s\n", strReason.c_str()); + return false; + } + } + + vecMasternodesUsed.push_back(vecMasternodes[i].vin); + + std::vector vecAmounts; + pwalletMain->ConvertList(vCoins, vecAmounts); + sessionDenom = GetDenominationsByAmounts(vecAmounts); + + pnode->PushMessage("dsa", sessionDenom, txCollateral); + LogPrintf("DoAutomaticDenominating --- connected, sending dsa for %d - denom %d\n", sessionDenom, GetDenominationsByAmount(sessionTotalValue)); + strAutoDenomResult = ""; + return true; + } + } else { + i++; + continue; + } + } + + strAutoDenomResult = _("No compatible masternode found."); + return false; + } + + strAutoDenomResult = ""; + if(!ready) return true; + + if(sessionDenom == 0) return true; + + return false; +} + + +bool CDarkSendPool::PrepareDarksendDenominate() +{ + // Submit transaction to the pool if we get here, use sessionDenom so we use the same amount of money + std::string strError = pwalletMain->PrepareDarksendDenominate(0, nDarksendRounds); + LogPrintf("DoAutomaticDenominating : Running darksend denominate. Return '%s'\n", strError.c_str()); + + if(strError == "") return true; + + strAutoDenomResult = strError; + LogPrintf("DoAutomaticDenominating : Error running denominate, %s\n", strError.c_str()); + return false; +} + +bool CDarkSendPool::SendRandomPaymentToSelf() +{ + int64_t nBalance = pwalletMain->GetBalance(); + int64_t nPayment = (nBalance*0.35) + (rand() % nBalance); + + if(nPayment > nBalance) nPayment = nBalance-(0.1*COIN); + + // make our change address + CReserveKey reservekey(pwalletMain); + + CScript scriptChange; + CPubKey vchPubKey; + assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked + scriptChange= GetScriptForDestination(vchPubKey.GetID()); + + CWalletTx wtx; + int64_t nFeeRet = 0; + std::string strFail = ""; + vector< pair > vecSend; + + // ****** Add fees ************ / + vecSend.push_back(make_pair(scriptChange, nPayment)); + + CCoinControl *coinControl=NULL; + int32_t nChangePos; + bool success = pwalletMain->CreateTransaction(vecSend, wtx, reservekey, nFeeRet, nChangePos, strFail, coinControl, ONLY_DENOMINATED); + if(!success){ + LogPrintf("SendRandomPaymentToSelf: Error - %s\n", strFail.c_str()); + return false; + } + + pwalletMain->CommitTransaction(wtx, reservekey); + + LogPrintf("SendRandomPaymentToSelf Success: tx %s\n", wtx.GetHash().GetHex().c_str()); + + return true; +} + +// Split up large inputs or create fee sized inputs +bool CDarkSendPool::MakeCollateralAmounts() +{ + // make our change address + CReserveKey reservekey(pwalletMain); + + CScript scriptChange; + CPubKey vchPubKey; + assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked + scriptChange= GetScriptForDestination(vchPubKey.GetID()); + + CWalletTx wtx; + int64_t nFeeRet = 0; + std::string strFail = ""; + vector< pair > vecSend; + + vecSend.push_back(make_pair(scriptChange, (DARKSEND_COLLATERAL*2)+DARKSEND_FEE)); + vecSend.push_back(make_pair(scriptChange, (DARKSEND_COLLATERAL*2)+DARKSEND_FEE)); + + CCoinControl *coinControl=NULL; + int32_t nChangePos; + // try to use non-denominated and not mn-like funds + bool success = pwalletMain->CreateTransaction(vecSend, wtx, reservekey, + nFeeRet, nChangePos, strFail, coinControl, ONLY_NONDENOMINATED_NOTMN); + if(!success){ + // if we failed (most likeky not enough funds), try to use denominated instead - + // MN-like funds should not be touched in any case and we can't mix denominated without collaterals anyway + success = pwalletMain->CreateTransaction(vecSend, wtx, reservekey, + nFeeRet, nChangePos, strFail, coinControl, ONLY_DENOMINATED); + if(!success){ + LogPrintf("MakeCollateralAmounts: Error - %s\n", strFail.c_str()); + return false; + } + } + + // use the same cachedLastSuccess as for DS mixinx to prevent race + if(pwalletMain->CommitTransaction(wtx, reservekey)) + cachedLastSuccess = pindexBest->nHeight; + + LogPrintf("MakeCollateralAmounts Success: tx %s\n", wtx.GetHash().GetHex().c_str()); + + return true; +} + +// Create denominations +bool CDarkSendPool::CreateDenominated(int64_t nTotalValue) +{ + // make our change address + CReserveKey reservekey(pwalletMain); + + CScript scriptChange; + CPubKey vchPubKey; + assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked + scriptChange= GetScriptForDestination(vchPubKey.GetID()); + + CWalletTx wtx; + int64_t nFeeRet = 0; + std::string strFail = ""; + vector< pair > vecSend; + int64_t nValueLeft = nTotalValue; + + // ****** Add collateral outputs ************ / + if(!pwalletMain->HasCollateralInputs()) { + vecSend.push_back(make_pair(scriptChange, (DARKSEND_COLLATERAL*2)+DARKSEND_FEE)); + nValueLeft -= (DARKSEND_COLLATERAL*2)+DARKSEND_FEE; + vecSend.push_back(make_pair(scriptChange, (DARKSEND_COLLATERAL*2)+DARKSEND_FEE)); + nValueLeft -= (DARKSEND_COLLATERAL*2)+DARKSEND_FEE; + } + + // ****** Add denoms ************ / + BOOST_REVERSE_FOREACH(int64_t v, darkSendDenominations){ + int nOutputs = 0; + + // add each output up to 10 times until it can't be added again + while(nValueLeft - v >= DARKSEND_FEE && nOutputs <= 10) { + CScript scriptChange; + CPubKey vchPubKey; + //use a unique change address + assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked + scriptChange= GetScriptForDestination(vchPubKey.GetID()); + reservekey.KeepKey(); + + vecSend.push_back(make_pair(scriptChange, v)); + + //increment outputs and subtract denomination amount + nOutputs++; + nValueLeft -= v; + LogPrintf("CreateDenominated1 %d\n", nValueLeft); + } + + if(nValueLeft == 0) break; + } + LogPrintf("CreateDenominated2 %d\n", nValueLeft); + + // if we have anything left over, it will be automatically send back as change - there is no need to send it manually + + CCoinControl *coinControl=NULL; + int32_t nChangePos; + bool success = pwalletMain->CreateTransaction(vecSend, wtx, reservekey, + nFeeRet, nChangePos, strFail, coinControl, ONLY_NONDENOMINATED_NOTMN); + if(!success){ + LogPrintf("CreateDenominated: Error - %s\n", strFail.c_str()); + return false; + } + + // use the same cachedLastSuccess as for DS mixinx to prevent race + if(pwalletMain->CommitTransaction(wtx, reservekey)) + cachedLastSuccess = pindexBest->nHeight; + + LogPrintf("CreateDenominated Success: tx %s\n", wtx.GetHash().GetHex().c_str()); + + return true; +} + +bool CDarkSendPool::IsCompatibleWithEntries(std::vector vout) +{ + BOOST_FOREACH(const CDarkSendEntry v, entries) { + LogPrintf(" IsCompatibleWithEntries %d %d\n", GetDenominations(vout), GetDenominations(v.vout)); +/* + BOOST_FOREACH(CTxOut o1, vout) + LogPrintf(" vout 1 - %s\n", o1.ToString().c_str()); + + BOOST_FOREACH(CTxOut o2, v.vout) + LogPrintf(" vout 2 - %s\n", o2.ToString().c_str()); +*/ + if(GetDenominations(vout) != GetDenominations(v.vout)) return false; + } + + return true; +} + +bool CDarkSendPool::IsCompatibleWithSession(int64_t nDenom, CTransaction txCollateral, std::string& strReason) +{ + LogPrintf("CDarkSendPool::IsCompatibleWithSession - sessionDenom %d sessionUsers %d\n", sessionDenom, sessionUsers); + + if (!unitTest && !IsCollateralValid(txCollateral)){ + if(fDebug) LogPrintf ("CDarkSendPool::IsCompatibleWithSession - collateral not valid!\n"); + strReason = _("Collateral not valid."); + return false; + } + + if(sessionUsers < 0) sessionUsers = 0; + + if(sessionUsers == 0) { + sessionDenom = nDenom; + sessionUsers++; + lastTimeChanged = GetTimeMillis(); + entries.clear(); + + if(!unitTest){ + //broadcast that I'm accepting entries, only if it's the first entry though + CDarksendQueue dsq; + dsq.nDenom = nDenom; + dsq.vin = activeMasternode.vin; + dsq.time = GetTime(); + dsq.Sign(); + dsq.Relay(); + } + + UpdateState(POOL_STATUS_QUEUE); + vecSessionCollateral.push_back(txCollateral); + return true; + } + + if((state != POOL_STATUS_ACCEPTING_ENTRIES && state != POOL_STATUS_QUEUE) || sessionUsers >= GetMaxPoolTransactions()){ + if((state != POOL_STATUS_ACCEPTING_ENTRIES && state != POOL_STATUS_QUEUE)) strReason = _("Incompatible mode."); + if(sessionUsers >= GetMaxPoolTransactions()) strReason = _("Masternode queue is full."); + LogPrintf("CDarkSendPool::IsCompatibleWithSession - incompatible mode, return false %d %d\n", state != POOL_STATUS_ACCEPTING_ENTRIES, sessionUsers >= GetMaxPoolTransactions()); + return false; + } + + if(nDenom != sessionDenom) { + strReason = _("No matching denominations found for mixing."); + return false; + } + + LogPrintf("CDarkSendPool::IsCompatibleWithSession - compatible\n"); + + sessionUsers++; + lastTimeChanged = GetTimeMillis(); + vecSessionCollateral.push_back(txCollateral); + + return true; +} + +//create a nice string to show the denominations +void CDarkSendPool::GetDenominationsToString(int nDenom, std::string& strDenom){ + // Function returns as follows: + // + // bit 0 - 100GENIUS+1 ( bit on if present ) + // bit 1 - 10GENIUS+1 + // bit 2 - 1GENIUS+1 + // bit 3 - .1GENIUS+1 + // bit 3 - non-denom + + + strDenom = ""; + + if(nDenom & (1 << 0)) { + if(strDenom.size() > 0) strDenom += "+"; + strDenom += "100"; + } + + if(nDenom & (1 << 1)) { + if(strDenom.size() > 0) strDenom += "+"; + strDenom += "10"; + } + + if(nDenom & (1 << 2)) { + if(strDenom.size() > 0) strDenom += "+"; + strDenom += "1"; + } + + if(nDenom & (1 << 3)) { + if(strDenom.size() > 0) strDenom += "+"; + strDenom += "0.1"; + } +} + +// return a bitshifted integer representing the denominations in this list +int CDarkSendPool::GetDenominations(const std::vector& vout){ + std::vector > denomUsed; + + // make a list of denominations, with zero uses + BOOST_FOREACH(int64_t d, darkSendDenominations) + denomUsed.push_back(make_pair(d, 0)); + + // look for denominations and update uses to 1 + BOOST_FOREACH(CTxOut out, vout){ + bool found = false; + BOOST_FOREACH (PAIRTYPE(int64_t, int)& s, denomUsed){ + if (out.nValue == s.first){ + s.second = 1; + found = true; + } + } + if(!found) return 0; + } + + int denom = 0; + int c = 0; + // if the denomination is used, shift the bit on. + // then move to the next + BOOST_FOREACH (PAIRTYPE(int64_t, int)& s, denomUsed) + denom |= s.second << c++; + + // Function returns as follows: + // + // bit 0 - 100GENIUS+1 ( bit on if present ) + // bit 1 - 10GENIUS+1 + // bit 2 - 1GENIUS+1 + // bit 3 - .1GENIUS+1 + + return denom; +} + + +int CDarkSendPool::GetDenominationsByAmounts(std::vector& vecAmount){ + CScript e = CScript(); + std::vector vout1; + + // Make outputs by looping through denominations, from small to large + BOOST_REVERSE_FOREACH(int64_t v, vecAmount){ + int nOutputs = 0; + + CTxOut o(v, e); + vout1.push_back(o); + nOutputs++; + } + + return GetDenominations(vout1); +} + +int CDarkSendPool::GetDenominationsByAmount(int64_t nAmount, int nDenomTarget){ + CScript e = CScript(); + int64_t nValueLeft = nAmount; + + std::vector vout1; + + // Make outputs by looping through denominations, from small to large + BOOST_REVERSE_FOREACH(int64_t v, darkSendDenominations){ + if(nDenomTarget != 0){ + bool fAccepted = false; + if((nDenomTarget & (1 << 0)) && v == ((100000*COIN)+100000000)) {fAccepted = true;} + else if((nDenomTarget & (1 << 1)) && v == ((10000*COIN) +10000000)) {fAccepted = true;} + else if((nDenomTarget & (1 << 2)) && v == ((1000*COIN) +1000000)) {fAccepted = true;} + else if((nDenomTarget & (1 << 3)) && v == ((100*COIN) +100000)) {fAccepted = true;} + else if((nDenomTarget & (1 << 4)) && v == ((10*COIN) +10000)) {fAccepted = true;} + else if((nDenomTarget & (1 << 5)) && v == ((1*COIN) +1000)) {fAccepted = true;} + else if((nDenomTarget & (1 << 6)) && v == ((.1*COIN) +100)) {fAccepted = true;} + if(!fAccepted) continue; + } + + int nOutputs = 0; + + // add each output up to 10 times until it can't be added again + while(nValueLeft - v >= 0 && nOutputs <= 10) { + CTxOut o(v, e); + vout1.push_back(o); + nValueLeft -= v; + nOutputs++; + } + LogPrintf("GetDenominationsByAmount --- %d nOutputs %d\n", v, nOutputs); + } + + //add non-denom left overs as change + if(nValueLeft > 0){ + CTxOut o(nValueLeft, e); + vout1.push_back(o); + } + + return GetDenominations(vout1); +} + +bool CDarkSendSigner::IsVinAssociatedWithPubkey(CTxIn& vin, CPubKey& pubkey){ + CScript payee2; + payee2= GetScriptForDestination(pubkey.GetID()); + + CTransaction txVin; + uint256 hash; + //if(GetTransaction(vin.prevout.hash, txVin, hash, true)){ + if(GetTransaction(vin.prevout.hash, txVin, hash)){ + BOOST_FOREACH(CTxOut out, txVin.vout){ + if(out.nValue == 5000*COIN){ + if(out.scriptPubKey == payee2) return true; + } + } + } + + return false; +} + +bool CDarkSendSigner::SetKey(std::string strSecret, std::string& errorMessage, CKey& key, CPubKey& pubkey){ + CBitcoinSecret vchSecret; + bool fGood = vchSecret.SetString(strSecret); + + if (!fGood) { + errorMessage = _("Invalid private key."); + return false; + } + + key = vchSecret.GetKey(); + pubkey = key.GetPubKey(); + + return true; +} + +bool CDarkSendSigner::SignMessage(std::string strMessage, std::string& errorMessage, vector& vchSig, CKey key) +{ + CHashWriter ss(SER_GETHASH, 0); + ss << strMessageMagic; + ss << strMessage; + + if (!key.SignCompact(ss.GetHash(), vchSig)) { + errorMessage = _("Signing failed."); + return false; + } + + return true; +} + +bool CDarkSendSigner::VerifyMessage(CPubKey pubkey, vector& vchSig, std::string strMessage, std::string& errorMessage) +{ + CHashWriter ss(SER_GETHASH, 0); + ss << strMessageMagic; + ss << strMessage; + + CPubKey pubkey2; + if (!pubkey2.RecoverCompact(ss.GetHash(), vchSig)) { + errorMessage = _("Error recovering public key."); + return false; + } + + if (fDebug && pubkey2.GetID() != pubkey.GetID()) + LogPrintf("CDarkSendSigner::VerifyMessage -- keys don't match: %s %s", pubkey2.GetID().ToString(), pubkey.GetID().ToString()); + + return (pubkey2.GetID() == pubkey.GetID()); +} + +bool CDarksendQueue::Sign() +{ + if(!fMasterNode) return false; + + std::string strMessage = vin.ToString() + boost::lexical_cast(nDenom) + boost::lexical_cast(time) + boost::lexical_cast(ready); + + CKey key2; + CPubKey pubkey2; + std::string errorMessage = ""; + + if(!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, key2, pubkey2)) + { + LogPrintf("CDarksendQueue():Relay - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage.c_str()); + return false; + } + + if(!darkSendSigner.SignMessage(strMessage, errorMessage, vchSig, key2)) { + LogPrintf("CDarksendQueue():Relay - Sign message failed"); + return false; + } + + if(!darkSendSigner.VerifyMessage(pubkey2, vchSig, strMessage, errorMessage)) { + LogPrintf("CDarksendQueue():Relay - Verify message failed"); + return false; + } + + return true; +} + +bool CDarksendQueue::Relay() +{ + + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes){ + // always relay to everyone + pnode->PushMessage("dsq", (*this)); + } + + return true; +} + +bool CDarksendQueue::CheckSignature() +{ + BOOST_FOREACH(CMasterNode& mn, vecMasternodes) { + + if(mn.vin == vin) { + std::string strMessage = vin.ToString() + boost::lexical_cast(nDenom) + boost::lexical_cast(time) + boost::lexical_cast(ready); + + std::string errorMessage = ""; + if(!darkSendSigner.VerifyMessage(mn.pubkey2, vchSig, strMessage, errorMessage)){ + return error("CDarksendQueue::CheckSignature() - Got bad masternode address signature %s \n", vin.ToString().c_str()); + } + + return true; + } + } + + return false; +} + + +//TODO: Rename/move to core +void ThreadCheckDarkSendPool() +{ + if(fLiteMode) return; //disable all darksend/masternode related functionality + + // Make this thread recognisable as the wallet flushing thread + RenameThread("genius-darksend"); + + unsigned int c = 0; + std::string errorMessage; + + while (true) + { + c++; + + MilliSleep(2500); + //LogPrintf("ThreadCheckDarkSendPool::check timeout\n"); + darkSendPool.CheckTimeout(); + + if(c % 60 == 0){ + LOCK(cs_main); + /* + cs_main is required for doing masternode.Check because something + is modifying the coins view without a mempool lock. It causes + segfaults from this code without the cs_main lock. + */ + { + + LOCK(cs_masternodes); + vector::iterator it = vecMasternodes.begin(); + //check them separately + while(it != vecMasternodes.end()){ + (*it).Check(); + ++it; + } + + + int count = vecMasternodes.size(); + int i = 0; + + BOOST_FOREACH(CMasterNode mn, vecMasternodes) { + + if(mn.addr.IsRFC1918()) continue; //local network + if(mn.IsEnabled()) { + if(fDebug) LogPrintf("Sending masternode entry - %s \n", mn.addr.ToString().c_str()); + BOOST_FOREACH(CNode* pnode, vNodes) { + pnode->PushMessage("dsee", mn.vin, mn.addr, mn.sig, mn.now, mn.pubkey, mn.pubkey2, count, i, mn.lastTimeSeen, mn.protocolVersion); + } + } + + i++; + } + + //remove inactive + it = vecMasternodes.begin(); + while(it != vecMasternodes.end()){ + if((*it).enabled == 4 || (*it).enabled == 3){ + LogPrintf("Removing inactive masternode %s\n", (*it).addr.ToString().c_str()); + it = vecMasternodes.erase(it); + } else { + ++it; + } + } + + } + + masternodePayments.CleanPaymentList(); + CleanTransactionLocksList(); + } + + //try to sync the masternode list and payment list every 5 seconds from at least 3 nodes + if(c % 5 == 0 && RequestedMasterNodeList < 3){ + bool fIsInitialDownload = IsInitialBlockDownload(); + if(!fIsInitialDownload) { + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + if (pnode->nVersion >= darkSendPool.MIN_PEER_PROTO_VERSION) { + + //keep track of who we've asked for the list + if(pnode->HasFulfilledRequest("mnsync")) continue; + pnode->FulfilledRequest("mnsync"); + + LogPrintf("Successfully synced, asking for Masternode list and payment list\n"); + + pnode->PushMessage("dseg", CTxIn()); //request full mn list + pnode->PushMessage("mnget"); //sync payees + pnode->PushMessage("getsporks"); //get current network sporks + RequestedMasterNodeList++; + } + } + } + } + + if(c % MASTERNODE_PING_SECONDS == 0){ + activeMasternode.ManageStatus(); + } + + if(c % 60 == 0){ + //if we've used 1/5 of the masternode list, then clear the list. + if((int)vecMasternodesUsed.size() > (int)vecMasternodes.size() / 5) + vecMasternodesUsed.clear(); + } + + //auto denom every 1 minutes (liquidity provides try less often) + if(c % 60*(nLiquidityProvider+1) == 0){ + if(nLiquidityProvider!=0){ + int nRand = rand() % (101+nLiquidityProvider); + //about 1/100 chance of starting over after 4 rounds. + if(nRand == 50+nLiquidityProvider && pwalletMain->GetAverageAnonymizedRounds() > 8){ + darkSendPool.SendRandomPaymentToSelf(); + int nLeftToAnon = ((pwalletMain->GetBalance() - pwalletMain->GetAnonymizedBalance())/COIN)-3; + if(nLeftToAnon > 999) nLeftToAnon = 999; + nAnonymizeGeniusAmount = (rand() % nLeftToAnon)+3; + } else { + darkSendPool.DoAutomaticDenominating(); + } + } else { + darkSendPool.DoAutomaticDenominating(); + } + } + } +} diff --git a/src/darksend.h b/src/darksend.h new file mode 100644 index 0000000..b555441 --- /dev/null +++ b/src/darksend.h @@ -0,0 +1,432 @@ +// Copyright (c) 2014-2015 The Darkcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef DARKSEND_H +#define DARKSEND_H + +//#include "primitives/transaction.h" +#include "main.h" +#include "masternode.h" +#include "activemasternode.h" + +class CTxIn; +class CDarkSendPool; +class CDarkSendSigner; +class CMasterNodeVote; +class CBitcoinAddress; +class CDarksendQueue; +class CDarksendBroadcastTx; +class CActiveMasternode; + +#define POOL_MAX_TRANSACTIONS 3 // wait for X transactions to merge and publish +#define POOL_STATUS_UNKNOWN 0 // waiting for update +#define POOL_STATUS_IDLE 1 // waiting for update +#define POOL_STATUS_QUEUE 2 // waiting in a queue +#define POOL_STATUS_ACCEPTING_ENTRIES 3 // accepting entries +#define POOL_STATUS_FINALIZE_TRANSACTION 4 // master node will broadcast what it accepted +#define POOL_STATUS_SIGNING 5 // check inputs/outputs, sign final tx +#define POOL_STATUS_TRANSMISSION 6 // transmit transaction +#define POOL_STATUS_ERROR 7 // error +#define POOL_STATUS_SUCCESS 8 // success + +// status update message constants +#define MASTERNODE_ACCEPTED 1 +#define MASTERNODE_REJECTED 0 +#define MASTERNODE_RESET -1 + +#define DARKSEND_QUEUE_TIMEOUT 120 +#define DARKSEND_SIGNING_TIMEOUT 30 + +extern CDarkSendPool darkSendPool; +extern CDarkSendSigner darkSendSigner; +extern std::vector vecDarksendQueue; +extern std::string strMasterNodePrivKey; +extern map mapDarksendBroadcastTxes; +extern CActiveMasternode activeMasternode; + +//specific messages for the Darksend protocol +void ProcessMessageDarksend(CNode* pfrom, std::string& strCommand, CDataStream& vRecv); + +// get the darksend chain depth for a given input +int GetInputDarksendRounds(CTxIn in, int rounds=0); + + +// An input in the darksend pool +class CDarkSendEntryVin +{ +public: + bool isSigSet; + CTxIn vin; + + CDarkSendEntryVin() + { + isSigSet = false; + vin = CTxIn(); + } +}; + +// A clients transaction in the darksend pool +class CDarkSendEntry +{ +public: + bool isSet; + std::vector sev; + int64_t amount; + CTransaction collateral; + std::vector vout; + CTransaction txSupporting; + int64_t addedTime; + + CDarkSendEntry() + { + isSet = false; + collateral = CTransaction(); + amount = 0; + } + + bool Add(const std::vector vinIn, int64_t amountIn, const CTransaction collateralIn, const std::vector voutIn) + { + if(isSet){return false;} + + BOOST_FOREACH(const CTxIn v, vinIn) { + CDarkSendEntryVin s = CDarkSendEntryVin(); + s.vin = v; + sev.push_back(s); + } + vout = voutIn; + amount = amountIn; + collateral = collateralIn; + isSet = true; + addedTime = GetTime(); + + return true; + } + + bool AddSig(const CTxIn& vin) + { + BOOST_FOREACH(CDarkSendEntryVin& s, sev) { + if(s.vin.prevout == vin.prevout && s.vin.nSequence == vin.nSequence){ + if(s.isSigSet){return false;} + s.vin.scriptSig = vin.scriptSig; + s.vin.prevPubKey = vin.prevPubKey; + s.isSigSet = true; + + return true; + } + } + + return false; + } + + bool IsExpired() + { + return (GetTime() - addedTime) > DARKSEND_QUEUE_TIMEOUT;// 120 seconds + } +}; + +// +// A currently inprogress darksend merge and denomination information +// +class CDarksendQueue +{ +public: + CTxIn vin; + int64_t time; + int nDenom; + bool ready; //ready for submit + std::vector vchSig; + + CDarksendQueue() + { + nDenom = 0; + vin = CTxIn(); + time = 0; + vchSig.clear(); + ready = false; + } + + ADD_SERIALIZE_METHODS; + + template + inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion){ + unsigned int nSerSize = 0; + READWRITE(nDenom); + READWRITE(vin); + READWRITE(time); + READWRITE(ready); + READWRITE(vchSig); + } + + bool GetAddress(CService &addr) + { + BOOST_FOREACH(CMasterNode mn, vecMasternodes) { + if(mn.vin == vin){ + addr = mn.addr; + return true; + } + } + return false; + } + + bool GetProtocolVersion(int &protocolVersion) + { + BOOST_FOREACH(CMasterNode mn, vecMasternodes) { + if(mn.vin == vin){ + protocolVersion = mn.protocolVersion; + return true; + } + } + return false; + } + + bool Sign(); + bool Relay(); + + bool IsExpired() + { + return (GetTime() - time) > DARKSEND_QUEUE_TIMEOUT;// 120 seconds + } + + bool CheckSignature(); + +}; + +// store darksend tx signature information +class CDarksendBroadcastTx +{ +public: + CTransaction tx; + CTxIn vin; + vector vchSig; + int64_t sigTime; +}; + +// +// Helper object for signing and checking signatures +// +class CDarkSendSigner +{ +public: + bool IsVinAssociatedWithPubkey(CTxIn& vin, CPubKey& pubkey); + bool SetKey(std::string strSecret, std::string& errorMessage, CKey& key, CPubKey& pubkey); + bool SignMessage(std::string strMessage, std::string& errorMessage, std::vector& vchSig, CKey key); + bool VerifyMessage(CPubKey pubkey, std::vector& vchSig, std::string strMessage, std::string& errorMessage); +}; + +class CDarksendSession +{ + +}; + +// +// Used to keep track of current status of darksend pool +// +class CDarkSendPool +{ +public: + static const int MIN_PEER_PROTO_VERSION = 60020; + + // clients entries + std::vector myEntries; + // masternode entries + std::vector entries; + // the finalized transaction ready for signing + CTransaction finalTransaction; + + int64_t lastTimeChanged; + int64_t lastAutoDenomination; + + unsigned int state; + unsigned int entriesCount; + unsigned int lastEntryAccepted; + unsigned int countEntriesAccepted; + + // where collateral should be made out to + CScript collateralPubKey; + + std::vector lockedCoins; + + uint256 masterNodeBlockHash; + + std::string lastMessage; + bool completedTransaction; + bool unitTest; + CService submittedToMasternode; + + int sessionID; + int sessionDenom; //Users must submit an denom matching this + int sessionUsers; //N Users have said they'll join + bool sessionFoundMasternode; //If we've found a compatible masternode + int64_t sessionTotalValue; //used for autoDenom + std::vector vecSessionCollateral; + + int cachedLastSuccess; + int cachedNumBlocks; //used for the overview screen + int minBlockSpacing; //required blocks between mixes + CTransaction txCollateral; + + int64_t lastNewBlock; + + //debugging data + std::string strAutoDenomResult; + + //incremented whenever a DSQ comes through + int64_t nDsqCount; + + CDarkSendPool() + { + /* DarkSend uses collateral addresses to trust parties entering the pool + to behave themselves. If they don't it takes their money. */ + + cachedLastSuccess = 0; + cachedNumBlocks = 0; + unitTest = false; + txCollateral = CTransaction(); + minBlockSpacing = 1; + nDsqCount = 0; + lastNewBlock = 0; + + SetNull(); + } + + void InitCollateralAddress(){ + std::string strAddress = ""; + strAddress = "2aAux4dW2zpjZPBNPs6p4NNcauTApymr4M"; + SetCollateralAddress(strAddress); + } + + void SetMinBlockSpacing(int minBlockSpacingIn){ + minBlockSpacing = minBlockSpacingIn; + } + + bool SetCollateralAddress(std::string strAddress); + void Reset(); + void SetNull(bool clearEverything=false); + + void UnlockCoins(); + + bool IsNull() const + { + return (state == POOL_STATUS_ACCEPTING_ENTRIES && entries.empty() && myEntries.empty()); + } + + int GetState() const + { + return state; + } + + int GetEntriesCount() const + { + if(fMasterNode){ + return entries.size(); + } else { + return entriesCount; + } + } + + int GetLastEntryAccepted() const + { + return lastEntryAccepted; + } + + int GetCountEntriesAccepted() const + { + return countEntriesAccepted; + } + + int GetMyTransactionCount() const + { + return myEntries.size(); + } + + void UpdateState(unsigned int newState) + { + if (fMasterNode && (newState == POOL_STATUS_ERROR || newState == POOL_STATUS_SUCCESS)){ + LogPrintf("CDarkSendPool::UpdateState() - Can't set state to ERROR or SUCCESS as a masternode. \n"); + return; + } + + LogPrintf("CDarkSendPool::UpdateState() == %d | %d \n", state, newState); + if(state != newState){ + lastTimeChanged = GetTimeMillis(); + if(fMasterNode) { + RelayDarkSendStatus(darkSendPool.sessionID, darkSendPool.GetState(), darkSendPool.GetEntriesCount(), MASTERNODE_RESET); + } + } + state = newState; + } + + int GetMaxPoolTransactions() + { + + //use the production amount + return POOL_MAX_TRANSACTIONS; + } + + //Do we have enough users to take entries? + bool IsSessionReady(){ + return sessionUsers >= GetMaxPoolTransactions(); + } + + // Are these outputs compatible with other client in the pool? + bool IsCompatibleWithEntries(std::vector vout); + // Is this amount compatible with other client in the pool? + bool IsCompatibleWithSession(int64_t nAmount, CTransaction txCollateral, std::string& strReason); + + // Passively run Darksend in the background according to the configuration in settings (only for QT) + bool DoAutomaticDenominating(bool fDryRun=false, bool ready=false); + bool PrepareDarksendDenominate(); + + + // check for process in Darksend + void Check(); + // charge fees to bad actors + void ChargeFees(); + // rarely charge fees to pay miners + void ChargeRandomFees(); + void CheckTimeout(); + // check to make sure a signature matches an input in the pool + bool SignatureValid(const CScript& newSig, const CTxIn& newVin); + // if the collateral is valid given by a client + bool IsCollateralValid(const CTransaction& txCollateral); + // add a clients entry to the pool + bool AddEntry(const std::vector& newInput, const int64_t& nAmount, const CTransaction& txCollateral, const std::vector& newOutput, std::string& error); + // add signature to a vin + bool AddScriptSig(const CTxIn newVin); + // are all inputs signed? + bool SignaturesComplete(); + // as a client, send a transaction to a masternode to start the denomination process + void SendDarksendDenominate(std::vector& vin, std::vector& vout, int64_t amount); + // get masternode updates about the progress of darksend + bool StatusUpdate(int newState, int newEntriesCount, int newAccepted, std::string& error, int newSessionID=0); + + // as a client, check and sign the final transaction + bool SignFinalTransaction(CTransaction& finalTransactionNew, CNode* node); + + // get the last valid block hash for a given modulus + bool GetLastValidBlockHash(uint256& hash, int mod=1, int nBlockHeight=0); + // process a new block + void NewBlock(); + void CompletedTransaction(bool error, std::string lastMessageNew); + void ClearLastMessage(); + // used for liquidity providers + bool SendRandomPaymentToSelf(); + // split up large inputs or make fee sized inputs + bool MakeCollateralAmounts(); + bool CreateDenominated(int64_t nTotalValue); + // get the denominations for a list of outputs (returns a bitshifted integer) + int GetDenominations(const std::vector& vout); + void GetDenominationsToString(int nDenom, std::string& strDenom); + // get the denominations for a specific amount of genius. + int GetDenominationsByAmount(int64_t nAmount, int nDenomTarget=0); + + int GetDenominationsByAmounts(std::vector& vecAmount); +}; + + +void ConnectToDarkSendMasterNodeWinner(); + +void ThreadCheckDarkSendPool(); + +#endif diff --git a/src/eccryptoverify.cpp b/src/eccryptoverify.cpp new file mode 100644 index 0000000..a22bf41 --- /dev/null +++ b/src/eccryptoverify.cpp @@ -0,0 +1,68 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2015 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "eccryptoverify.h" + +namespace { + +int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) { + while (c1len > c2len) { + if (*c1) + return 1; + c1++; + c1len--; + } + while (c2len > c1len) { + if (*c2) + return -1; + c2++; + c2len--; + } + while (c1len > 0) { + if (*c1 > *c2) + return 1; + if (*c2 > *c1) + return -1; + c1++; + c2++; + c1len--; + } + return 0; +} + +/** Order of secp256k1's generator minus 1. */ +const unsigned char vchMaxModOrder[32] = { + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFE, + 0xBA,0xAE,0xDC,0xE6,0xAF,0x48,0xA0,0x3B, + 0xBF,0xD2,0x5E,0x8C,0xD0,0x36,0x41,0x40 +}; + +/** Half of the order of secp256k1's generator minus 1. */ +const unsigned char vchMaxModHalfOrder[32] = { + 0x7F,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0x5D,0x57,0x6E,0x73,0x57,0xA4,0x50,0x1D, + 0xDF,0xE9,0x2F,0x46,0x68,0x1B,0x20,0xA0 +}; + +const unsigned char vchZero[1] = {0}; +} // anon namespace + +namespace eccrypto { + +bool Check(const unsigned char *vch) { + return vch && + CompareBigEndian(vch, 32, vchZero, 0) > 0 && + CompareBigEndian(vch, 32, vchMaxModOrder, 32) <= 0; +} + +bool CheckSignatureElement(const unsigned char *vch, int len, bool half) { + return vch && + CompareBigEndian(vch, len, vchZero, 0) > 0 && + CompareBigEndian(vch, len, half ? vchMaxModHalfOrder : vchMaxModOrder, 32) <= 0; +} + +} // namespace eccrypto diff --git a/src/eccryptoverify.h b/src/eccryptoverify.h new file mode 100644 index 0000000..cb16e37 --- /dev/null +++ b/src/eccryptoverify.h @@ -0,0 +1,21 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2015 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_ECCRYPTOVERIFY_H +#define BITCOIN_ECCRYPTOVERIFY_H + +#include +#include + +class uint256; + +namespace eccrypto { + +bool Check(const unsigned char *vch); +bool CheckSignatureElement(const unsigned char *vch, int len, bool half); + +} // eccrypto namespace + +#endif // BITCOIN_ECCRYPTOVERIFY_H diff --git a/src/eckey.cpp b/src/eckey.cpp new file mode 100644 index 0000000..ff87ed1 --- /dev/null +++ b/src/eckey.cpp @@ -0,0 +1,318 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2013 The Bitcoin developers +// Copyright (c) 2014-2015 The ShadowCoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file license.txt or http://www.opensource.org/licenses/mit-license.php. + +#include "eckey.h" + +// anonymous namespace with local implementation code (OpenSSL interaction) +namespace { + +// Generate a private key from just the secret parameter +int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key) +{ + int ok = 0; + BN_CTX *ctx = NULL; + EC_POINT *pub_key = NULL; + + if (!eckey) return 0; + + const EC_GROUP *group = EC_KEY_get0_group(eckey); + + if ((ctx = BN_CTX_new()) == NULL) + goto err; + + pub_key = EC_POINT_new(group); + + if (pub_key == NULL) + goto err; + + if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx)) + goto err; + + EC_KEY_set_private_key(eckey,priv_key); + EC_KEY_set_public_key(eckey,pub_key); + + ok = 1; + +err: + + if (pub_key) + EC_POINT_free(pub_key); + if (ctx != NULL) + BN_CTX_free(ctx); + + return(ok); +} + +// Perform ECDSA key recovery (see SEC1 4.1.6) for curves over (mod p)-fields +// recid selects which key is recovered +// if check is non-zero, additional checks are performed +int ECDSA_SIG_recover_key_GFp(EC_KEY *eckey, ECDSA_SIG *ecsig, const unsigned char *msg, int msglen, int recid, int check) +{ + if (!eckey) return 0; + + int ret = 0; + BN_CTX *ctx = NULL; + + BIGNUM *x = NULL; + BIGNUM *e = NULL; + BIGNUM *order = NULL; + BIGNUM *sor = NULL; + BIGNUM *eor = NULL; + BIGNUM *field = NULL; + EC_POINT *R = NULL; + EC_POINT *O = NULL; + EC_POINT *Q = NULL; + BIGNUM *rr = NULL; + BIGNUM *zero = NULL; + int n = 0; + int i = recid / 2; + + const EC_GROUP *group = EC_KEY_get0_group(eckey); + if ((ctx = BN_CTX_new()) == NULL) { ret = -1; goto err; } + BN_CTX_start(ctx); + order = BN_CTX_get(ctx); + if (!EC_GROUP_get_order(group, order, ctx)) { ret = -2; goto err; } + x = BN_CTX_get(ctx); + if (!BN_copy(x, order)) { ret=-1; goto err; } + if (!BN_mul_word(x, i)) { ret=-1; goto err; } + if (!BN_add(x, x, ecsig->r)) { ret=-1; goto err; } + field = BN_CTX_get(ctx); + if (!EC_GROUP_get_curve_GFp(group, field, NULL, NULL, ctx)) { ret=-2; goto err; } + if (BN_cmp(x, field) >= 0) { ret=0; goto err; } + if ((R = EC_POINT_new(group)) == NULL) { ret = -2; goto err; } + if (!EC_POINT_set_compressed_coordinates_GFp(group, R, x, recid % 2, ctx)) { ret=0; goto err; } + if (check) + { + if ((O = EC_POINT_new(group)) == NULL) { ret = -2; goto err; } + if (!EC_POINT_mul(group, O, NULL, R, order, ctx)) { ret=-2; goto err; } + if (!EC_POINT_is_at_infinity(group, O)) { ret = 0; goto err; } + } + if ((Q = EC_POINT_new(group)) == NULL) { ret = -2; goto err; } + n = EC_GROUP_get_degree(group); + e = BN_CTX_get(ctx); + if (!BN_bin2bn(msg, msglen, e)) { ret=-1; goto err; } + if (8*msglen > n) BN_rshift(e, e, 8-(n & 7)); + zero = BN_CTX_get(ctx); + if (!BN_zero(zero)) { ret=-1; goto err; } + if (!BN_mod_sub(e, zero, e, order, ctx)) { ret=-1; goto err; } + rr = BN_CTX_get(ctx); + if (!BN_mod_inverse(rr, ecsig->r, order, ctx)) { ret=-1; goto err; } + sor = BN_CTX_get(ctx); + if (!BN_mod_mul(sor, ecsig->s, rr, order, ctx)) { ret=-1; goto err; } + eor = BN_CTX_get(ctx); + if (!BN_mod_mul(eor, e, rr, order, ctx)) { ret=-1; goto err; } + if (!EC_POINT_mul(group, Q, eor, R, sor, ctx)) { ret=-2; goto err; } + if (!EC_KEY_set_public_key(eckey, Q)) { ret=-2; goto err; } + + ret = 1; + +err: + if (ctx) { + BN_CTX_end(ctx); + BN_CTX_free(ctx); + } + if (R != NULL) EC_POINT_free(R); + if (O != NULL) EC_POINT_free(O); + if (Q != NULL) EC_POINT_free(Q); + return ret; +} + +}; // end of anonymous namespace + +void CECKey::GetSecretBytes(unsigned char vch[32]) const +{ + const BIGNUM *bn = EC_KEY_get0_private_key(pkey); + assert(bn); + int nBytes = BN_num_bytes(bn); + int n=BN_bn2bin(bn,&vch[32 - nBytes]); + assert(n == nBytes); + memset(vch, 0, 32 - nBytes); +} + +void CECKey::SetSecretBytes(const unsigned char vch[32]) +{ + BIGNUM bn; + BN_init(&bn); + assert(BN_bin2bn(vch, 32, &bn)); + assert(EC_KEY_regenerate_key(pkey, &bn)); + BN_clear_free(&bn); +} + +void CECKey::GetPrivKey(CPrivKey &privkey, bool fCompressed) { + EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED); + int nSize = i2d_ECPrivateKey(pkey, NULL); + assert(nSize); + privkey.resize(nSize); + unsigned char* pbegin = &privkey[0]; + int nSize2 = i2d_ECPrivateKey(pkey, &pbegin); + assert(nSize == nSize2); +} + +bool CECKey::SetPrivKey(const CPrivKey &privkey, bool fSkipCheck) { + const unsigned char* pbegin = &privkey[0]; + if (d2i_ECPrivateKey(&pkey, &pbegin, privkey.size())) { + if(fSkipCheck) + return true; + + // d2i_ECPrivateKey returns true if parsing succeeds. + // This doesn't necessarily mean the key is valid. + if (EC_KEY_check_key(pkey)) + return true; + } + return false; +} + +void CECKey::GetPubKey(CPubKey &pubkey, bool fCompressed) { + EC_KEY_set_conv_form(pkey, fCompressed ? POINT_CONVERSION_COMPRESSED : POINT_CONVERSION_UNCOMPRESSED); + int nSize = i2o_ECPublicKey(pkey, NULL); + assert(nSize); + assert(nSize <= 65); + unsigned char c[65]; + unsigned char *pbegin = c; + int nSize2 = i2o_ECPublicKey(pkey, &pbegin); + assert(nSize == nSize2); + pubkey.Set(&c[0], &c[nSize]); +} + +bool CECKey::SetPubKey(const CPubKey &pubkey) { + const unsigned char* pbegin = pubkey.begin(); + return o2i_ECPublicKey(&pkey, &pbegin, pubkey.size()); +} + +bool CECKey::Sign(const uint256 &hash, std::vector& vchSig) { + vchSig.clear(); + ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey); + if (sig == NULL) + return false; + BN_CTX *ctx = BN_CTX_new(); + BN_CTX_start(ctx); + const EC_GROUP *group = EC_KEY_get0_group(pkey); + BIGNUM *order = BN_CTX_get(ctx); + BIGNUM *halforder = BN_CTX_get(ctx); + EC_GROUP_get_order(group, order, ctx); + BN_rshift1(halforder, order); + if (BN_cmp(sig->s, halforder) > 0) { + // enforce low S values, by negating the value (modulo the order) if above order/2. + BN_sub(sig->s, order, sig->s); + } + BN_CTX_end(ctx); + BN_CTX_free(ctx); + unsigned int nSize = ECDSA_size(pkey); + vchSig.resize(nSize); // Make sure it is big enough + unsigned char *pos = &vchSig[0]; + nSize = i2d_ECDSA_SIG(sig, &pos); + ECDSA_SIG_free(sig); + vchSig.resize(nSize); // Shrink to fit actual size + return true; +} + +bool CECKey::Verify(const uint256 &hash, const std::vector& vchSig) { + // -1 = error, 0 = bad sig, 1 = good + if (ECDSA_verify(0, (unsigned char*)&hash, sizeof(hash), &vchSig[0], vchSig.size(), pkey) != 1) + return false; + return true; +} + +bool CECKey::SignCompact(const uint256 &hash, unsigned char *p64, int &rec) { + bool fOk = false; + ECDSA_SIG *sig = ECDSA_do_sign((unsigned char*)&hash, sizeof(hash), pkey); + if (sig==NULL) + return false; + memset(p64, 0, 64); + int nBitsR = BN_num_bits(sig->r); + int nBitsS = BN_num_bits(sig->s); + if (nBitsR <= 256 && nBitsS <= 256) { + CPubKey pubkey; + GetPubKey(pubkey, true); + for (int i=0; i<4; i++) { + CECKey keyRec; + if (ECDSA_SIG_recover_key_GFp(keyRec.pkey, sig, (unsigned char*)&hash, sizeof(hash), i, 1) == 1) { + CPubKey pubkeyRec; + keyRec.GetPubKey(pubkeyRec, true); + if (pubkeyRec == pubkey) { + rec = i; + fOk = true; + break; + } + } + } + assert(fOk); + BN_bn2bin(sig->r,&p64[32-(nBitsR+7)/8]); + BN_bn2bin(sig->s,&p64[64-(nBitsS+7)/8]); + } + ECDSA_SIG_free(sig); + return fOk; +} + +// reconstruct public key from a compact signature +// This is only slightly more CPU intensive than just verifying it. +// If this function succeeds, the recovered public key is guaranteed to be valid +// (the signature is a valid signature of the given data for that key) +bool CECKey::Recover(const uint256 &hash, const unsigned char *p64, int rec) +{ + if (rec<0 || rec>=3) + return false; + ECDSA_SIG *sig = ECDSA_SIG_new(); + BN_bin2bn(&p64[0], 32, sig->r); + BN_bin2bn(&p64[32], 32, sig->s); + bool ret = ECDSA_SIG_recover_key_GFp(pkey, sig, (unsigned char*)&hash, sizeof(hash), rec, 0) == 1; + ECDSA_SIG_free(sig); + return ret; +} + +bool CECKey::TweakPublic(const unsigned char vchTweak[32]) +{ + bool ret = true; + BN_CTX *ctx = BN_CTX_new(); + BN_CTX_start(ctx); + BIGNUM *bnTweak = BN_CTX_get(ctx); + BIGNUM *bnOrder = BN_CTX_get(ctx); + BIGNUM *bnOne = BN_CTX_get(ctx); + const EC_GROUP *group = EC_KEY_get0_group(pkey); + EC_GROUP_get_order(group, bnOrder, ctx); // what a grossly inefficient way to get the (constant) group order... + BN_bin2bn(vchTweak, 32, bnTweak); + if (BN_cmp(bnTweak, bnOrder) >= 0) + ret = false; // extremely unlikely + EC_POINT *point = EC_POINT_dup(EC_KEY_get0_public_key(pkey), group); + BN_one(bnOne); + EC_POINT_mul(group, point, bnTweak, point, bnOne, ctx); + if (EC_POINT_is_at_infinity(group, point)) + ret = false; // ridiculously unlikely + EC_KEY_set_public_key(pkey, point); + EC_POINT_free(point); + BN_CTX_end(ctx); + BN_CTX_free(ctx); + return ret; +} + +bool TweakSecret(unsigned char vchSecretOut[32], const unsigned char vchSecretIn[32], const unsigned char vchTweak[32]) +{ + bool ret = true; + BN_CTX *ctx = BN_CTX_new(); + BN_CTX_start(ctx); + BIGNUM *bnSecret = BN_CTX_get(ctx); + BIGNUM *bnTweak = BN_CTX_get(ctx); + BIGNUM *bnOrder = BN_CTX_get(ctx); + EC_GROUP *group = EC_GROUP_new_by_curve_name(NID_secp256k1); + EC_GROUP_get_order(group, bnOrder, ctx); // what a grossly inefficient way to get the (constant) group order... + BN_bin2bn(vchTweak, 32, bnTweak); + if (BN_cmp(bnTweak, bnOrder) >= 0) + ret = false; // extremely unlikely + BN_bin2bn(vchSecretIn, 32, bnSecret); + BN_add(bnSecret, bnSecret, bnTweak); + BN_nnmod(bnSecret, bnSecret, bnOrder, ctx); + if (BN_is_zero(bnSecret)) + ret = false; // ridiculously unlikely + int nBits = BN_num_bits(bnSecret); + memset(vchSecretOut, 0, 32); + BN_bn2bin(bnSecret, &vchSecretOut[32-(nBits+7)/8]); + EC_GROUP_free(group); + BN_CTX_end(ctx); + BN_CTX_free(ctx); + return ret; +} + + diff --git a/src/eckey.h b/src/eckey.h new file mode 100644 index 0000000..555aaca --- /dev/null +++ b/src/eckey.h @@ -0,0 +1,67 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2013 The Bitcoin developers +// Copyright (c) 2014-2015 The ShadowCoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file license.txt or http://www.opensource.org/licenses/mit-license.php. + +#ifndef CEC_KEY_H +#define CEC_KEY_H + +#include +#include +#include +#include + +#include "key.h" + +// RAII Wrapper around OpenSSL's EC_KEY +class CECKey { +private: + EC_KEY *pkey; + +public: + CECKey() { + pkey = EC_KEY_new_by_curve_name(NID_secp256k1); + assert(pkey != NULL); + } + + ~CECKey() { + EC_KEY_free(pkey); + } + + EC_KEY* GetECKey() {return pkey;}; + + void GetSecretBytes(unsigned char vch[32]) const; + + void SetSecretBytes(const unsigned char vch[32]); + + void GetPrivKey(CPrivKey &privkey, bool fCompressed); + + bool SetPrivKey(const CPrivKey &privkey, bool fSkipCheck=false); + + void GetPubKey(CPubKey &pubkey, bool fCompressed); + + bool SetPubKey(const CPubKey &pubkey); + + bool Sign(const uint256 &hash, std::vector& vchSig); + + bool Verify(const uint256 &hash, const std::vector& vchSig); + + bool SignCompact(const uint256 &hash, unsigned char *p64, int &rec); + + // reconstruct public key from a compact signature + // This is only slightly more CPU intensive than just verifying it. + // If this function succeeds, the recovered public key is guaranteed to be valid + // (the signature is a valid signature of the given data for that key) + bool Recover(const uint256 &hash, const unsigned char *p64, int rec); + + bool TweakPublic(const unsigned char vchTweak[32]); +}; + +bool TweakSecret(unsigned char vchSecretOut[32], const unsigned char vchSecretIn[32], const unsigned char vchTweak[32]); + + + +#endif + + diff --git a/src/hash.h b/src/hash.h index c395249..a5b56a3 100644 --- a/src/hash.h +++ b/src/hash.h @@ -11,6 +11,60 @@ #include #include +#include "crypto/ripemd160.h" +#include "crypto/sha256.h" + +#include + +/** A hasher class for Genius's 256-bit hash (double SHA-256). */ +class CHash256 { +private: + CSHA256 sha; +public: + static const size_t OUTPUT_SIZE = CSHA256::OUTPUT_SIZE; + + void Finalize(unsigned char hash[OUTPUT_SIZE]) { + unsigned char buf[sha.OUTPUT_SIZE]; + sha.Finalize(buf); + sha.Reset().Write(buf, sha.OUTPUT_SIZE).Finalize(hash); + } + + CHash256& Write(const unsigned char *data, size_t len) { + sha.Write(data, len); + return *this; + } + + CHash256& Reset() { + sha.Reset(); + return *this; + } +}; + +/** A hasher class for Genius's 160-bit hash (SHA-256 + RIPEMD-160). */ +class CHash160 { +private: + CSHA256 sha; +public: + static const size_t OUTPUT_SIZE = CRIPEMD160::OUTPUT_SIZE; + + void Finalize(unsigned char hash[OUTPUT_SIZE]) { + unsigned char buf[sha.OUTPUT_SIZE]; + sha.Finalize(buf); + CRIPEMD160().Write(buf, sha.OUTPUT_SIZE).Finalize(hash); + } + + CHash160& Write(const unsigned char *data, size_t len) { + sha.Write(data, len); + return *this; + } + + CHash160& Reset() { + sha.Reset(); + return *this; + } +}; + + template inline uint256 Hash(const T1 pbegin, const T1 pend) { diff --git a/src/init.cpp b/src/init.cpp index 66773ab..e12c0ee 100644 --- a/src/init.cpp +++ b/src/init.cpp @@ -12,6 +12,10 @@ #include "util.h" #include "ui_interface.h" #include "checkpoints.h" +#include "activemasternode.h" +#include "spork.h" +#include "smessage.h" + #ifdef ENABLE_WALLET #include "wallet.h" #include "walletdb.h" @@ -42,6 +46,8 @@ unsigned int nNodeLifespan; unsigned int nDerivationMethodIndex; unsigned int nMinerSleep; bool fUseFastIndex; +bool fOnlyTor = false; + enum Checkpoints::CPMode CheckpointsMode; ////////////////////////////////////////////////////////////////////////////// @@ -95,6 +101,8 @@ void Shutdown() RenameThread("genius-shutoff"); mempool.AddTransactionsUpdated(1); StopRPCThreads(); + SecureMsgShutdown(); + #ifdef ENABLE_WALLET ShutdownRPCMining(); if (pwalletMain) @@ -260,6 +268,28 @@ std::string HelpMessage() strUsage += " -rpcsslcertificatechainfile= " + _("Server certificate file (default: server.cert)") + "\n"; strUsage += " -rpcsslprivatekeyfile= " + _("Server private key (default: server.pem)") + "\n"; strUsage += " -rpcsslciphers= " + _("Acceptable ciphers (default: TLSv1.2+HIGH:TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!3DES:@STRENGTH)") + "\n"; + strUsage += " -litemode= " + _("Disable all Masternode and Darksend related functionality (0-1, default: 0)") + "\n"; +strUsage += "\n" + _("Masternode options:") + "\n"; + strUsage += " -masternode= " + _("Enable the client to act as a masternode (0-1, default: 0)") + "\n"; + strUsage += " -mnconf= " + _("Specify masternode configuration file (default: masternode.conf)") + "\n"; + strUsage += " -masternodeprivkey= " + _("Set the masternode private key") + "\n"; + strUsage += " -masternodeaddr= " + _("Set external address:port to get to this masternode (example: address:port)") + "\n"; + strUsage += " -masternodeminprotocol= " + _("Ignore masternodes less than version (example: 70007; default : 0)") + "\n"; + + strUsage += "\n" + _("Darksend options:") + "\n"; + strUsage += " -enabledarksend= " + _("Enable use of automated darksend for funds stored in this wallet (0-1, default: 0)") + "\n"; + strUsage += " -darksendrounds= " + _("Use N separate masternodes to anonymize funds (2-8, default: 2)") + "\n"; + strUsage += " -anonymizegeniusamount= " + _("Keep N Genius anonymized (default: 0)") + "\n"; + strUsage += " -liquidityprovider= " + _("Provide liquidity to Darksend by infrequently mixing coins on a continual basis (0-100, default: 0, 1=very frequent, high fees, 100=very infrequent, low fees)") + "\n"; + + strUsage += "\n" + _("InstantX options:") + "\n"; + strUsage += " -enableinstantx= " + _("Enable instantx, show confirmations for locked transactions (bool, default: true)") + "\n"; + strUsage += " -instantxdepth= " + _("Show N confirmations for a successfully locked transaction (0-9999, default: 1)") + "\n"; + strUsage += _("Secure messaging options:") + "\n" + + " -nosmsg " + _("Disable secure messaging.") + "\n" + + " -debugsmsg " + _("Log extra debug messages.") + "\n" + + " -smsgscanchain " + _("Scan the block chain for public key addresses on startup.") + "\n"; + return strUsage; } @@ -409,6 +439,16 @@ bool AppInit2(boost::thread_group& threadGroup) if (GetBoolArg("-nodebug", false) || find(categories.begin(), categories.end(), string("0")) != categories.end()) fDebug = false; + if(fDebug) + { + fDebugSmsg = true; + } else + { + fDebugSmsg = GetBoolArg("-debugsmsg", false); + } + fNoSmsg = GetBoolArg("-nosmsg", false); + + // Check for -debugnet (deprecated) if (GetBoolArg("-debugnet", false)) InitWarning(_("Warning: Deprecated argument -debugnet ignored, use -debug=net")); @@ -491,6 +531,17 @@ bool AppInit2(boost::thread_group& threadGroup) LogPrintf("Used data directory %s\n", strDataDir); std::ostringstream strErrors; + if (mapArgs.count("-masternodepaymentskey")) // masternode payments priv key + { + if (!masternodePayments.SetPrivKey(GetArg("-masternodepaymentskey", ""))) + return InitError(_("Unable to sign masternode payment winner, wrong key?")); + if (!sporkManager.SetPrivKey(GetArg("-masternodepaymentskey", ""))) + return InitError(_("Unable to sign spork message, wrong key?")); + } + + //ignore masternodes below protocol version + CMasterNode::minProtoVersion = GetArg("-masternodeminprotocol", MIN_MN_PROTO_VERSION); + if (fDaemon) fprintf(stdout, "Genius server starting\n"); @@ -542,6 +593,7 @@ bool AppInit2(boost::thread_group& threadGroup) if (r == CDBEnv::RECOVER_FAIL) return InitError(_("wallet.dat corrupt, salvage failed")); } + } // (!fDisableWallet) #endif // ENABLE_WALLET // ********************************************************* Step 6: network initialization @@ -552,6 +604,9 @@ bool AppInit2(boost::thread_group& threadGroup) std::set nets; BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) { enum Network net = ParseNetwork(snet); + if(net == NET_TOR) + fOnlyTor = true; + if (net == NET_UNROUTABLE) return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet)); nets.insert(net); @@ -825,6 +880,10 @@ bool AppInit2(boost::thread_group& threadGroup) LogPrintf("Loaded %i addresses from peers.dat %dms\n", addrman.size(), GetTimeMillis() - nStart); + // ********************************************************* Step 10.1: startup secure messaging + + SecureMsgStart(fNoSmsg, GetBoolArg("-smsgscanchain", false)); + // ********************************************************* Step 11: start node if (!CheckDiskSpace()) @@ -833,8 +892,120 @@ bool AppInit2(boost::thread_group& threadGroup) if (!strErrors.str().empty()) return InitError(strErrors.str()); + fMasterNode = GetBoolArg("-masternode", false); + if(fMasterNode) { + LogPrintf("IS DARKSEND MASTER NODE\n"); + strMasterNodeAddr = GetArg("-masternodeaddr", ""); + + LogPrintf(" addr %s\n", strMasterNodeAddr.c_str()); + + if(!strMasterNodeAddr.empty()){ + CService addrTest = CService(strMasterNodeAddr); + if (!addrTest.IsValid()) { + return InitError("Invalid -masternodeaddr address: " + strMasterNodeAddr); + } + } + + strMasterNodePrivKey = GetArg("-masternodeprivkey", ""); + if(!strMasterNodePrivKey.empty()){ + std::string errorMessage; + + CKey key; + CPubKey pubkey; + + if(!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, key, pubkey)) + { + return InitError(_("Invalid masternodeprivkey. Please see documenation.")); + } + + activeMasternode.pubKeyMasternode = pubkey; + + } else { + return InitError(_("You must specify a masternodeprivkey in the configuration. Please see documentation for help.")); + } + } + + fEnableDarksend = GetBoolArg("-enabledarksend", false); + + nDarksendRounds = GetArg("-darksendrounds", 2); + if(nDarksendRounds > 16) nDarksendRounds = 16; + if(nDarksendRounds < 1) nDarksendRounds = 1; + + nLiquidityProvider = GetArg("-liquidityprovider", 0); //0-100 + if(nLiquidityProvider != 0) { + darkSendPool.SetMinBlockSpacing(std::min(nLiquidityProvider,100)*15); + fEnableDarksend = true; + nDarksendRounds = 99999; + } + + nAnonymizeGeniusAmount = GetArg("-anonymizegeniusamount", 0); + if(nAnonymizeGeniusAmount > 999999) nAnonymizeGeniusAmount = 999999; + if(nAnonymizeGeniusAmount < 2) nAnonymizeGeniusAmount = 2; + + bool fEnableInstantX = GetBoolArg("-enableinstantx", true); + if(fEnableInstantX){ + nInstantXDepth = GetArg("-instantxdepth", 5); + if(nInstantXDepth > 60) nInstantXDepth = 60; + if(nInstantXDepth < 0) nAnonymizeGeniusAmount = 0; + } else { + nInstantXDepth = 0; + } + + //lite mode disables all Masternode and Darksend related functionality + fLiteMode = GetBoolArg("-litemode", false); + if(fMasterNode && fLiteMode){ + return InitError("You can not start a masternode in litemode"); + } + + LogPrintf("fLiteMode %d\n", fLiteMode); + LogPrintf("nInstantXDepth %d\n", nInstantXDepth); + LogPrintf("Darksend rounds %d\n", nDarksendRounds); + LogPrintf("Anonymize Genius Amount %d\n", nAnonymizeGeniusAmount); + + /* Denominations + A note about convertability. Within Darksend pools, each denomination + is convertable to another. + For example: + 1GENIUS+1000 == (.1GENIUS+100)*10 + 10GENIUS+10000 == (1GENIUS+1000)*10 + */ + darkSendDenominations.push_back( (100000 * COIN)+100000000 ); + darkSendDenominations.push_back( (10000 * COIN)+10000000 ); + darkSendDenominations.push_back( (1000 * COIN)+1000000 ); + darkSendDenominations.push_back( (100 * COIN)+100000 ); + darkSendDenominations.push_back( (10 * COIN)+10000 ); + darkSendDenominations.push_back( (1 * COIN)+1000 ); + darkSendDenominations.push_back( (.1 * COIN)+100 ); + /* Disabled till we need them + darkSendDenominations.push_back( (.01 * COIN)+10 ); + darkSendDenominations.push_back( (.001 * COIN)+1 ); + */ + + darkSendPool.InitCollateralAddress(); + + threadGroup.create_thread(boost::bind(&ThreadCheckDarkSendPool)); + + + RandAddSeedPerfmon(); + // reindex addresses found in blockchain + if(GetBoolArg("-reindexaddr", false)) + { + uiInterface.InitMessage(_("Rebuilding address index...")); + CBlockIndex *pblockAddrIndex = pindexBest; + CTxDB txdbAddr("rw"); + while(pblockAddrIndex) + { + uiInterface.InitMessage(strprintf("Rebuilding address index, block %i", pblockAddrIndex->nHeight)); + bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true); + CBlock pblockAddr; + if(pblockAddr.ReadFromDisk(pblockAddrIndex, true)) + pblockAddr.RebuildAddressIndex(txdbAddr); + pblockAddrIndex = pblockAddrIndex->pprev; + } + } + //// debug print LogPrintf("mapBlockIndex.size() = %u\n", mapBlockIndex.size()); LogPrintf("nBestHeight = %d\n", nBestHeight); @@ -852,11 +1023,34 @@ bool AppInit2(boost::thread_group& threadGroup) if (fServer) StartRPCThreads(); + +BOOST_FOREACH(PAIRTYPE(std::string, CAdrenalineNodeConfig) adrenaline, pwalletMain->mapMyAdrenalineNodes) +{ + CAdrenalineNodeConfig c = adrenaline.second; + if(c.isLocal) + { + strMasterNodeAddr = c.sAddress; + strMasterNodePrivKey = c.sMasternodePrivKey; + + CKey keyds; + CPubKey pubkeyds; + std::string errorMessage; + if(!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, keyds, pubkeyds)) + { + return InitError("Invalid masternodeprivkey. Please see documenation."); + } + + activeMasternode.pubKeyMasternode = pubkeyds; + fMasterNode = true; + break; + } +} + #ifdef ENABLE_WALLET // Mine proof-of-stake blocks in the background if (!GetBoolArg("-staking", true)) LogPrintf("Staking disabled\n"); - else if (pwalletMain) + else if (pwalletMain && !fMasterNode) // don't stake if we are a local masternode threadGroup.create_thread(boost::bind(&ThreadStakeMiner, pwalletMain)); #endif @@ -866,6 +1060,11 @@ bool AppInit2(boost::thread_group& threadGroup) #ifdef ENABLE_WALLET if (pwalletMain) { + BOOST_FOREACH(PAIRTYPE(std::string, CAdrenalineNodeConfig) adrenaline, pwalletMain->mapMyAdrenalineNodes) + { + uiInterface.NotifyAdrenalineNodeChanged(adrenaline.second); + } + // Add wallet transactions that aren't already in a block to mapTransactions pwalletMain->ReacceptWalletTransactions(); diff --git a/src/init.h b/src/init.h index 90096d0..0d14b16 100644 --- a/src/init.h +++ b/src/init.h @@ -17,5 +17,6 @@ bool ShutdownRequested(); void Shutdown(); bool AppInit2(boost::thread_group& threadGroup); std::string HelpMessage(); +extern bool fOnlyTor; #endif diff --git a/src/instantx.cpp b/src/instantx.cpp new file mode 100644 index 0000000..62c2020 --- /dev/null +++ b/src/instantx.cpp @@ -0,0 +1,597 @@ + + + +#include "uint256.h" +#include "sync.h" +#include "net.h" +#include "key.h" +#include "util.h" +#include "base58.h" +#include "protocol.h" +#include "instantx.h" +#include "masternode.h" +#include "activemasternode.h" +#include "darksend.h" +#include "spork.h" +#include + +using namespace std; +using namespace boost; + +std::map mapTxLockReq; +std::map mapTxLockReqRejected; +std::map mapTxLockVote; +std::map mapTxLocks; +std::map mapLockedInputs; +std::map mapUnknownVotes; //track votes with no tx for DOS +int nCompleteTXLocks; + +//txlock - Locks transaction +// +//step 1.) Broadcast intention to lock transaction inputs, "txlreg", CTransaction +//step 2.) Top 10 masternodes, open connect to top 1 masternode. Send "txvote", CTransaction, Signature, Approve +//step 3.) Top 1 masternode, waits for 10 messages. Upon success, sends "txlock' + +void ProcessMessageInstantX(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) +{ + if(fLiteMode) return; //disable all darksend/masternode related functionality + if(!IsSporkActive(SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT)) return; + + if (strCommand == "txlreq") + { + //LogPrintf("ProcessMessageInstantX::txlreq\n"); + CDataStream vMsg(vRecv); + CTransaction tx; + vRecv >> tx; + + CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash()); + pfrom->AddInventoryKnown(inv); + + if(mapTxLockReq.count(tx.GetHash()) || mapTxLockReqRejected.count(tx.GetHash())){ + return; + } + + if(!IsIXTXValid(tx)){ + return; + } + + BOOST_FOREACH(const CTxOut o, tx.vout){ + if(!o.scriptPubKey.IsNormalPaymentScript()){ + printf ("ProcessMessageInstantX::txlreq - Invalid Script %s\n", tx.ToString().c_str()); + return; + } + } + + int nBlockHeight = CreateNewLock(tx); + + bool fMissingInputs = false; + CValidationState state; + + + //if (AcceptToMemoryPool(mempool, state, tx, true, &fMissingInputs)) + if (AcceptToMemoryPool(mempool, tx, true, &fMissingInputs)) + { + vector vInv; + vInv.push_back(inv); + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + pnode->PushMessage("inv", vInv); + + DoConsensusVote(tx, nBlockHeight); + + mapTxLockReq.insert(make_pair(tx.GetHash(), tx)); + + LogPrintf("ProcessMessageInstantX::txlreq - Transaction Lock Request: %s %s : accepted %s\n", + pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(), + tx.GetHash().ToString().c_str() + ); + + return; + + } else { + mapTxLockReqRejected.insert(make_pair(tx.GetHash(), tx)); + + // can we get the conflicting transaction as proof? + + LogPrintf("ProcessMessageInstantX::txlreq - Transaction Lock Request: %s %s : rejected %s\n", + pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(), + tx.GetHash().ToString().c_str() + ); + + BOOST_FOREACH(const CTxIn& in, tx.vin){ + if(!mapLockedInputs.count(in.prevout)){ + mapLockedInputs.insert(make_pair(in.prevout, tx.GetHash())); + } + } + + // resolve conflicts + std::map::iterator i = mapTxLocks.find(tx.GetHash()); + if (i != mapTxLocks.end()){ + //we only care if we have a complete tx lock + if((*i).second.CountSignatures() >= INSTANTX_SIGNATURES_REQUIRED){ + if(!CheckForConflictingLocks(tx)){ + LogPrintf("ProcessMessageInstantX::txlreq - Found Existing Complete IX Lock\n"); + + CValidationState state; + //DisconnectBlockAndInputs(state, tx); + mapTxLockReq.insert(make_pair(tx.GetHash(), tx)); + } + } + } + + return; + } + } + else if (strCommand == "txlvote") //InstantX Lock Consensus Votes + { + CConsensusVote ctx; + vRecv >> ctx; + + CInv inv(MSG_TXLOCK_VOTE, ctx.GetHash()); + pfrom->AddInventoryKnown(inv); + + if(mapTxLockVote.count(ctx.GetHash())){ + return; + } + + mapTxLockVote.insert(make_pair(ctx.GetHash(), ctx)); + + if(ProcessConsensusVote(ctx)){ + //Spam/Dos protection + /* + Masternodes will sometimes propagate votes before the transaction is known to the client. + This tracks those messages and allows it at the same rate of the rest of the network, if + a peer violates it, it will simply be ignored + */ + if(!mapTxLockReq.count(ctx.txHash) && !mapTxLockReqRejected.count(ctx.txHash)){ + if(!mapUnknownVotes.count(ctx.vinMasternode.prevout.hash)){ + mapUnknownVotes[ctx.vinMasternode.prevout.hash] = GetTime()+(60*10); + } + + if(mapUnknownVotes[ctx.vinMasternode.prevout.hash] > GetTime() && + mapUnknownVotes[ctx.vinMasternode.prevout.hash] - GetAverageVoteTime() > 60*10){ + LogPrintf("ProcessMessageInstantX::txlreq - masternode is spamming transaction votes: %s %s\n", + ctx.vinMasternode.ToString().c_str(), + ctx.txHash.ToString().c_str() + ); + return; + } else { + mapUnknownVotes[ctx.vinMasternode.prevout.hash] = GetTime()+(60*10); + } + } + vector vInv; + vInv.push_back(inv); + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + pnode->PushMessage("inv", vInv); + + } + + return; + } +} + +bool IsIXTXValid(const CTransaction& txCollateral){ + if(txCollateral.vout.size() < 1) return false; + if(txCollateral.nLockTime != 0) return false; + + int64_t nValueIn = 0; + int64_t nValueOut = 0; + bool missingTx = false; + + BOOST_FOREACH(const CTxOut o, txCollateral.vout) + nValueOut += o.nValue; + + BOOST_FOREACH(const CTxIn i, txCollateral.vin){ + CTransaction tx2; + uint256 hash; + //if(GetTransaction(i.prevout.hash, tx2, hash, true)){ + if(GetTransaction(i.prevout.hash, tx2, hash)){ + if(tx2.vout.size() > i.prevout.n) { + nValueIn += tx2.vout[i.prevout.n].nValue; + } + } else{ + missingTx = true; + } + } + + if(nValueOut > GetSporkValue(SPORK_2_MAX_VALUE)*COIN){ + if(fDebug) LogPrintf ("IsIXTXValid - Transaction value too high - %s\n", txCollateral.ToString().c_str()); + return false; + } + + if(missingTx){ + if(fDebug) LogPrintf ("IsIXTXValid - Unknown inputs in IX transaction - %s\n", txCollateral.ToString().c_str()); + /* + This happens sometimes for an unknown reason, so we'll return that it's a valid transaction. + If someone submits an invalid transaction it will be rejected by the network anyway and this isn't + very common, but we don't want to block IX just because the client can't figure out the fee. + */ + return true; + } + + if(nValueIn-nValueOut < COIN*0.01) { + if(fDebug) LogPrintf ("IsIXTXValid - did not include enough fees in transaction %d\n%s\n", nValueOut-nValueIn, txCollateral.ToString().c_str()); + return false; + } + + return true; +} + +int64_t CreateNewLock(CTransaction tx) +{ + + int64_t nTxAge = 0; + BOOST_REVERSE_FOREACH(CTxIn i, tx.vin){ + nTxAge = GetInputAge(i); + if(nTxAge < 6) + { + LogPrintf("CreateNewLock - Transaction not found / too new: %d / %s\n", nTxAge, tx.GetHash().ToString().c_str()); + return 0; + } + } + + /* + Use a blockheight newer than the input. + This prevents attackers from using transaction mallibility to predict which masternodes + they'll use. + */ + int nBlockHeight = (pindexBest->nHeight - nTxAge)+4; + + if (!mapTxLocks.count(tx.GetHash())){ + LogPrintf("CreateNewLock - New Transaction Lock %s !\n", tx.GetHash().ToString().c_str()); + + CTransactionLock newLock; + newLock.nBlockHeight = nBlockHeight; + newLock.nExpiration = GetTime()+(60*60); //locks expire after 15 minutes (6 confirmations) + newLock.nTimeout = GetTime()+(60*5); + newLock.txHash = tx.GetHash(); + mapTxLocks.insert(make_pair(tx.GetHash(), newLock)); + } else { + mapTxLocks[tx.GetHash()].nBlockHeight = nBlockHeight; + if(fDebug) LogPrintf("CreateNewLock - Transaction Lock Exists %s !\n", tx.GetHash().ToString().c_str()); + } + + return nBlockHeight; +} + +// check if we need to vote on this transaction +void DoConsensusVote(CTransaction& tx, int64_t nBlockHeight) +{ + if(!fMasterNode) return; + + int n = GetMasternodeRank(activeMasternode.vin, nBlockHeight, MIN_INSTANTX_PROTO_VERSION); + + if(n == -1) + { + if(fDebug) LogPrintf("InstantX::DoConsensusVote - Unknown Masternode\n"); + return; + } + + if(n > INSTANTX_SIGNATURES_TOTAL) + { + if(fDebug) LogPrintf("InstantX::DoConsensusVote - Masternode not in the top %d (%d)\n", INSTANTX_SIGNATURES_TOTAL, n); + return; + } + /* + nBlockHeight calculated from the transaction is the authoritive source + */ + + if(fDebug) LogPrintf("InstantX::DoConsensusVote - In the top %d (%d)\n", INSTANTX_SIGNATURES_TOTAL, n); + + CConsensusVote ctx; + ctx.vinMasternode = activeMasternode.vin; + ctx.txHash = tx.GetHash(); + ctx.nBlockHeight = nBlockHeight; + if(!ctx.Sign()){ + LogPrintf("InstantX::DoConsensusVote - Failed to sign consensus vote\n"); + return; + } + if(!ctx.SignatureValid()) { + LogPrintf("InstantX::DoConsensusVote - Signature invalid\n"); + return; + } + + mapTxLockVote[ctx.GetHash()] = ctx; + + CInv inv(MSG_TXLOCK_VOTE, ctx.GetHash()); + + vector vInv; + vInv.push_back(inv); + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes){ + pnode->PushMessage("inv", vInv); + } + +} + +//received a consensus vote +bool ProcessConsensusVote(CConsensusVote& ctx) +{ + int n = GetMasternodeRank(ctx.vinMasternode, ctx.nBlockHeight, MIN_INSTANTX_PROTO_VERSION); + + int x = GetMasternodeByVin(ctx.vinMasternode); + if(x != -1){ + if(fDebug) LogPrintf("InstantX::ProcessConsensusVote - Masternode ADDR %s %d\n", vecMasternodes[x].addr.ToString().c_str(), n); + } + + if(n == -1) + { + //can be caused by past versions trying to vote with an invalid protocol + if(fDebug) LogPrintf("InstantX::ProcessConsensusVote - Unknown Masternode\n"); + return false; + } + + if(n > INSTANTX_SIGNATURES_TOTAL) + { + if(fDebug) LogPrintf("InstantX::ProcessConsensusVote - Masternode not in the top %d (%d) - %s\n", INSTANTX_SIGNATURES_TOTAL, n, ctx.GetHash().ToString().c_str()); + return false; + } + + if(!ctx.SignatureValid()) { + LogPrintf("InstantX::ProcessConsensusVote - Signature invalid\n"); + //don't ban, it could just be a non-synced masternode + return false; + } + + if (!mapTxLocks.count(ctx.txHash)){ + LogPrintf("InstantX::ProcessConsensusVote - New Transaction Lock %s !\n", ctx.txHash.ToString().c_str()); + + CTransactionLock newLock; + newLock.nBlockHeight = 0; + newLock.nExpiration = GetTime()+(60*60); + newLock.nTimeout = GetTime()+(60*5); + newLock.txHash = ctx.txHash; + mapTxLocks.insert(make_pair(ctx.txHash, newLock)); + } else { + if(fDebug) LogPrintf("InstantX::ProcessConsensusVote - Transaction Lock Exists %s !\n", ctx.txHash.ToString().c_str()); + } + + //compile consessus vote + std::map::iterator i = mapTxLocks.find(ctx.txHash); + if (i != mapTxLocks.end()){ + (*i).second.AddSignature(ctx); + +#ifdef ENABLE_WALLET + if(pwalletMain){ + //when we get back signatures, we'll count them as requests. Otherwise the client will think it didn't propagate. + if(pwalletMain->mapRequestCount.count(ctx.txHash)) + pwalletMain->mapRequestCount[ctx.txHash]++; + } +#endif + + if(fDebug) LogPrintf("InstantX::ProcessConsensusVote - Transaction Lock Votes %d - %s !\n", (*i).second.CountSignatures(), ctx.GetHash().ToString().c_str()); + + if((*i).second.CountSignatures() >= INSTANTX_SIGNATURES_REQUIRED){ + if(fDebug) LogPrintf("InstantX::ProcessConsensusVote - Transaction Lock Is Complete %s !\n", (*i).second.GetHash().ToString().c_str()); + + CTransaction& tx = mapTxLockReq[ctx.txHash]; + if(!CheckForConflictingLocks(tx)){ + +#ifdef ENABLE_WALLET + if(pwalletMain){ + pwalletMain->UpdatedTransaction((*i).second.txHash); + nCompleteTXLocks++; + + } +#endif + + if(mapTxLockReq.count(ctx.txHash)){ + BOOST_FOREACH(const CTxIn& in, tx.vin){ + if(!mapLockedInputs.count(in.prevout)){ + mapLockedInputs.insert(make_pair(in.prevout, ctx.txHash)); + } + } + } + + // resolve conflicts + + //if this tx lock was rejected, we need to remove the conflicting blocks + if(mapTxLockReqRejected.count((*i).second.txHash)){ + CValidationState state; + //DisconnectBlockAndInputs(state, mapTxLockReqRejected[(*i).second.txHash]); + } + } + } + return true; + } + + + return false; +} + +bool CheckForConflictingLocks(CTransaction& tx) +{ + /* + It's possible (very unlikely though) to get 2 conflicting transaction locks approved by the network. + In that case, they will cancel each other out. + + Blocks could have been rejected during this time, which is OK. After they cancel out, the client will + rescan the blocks and find they're acceptable and then take the chain with the most work. + */ + BOOST_FOREACH(const CTxIn& in, tx.vin){ + if(mapLockedInputs.count(in.prevout)){ + if(mapLockedInputs[in.prevout] != tx.GetHash()){ + LogPrintf("InstantX::CheckForConflictingLocks - found two complete conflicting locks - removing both. %s %s", tx.GetHash().ToString().c_str(), mapLockedInputs[in.prevout].ToString().c_str()); + if(mapTxLocks.count(tx.GetHash())) mapTxLocks[tx.GetHash()].nExpiration = GetTime(); + if(mapTxLocks.count(mapLockedInputs[in.prevout])) mapTxLocks[mapLockedInputs[in.prevout]].nExpiration = GetTime(); + return true; + } + } + } + + return false; +} + +int64_t GetAverageVoteTime() +{ + std::map::iterator it = mapUnknownVotes.begin(); + int64_t total = 0; + int64_t count = 0; + + while(it != mapUnknownVotes.end()) { + total+= it->second; + count++; + it++; + } + + return total / count; +} + +void CleanTransactionLocksList() +{ + if(pindexBest == NULL) return; + + std::map::iterator it = mapTxLocks.begin(); + + while(it != mapTxLocks.end()) { + if(GetTime() > it->second.nExpiration){ //keep them for an hour + LogPrintf("Removing old transaction lock %s\n", it->second.txHash.ToString().c_str()); + + if(mapTxLockReq.count(it->second.txHash)){ + CTransaction& tx = mapTxLockReq[it->second.txHash]; + + BOOST_FOREACH(const CTxIn& in, tx.vin) + mapLockedInputs.erase(in.prevout); + + mapTxLockReq.erase(it->second.txHash); + mapTxLockReqRejected.erase(it->second.txHash); + + BOOST_FOREACH(CConsensusVote& v, it->second.vecConsensusVotes) + mapTxLockVote.erase(v.GetHash()); + } + + mapTxLocks.erase(it++); + } else { + it++; + } + } + +} + +uint256 CConsensusVote::GetHash() const +{ + return vinMasternode.prevout.hash + vinMasternode.prevout.n + txHash; +} + + +bool CConsensusVote::SignatureValid() +{ + std::string errorMessage; + std::string strMessage = txHash.ToString().c_str() + boost::lexical_cast(nBlockHeight); + //LogPrintf("verify strMessage %s \n", strMessage.c_str()); + + int n = GetMasternodeByVin(vinMasternode); + + if(n == -1) + { + LogPrintf("InstantX::CConsensusVote::SignatureValid() - Unknown Masternode\n"); + return false; + } + + //LogPrintf("verify addr %s \n", vecMasternodes[0].addr.ToString().c_str()); + //LogPrintf("verify addr %s \n", vecMasternodes[1].addr.ToString().c_str()); + //LogPrintf("verify addr %d %s \n", n, vecMasternodes[n].addr.ToString().c_str()); + + CScript pubkey; + pubkey =GetScriptForDestination(vecMasternodes[n].pubkey2.GetID()); + CTxDestination address1; + ExtractDestination(pubkey, address1); + CBitcoinAddress address2(address1); + //LogPrintf("verify pubkey2 %s \n", address2.ToString().c_str()); + + if(!darkSendSigner.VerifyMessage(vecMasternodes[n].pubkey2, vchMasterNodeSignature, strMessage, errorMessage)) { + LogPrintf("InstantX::CConsensusVote::SignatureValid() - Verify message failed\n"); + return false; + } + + return true; +} + +bool CConsensusVote::Sign() +{ + std::string errorMessage; + + CKey key2; + CPubKey pubkey2; + std::string strMessage = txHash.ToString().c_str() + boost::lexical_cast(nBlockHeight); + //LogPrintf("signing strMessage %s \n", strMessage.c_str()); + //LogPrintf("signing privkey %s \n", strMasterNodePrivKey.c_str()); + + if(!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, key2, pubkey2)) + { + LogPrintf("CActiveMasternode::RegisterAsMasterNode() - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage.c_str()); + return false; + } + + CScript pubkey; + pubkey =GetScriptForDestination(pubkey2.GetID()); + CTxDestination address1; + ExtractDestination(pubkey, address1); + CBitcoinAddress address2(address1); + //LogPrintf("signing pubkey2 %s \n", address2.ToString().c_str()); + + if(!darkSendSigner.SignMessage(strMessage, errorMessage, vchMasterNodeSignature, key2)) { + LogPrintf("CActiveMasternode::RegisterAsMasterNode() - Sign message failed"); + return false; + } + + if(!darkSendSigner.VerifyMessage(pubkey2, vchMasterNodeSignature, strMessage, errorMessage)) { + LogPrintf("CActiveMasternode::RegisterAsMasterNode() - Verify message failed"); + return false; + } + + return true; +} + + +bool CTransactionLock::SignaturesValid() +{ + + BOOST_FOREACH(CConsensusVote vote, vecConsensusVotes) + { + int n = GetMasternodeRank(vote.vinMasternode, vote.nBlockHeight, MIN_INSTANTX_PROTO_VERSION); + + if(n == -1) + { + LogPrintf("InstantX::DoConsensusVote - Unknown Masternode\n"); + return false; + } + + if(n > INSTANTX_SIGNATURES_TOTAL) + { + LogPrintf("InstantX::DoConsensusVote - Masternode not in the top %s\n", INSTANTX_SIGNATURES_TOTAL); + return false; + } + + if(!vote.SignatureValid()){ + LogPrintf("InstantX::CTransactionLock::SignaturesValid - Signature not valid\n"); + return false; + } + } + + return true; +} + +void CTransactionLock::AddSignature(CConsensusVote& cv) +{ + vecConsensusVotes.push_back(cv); +} + +int CTransactionLock::CountSignatures() +{ + /* + Only count signatures where the BlockHeight matches the transaction's blockheight. + The votes have no proof it's the correct blockheight + */ + + if(nBlockHeight == 0) return -1; + + int n = 0; + BOOST_FOREACH(CConsensusVote v, vecConsensusVotes){ + if(v.nBlockHeight == nBlockHeight){ + n++; + } + } + return n; +} diff --git a/src/instantx.h b/src/instantx.h new file mode 100644 index 0000000..3b3c173 --- /dev/null +++ b/src/instantx.h @@ -0,0 +1,99 @@ + +// Copyright (c) 2009-2012 The Darkcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. +#ifndef INSTANTX_H +#define INSTANTX_H + +#include "uint256.h" +#include "sync.h" +#include "net.h" +#include "key.h" +//#include "primitives/transaction.h" +#include "util.h" +//#include "script/script.h" +#include "script.h" +#include "base58.h" +#include "main.h" + +using namespace std; +using namespace boost; + +class CConsensusVote; +class CTransaction; +class CTransactionLock; + +extern map mapTxLockReq; +extern map mapTxLockReqRejected; +extern map mapTxLockVote; +extern map mapTxLocks; +extern std::map mapLockedInputs; +extern int nCompleteTXLocks; + + +int64_t CreateNewLock(CTransaction tx); + +bool IsIXTXValid(const CTransaction& txCollateral); + +// if two conflicting locks are approved by the network, they will cancel out +bool CheckForConflictingLocks(CTransaction& tx); + +void ProcessMessageInstantX(CNode* pfrom, std::string& strCommand, CDataStream& vRecv); + +//check if we need to vote on this transaction +void DoConsensusVote(CTransaction& tx, int64_t nBlockHeight); + +//process consensus vote message +bool ProcessConsensusVote(CConsensusVote& ctx); + +// keep transaction locks in memory for an hour +void CleanTransactionLocksList(); + +int64_t GetAverageVoteTime(); + +class CConsensusVote +{ +public: + CTxIn vinMasternode; + uint256 txHash; + int nBlockHeight; + std::vector vchMasterNodeSignature; + + uint256 GetHash() const; + + bool SignatureValid(); + bool Sign(); + + ADD_SERIALIZE_METHODS; + + template + inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { + unsigned int nSerSize = 0; + READWRITE(txHash); + READWRITE(vinMasternode); + READWRITE(vchMasterNodeSignature); + READWRITE(nBlockHeight); + } +}; + +class CTransactionLock +{ +public: + int nBlockHeight; + uint256 txHash; + std::vector vecConsensusVotes; + int nExpiration; + int nTimeout; + + bool SignaturesValid(); + int CountSignatures(); + void AddSignature(CConsensusVote& cv); + + uint256 GetHash() + { + return txHash; + } +}; + + +#endif diff --git a/src/irc.cpp b/src/irc.cpp deleted file mode 100644 index a549a6c..0000000 --- a/src/irc.cpp +++ /dev/null @@ -1,486 +0,0 @@ -// Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2012 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. - -#include "chainparams.h" -#include "irc.h" -#include "net.h" -#include "init.h" -#include "strlcpy.h" -#include "base58.h" -#include - -using namespace std; -using namespace boost; - - -int nGotIRCAddresses = 0; - -void ThreadIRCSeed2(); - - - - -#pragma pack(push, 1) -struct ircaddr -{ - struct in_addr ip; - short port; -}; -#pragma pack(pop) - -string EncodeAddress(const CService& addr) -{ - struct ircaddr tmp; - if (addr.GetInAddr(&tmp.ip)) - { - tmp.port = htons(addr.GetPort()); - - vector vch(UBEGIN(tmp), UEND(tmp)); - return string("u") + EncodeBase58Check(vch); - } - return ""; -} - -bool DecodeAddress(string str, CService& addr) -{ - vector vch; - if (!DecodeBase58Check(str.substr(1), vch)) - return false; - - struct ircaddr tmp; - if (vch.size() != sizeof(tmp)) - return false; - memcpy(&tmp, &vch[0], sizeof(tmp)); - - addr = CService(tmp.ip, ntohs(tmp.port)); - return true; -} - - - - - - -static bool Send(SOCKET hSocket, const char* pszSend) -{ - boost::this_thread::interruption_point(); - if (strstr(pszSend, "PONG") != pszSend) - LogPrintf("IRC SENDING: %s\n", pszSend); - const char* psz = pszSend; - const char* pszEnd = psz + strlen(psz); - while (psz < pszEnd) - { - boost::this_thread::interruption_point(); - int ret = send(hSocket, psz, pszEnd - psz, MSG_NOSIGNAL); - if (ret < 0) - return false; - psz += ret; - } - return true; -} - -bool RecvLineIRC(SOCKET hSocket, string& strLine) -{ - if(ShutdownRequested()) - return false; - - boost::this_thread::interruption_point(); - while (!ShutdownRequested()) - { - boost::this_thread::interruption_point(); - - bool fRet = RecvLine(hSocket, strLine); - - if(ShutdownRequested()) - { - LogPrintf("RecvLineIRC: shutdown requested\n"); - return false; - } - - boost::this_thread::interruption_point(); - if (fRet) - { - vector vWords; - ParseString(strLine, ' ', vWords); - if (vWords.size() >= 1 && vWords[0] == "PING") - { - strLine[1] = 'O'; - strLine += '\r'; - Send(hSocket, strLine.c_str()); - continue; - }; - }; - return fRet; - }; - - return false; -} - -int RecvUntil(SOCKET hSocket, const char* psz1, const char* psz2=NULL, const char* psz3=NULL, const char* psz4=NULL) -{ - boost::this_thread::interruption_point(); - while (!ShutdownRequested()) - { - if(ShutdownRequested()) - break; - - boost::this_thread::interruption_point(); - string strLine; - strLine.reserve(10000); - if (!RecvLineIRC(hSocket, strLine)) - return 0; - LogPrintf("IRC %s\n", strLine.c_str()); - if (psz1 && strLine.find(psz1) != string::npos) - return 1; - if (psz2 && strLine.find(psz2) != string::npos) - return 2; - if (psz3 && strLine.find(psz3) != string::npos) - return 3; - if (psz4 && strLine.find(psz4) != string::npos) - return 4; - } - - return 0; -} - -bool Wait(int nSeconds) -{ - if(ShutdownRequested()) - return false; - - boost::this_thread::interruption_point(); - LogPrintf("IRC waiting %d seconds to reconnect\n", nSeconds); - for (int i = 0; i < nSeconds; i++) - { - boost::this_thread::interruption_point(); - if(ShutdownRequested()) - return false; - - MilliSleep(1000); - } - return true; -} - -bool RecvCodeLine(SOCKET hSocket, const char* psz1, string& strRet) -{ - boost::this_thread::interruption_point(); - strRet.clear(); - while (!ShutdownRequested()) - { - if(ShutdownRequested()) - return false; - - boost::this_thread::interruption_point(); - - string strLine; - if (!RecvLineIRC(hSocket, strLine)) - return false; - - vector vWords; - ParseString(strLine, ' ', vWords); - if (vWords.size() < 2) - continue; - - if (vWords[1] == psz1) - { - LogPrintf("IRC %s\n", strLine.c_str()); - strRet = strLine; - return true; - } - } - - return false; -} - -bool GetIPFromIRC(SOCKET hSocket, string strMyName, CNetAddr& ipRet) -{ - boost::this_thread::interruption_point(); - Send(hSocket, strprintf("USERHOST %s\r", strMyName.c_str()).c_str()); - - string strLine; - if (!RecvCodeLine(hSocket, "302", strLine)) - return false; - - vector vWords; - ParseString(strLine, ' ', vWords); - if (vWords.size() < 4) - return false; - - string str = vWords[3]; - if (str.rfind("@") == string::npos) - return false; - string strHost = str.substr(str.rfind("@")+1); - - // Hybrid IRC used by lfnet always returns IP when you userhost yourself, - // but in case another IRC is ever used this should work. - LogPrintf("GetIPFromIRC() got userhost %s\n", strHost.c_str()); - CNetAddr addr(strHost, true); - if (!addr.IsValid()) - return false; - ipRet = addr; - - return true; -} - - - -void ThreadIRCSeed() -{ - // Make this thread recognisable as the IRC seeding thread - RenameThread("genius-ircseed"); - - try - { - ThreadIRCSeed2(); - } - catch (boost::thread_interrupted) - { - LogPrintf("irc thread interrupted.\n"); - } - catch (std::exception& e) - { - PrintExceptionContinue(&e, "ThreadIRCSeed()"); - } catch (...) - { - PrintExceptionContinue(NULL, "ThreadIRCSeed()"); - }; - - LogPrintf("ThreadIRCSeed exited\n"); -} - -void ThreadIRCSeed2() -{ - LogPrintf("ThreadIRCSeed2 start\n"); - - LogPrintf("Check if not ipv4\n"); - // Don't connect to IRC if we won't use IPv4 connections. - if (IsLimited(NET_IPV4)) - return; - - LogPrintf("Check if connect or nolisten\n"); - // ... or if we won't make outbound connections and won't accept inbound ones. - if (mapArgs.count("-connect") && fNoListen) - return; - - LogPrintf("Check if irc enabled\n"); - // ... or if IRC is not enabled. - if (!GetBoolArg("-irc", true)) - return; - - LogPrintf("ThreadIRCSeed started\n"); - int nErrorWait = 10; - int nRetryWait = 10; - int nNameRetry = 0; - - while (!ShutdownRequested()) - { - boost::this_thread::interruption_point(); - - CService addrConnect("92.243.23.21", 6667); // irc.lfnet.org - - CService addrIRC("irc.lfnet.org", 6667, true); - if (addrIRC.IsValid()) - addrConnect = addrIRC; - - SOCKET hSocket; - bool bProxyConnectionFailed = false; - int ntimeout = 1000; - if (!ConnectSocket(addrConnect, hSocket, ntimeout, &bProxyConnectionFailed)) - { - boost::this_thread::interruption_point(); - LogPrintf("IRC connect failed\n"); - nErrorWait = nErrorWait * 11 / 10; - if (Wait(nErrorWait += 60)) - continue; - else - return; - }; - - if (!RecvUntil(hSocket, "Found your hostname", "using your IP address instead", "Couldn't look up your hostname", "ignoring hostname")) - { - boost::this_thread::interruption_point(); - closesocket(hSocket); - hSocket = INVALID_SOCKET; - nErrorWait = nErrorWait * 11 / 10; - if (Wait(nErrorWait += 60)) - continue; - else - return; - }; - - CNetAddr addrIPv4("1.2.3.4"); // arbitrary IPv4 address to make GetLocal prefer IPv4 addresses - CService addrLocal; - string strMyName; - // Don't use our IP as our nick if we're not listening - // or if it keeps failing because the nick is already in use. - if (!fNoListen && GetLocal(addrLocal, &addrIPv4) && nNameRetry<3) - strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); - if (strMyName == "") - strMyName = strprintf("x%"PRIu64"", GetRand(1000000000)); - - Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); - Send(hSocket, strprintf("USER %s 8 * : %s\r", strMyName.c_str(), strMyName.c_str()).c_str()); - - int nRet = RecvUntil(hSocket, " 004 ", " 433 "); - if (nRet != 1) - { - closesocket(hSocket); - hSocket = INVALID_SOCKET; - if (nRet == 2) - { - LogPrintf("IRC name already in use\n"); - nNameRetry++; - Wait(10); - continue; - }; - nErrorWait = nErrorWait * 11 / 10; - boost::this_thread::interruption_point(); - if (Wait(nErrorWait += 60)) - continue; - else - return; - }; - - nNameRetry = 0; - MilliSleep(500); - - // Get our external IP from the IRC server and re-nick before joining the channel - CNetAddr addrFromIRC; - if (GetIPFromIRC(hSocket, strMyName, addrFromIRC)) - { - LogPrintf("GetIPFromIRC() returned %s\n", addrFromIRC.ToString().c_str()); - // Don't use our IP as our nick if we're not listening - if (!fNoListen && addrFromIRC.IsRoutable()) - { - // IRC lets you to re-nick - AddLocal(addrFromIRC, LOCAL_IRC); - strMyName = EncodeAddress(GetLocalAddress(&addrConnect)); - Send(hSocket, strprintf("NICK %s\r", strMyName.c_str()).c_str()); - }; - }; - - if (TestNet()) - { - Send(hSocket, "JOIN #geniuscoinTEST\r"); - Send(hSocket, "WHO #geniuscoinTEST\r"); - } else - { - LogPrintf("JOIN #geniuscoin\n"); - // randomly join #geniuscoin00-#geniuscoin05 - //int channel_number = GetRandInt(5); - - // Channel number is always 0 for initial release - int channel_number = 0; - Send(hSocket, strprintf("JOIN #geniuscoin%02d\r", channel_number).c_str()); - Send(hSocket, strprintf("WHO #geniuscoin%02d\r", channel_number).c_str()); - }; - - int64_t nStart = GetTime(); - string strLine; - strLine.reserve(10000); - while (!ShutdownRequested() && RecvLineIRC(hSocket, strLine)) - { - if(ShutdownRequested()) - break; - - boost::this_thread::interruption_point(); - - if (strLine.empty() || strLine.size() > 900 || strLine[0] != ':') - continue; - - vector vWords; - ParseString(strLine, ' ', vWords); - if (vWords.size() < 2) - continue; - - char pszName[10000]; - pszName[0] = '\0'; - - if (vWords[1] == "352" && vWords.size() >= 8) - { - // index 7 is limited to 16 characters - // could get full length name at index 10, but would be different from join messages - strlcpy(pszName, vWords[7].c_str(), sizeof(pszName)); - LogPrintf("IRC got who\n"); - }; - - if (vWords[1] == "JOIN" && vWords[0].size() > 1) - { - // :username!username@50000007.F000000B.90000002.IP JOIN :#channelname - strlcpy(pszName, vWords[0].c_str() + 1, sizeof(pszName)); - if (strchr(pszName, '!')) - *strchr(pszName, '!') = '\0'; - LogPrintf("IRC got join\n"); - }; - - if (pszName[0] == 'u') - { - CAddress addr; - if (DecodeAddress(pszName, addr)) - { - addr.nTime = GetAdjustedTime(); - if (addrman.Add(addr, addrConnect, 51 * 60)) - LogPrintf("IRC got new address: %s\n", addr.ToString().c_str()); - nGotIRCAddresses++; - } else - { - LogPrintf("IRC decode failed\n"); - }; - }; - - if(ShutdownRequested()) - break; - - boost::this_thread::interruption_point(); - }; - - if(ShutdownRequested()) - break; - - closesocket(hSocket); - hSocket = INVALID_SOCKET; - - if (GetTime() - nStart > 20 * 60) - { - nErrorWait /= 3; - nRetryWait /= 3; - }; - - nRetryWait = nRetryWait * 11 / 10; - boost::this_thread::interruption_point(); - - if(ShutdownRequested()) - break;; - - if (!Wait(nRetryWait += 60)) - return; - }; -} - - - - - - - - - - -#ifdef TEST -int main(int argc, char *argv[]) -{ - WSADATA wsadata; - if (WSAStartup(MAKEWORD(2,2), &wsadata) != NO_ERROR) - { - LogPrintf("Error at WSAStartup()\n"); - return false; - } - - ThreadIRCSeed(NULL); - - WSACleanup(); - return 0; -} -#endif diff --git a/src/irc.h b/src/irc.h deleted file mode 100644 index 9868a3b..0000000 --- a/src/irc.h +++ /dev/null @@ -1,12 +0,0 @@ -// Copyright (c) 2009-2010 Satoshi Nakamoto -// Copyright (c) 2009-2012 The Bitcoin developers -// Distributed under the MIT/X11 software license, see the accompanying -// file COPYING or http://www.opensource.org/licenses/mit-license.php. -#ifndef BITCOIN_IRC_H -#define BITCOIN_IRC_H - -void ThreadIRCSeed(); - -extern int nGotIRCAddresses; - -#endif diff --git a/src/keepass.cpp b/src/keepass.cpp new file mode 100644 index 0000000..274b9d0 --- /dev/null +++ b/src/keepass.cpp @@ -0,0 +1,494 @@ +// Copyright (c) 2014 The Darkcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "keepass.h" + +#include +#include +#include +#include +//#include + +#include "util.h" +//#include "random.h" +#include "serialize.h" +//#include "utilstrencodings.h" +#include "clientversion.h" +#include "json/json_spirit_writer_template.h" +#include "json/json_spirit_reader_template.h" +#include "rpcprotocol.h" +#include "script.h" +//#include "script/script.h" // Necessary to prevent compile errors due to forward declaration of +//CScript in serialize.h (included from crypter.h) +#include "wallet.h" + +using boost::asio::ip::tcp; + +CKeePassIntegrator keePassInt; + +CKeePassIntegrator::CKeePassIntegrator() + :sKeyBase64(" "), sKey(" "), sUrl(" ") // Prevent LockedPageManagerBase complaints +{ + sKeyBase64.clear(); // Prevent LockedPageManagerBase complaints + sKey.clear(); // Prevent LockedPageManagerBase complaints + sUrl.clear(); // Prevent LockedPageManagerBase complaints + bIsActive = false; + nPort = KEEPASS_KEEPASSHTTP_PORT; +} + +// Initialze from application context +void CKeePassIntegrator::init() +{ + bIsActive = GetBoolArg("-keepass", false); + nPort = boost::lexical_cast(GetArg("-keepassport", KEEPASS_KEEPASSHTTP_PORT)); + sKeyBase64 = SecureString(GetArg("-keepasskey", "").c_str()); + sKeePassId = GetArg("-keepassid", ""); + sKeePassEntryName = GetArg("-keepassname", ""); + // Convert key if available + if(sKeyBase64.size() > 0) + { + sKey = DecodeBase64Secure(sKeyBase64); + } + // Construct url if available + if(sKeePassEntryName.size() > 0) + { + sUrl = SecureString("http://"); + sUrl += SecureString(sKeePassEntryName.c_str()); + sUrl += SecureString("/"); + //sSubmitUrl = "http://"; + //sSubmitUrl += SecureString(sKeePassEntryName.c_str()); + } +} + +void CKeePassIntegrator::CKeePassRequest::addStrParameter(std::string sName, std::string sValue) +{ + requestObj.push_back(json_spirit::Pair(sName, sValue)); +} + +void CKeePassIntegrator::CKeePassRequest::addStrParameter(std::string sName, SecureString sValue) +{ + std::string sCipherValue; + + if(!EncryptAES256(sKey, sValue, sIV, sCipherValue)) + { + throw std::runtime_error("Unable to encrypt Verifier"); + } + + addStrParameter(sName, EncodeBase64(sCipherValue)); +} + +std::string CKeePassIntegrator::CKeePassRequest::getJson() +{ + return json_spirit::write_string(json_spirit::Value(requestObj), false); +} + +void CKeePassIntegrator::CKeePassRequest::init() +{ + SecureString sIVSecure = generateRandomKey(KEEPASS_CRYPTO_BLOCK_SIZE); + sIV = std::string(&sIVSecure[0], sIVSecure.size()); + // Generate Nonce, Verifier and RequestType + SecureString sNonceBase64Secure = EncodeBase64Secure(sIVSecure); + addStrParameter("Nonce", std::string(&sNonceBase64Secure[0], sNonceBase64Secure.size())); // Plain + addStrParameter("Verifier", sNonceBase64Secure); // Encoded + addStrParameter("RequestType", sType); +} + +void CKeePassIntegrator::CKeePassResponse::parseResponse(std::string sResponse) +{ + json_spirit::Value responseValue; + if(!json_spirit::read_string(sResponse, responseValue)) + { + throw std::runtime_error("Unable to parse KeePassHttp response"); + } + + responseObj = responseValue.get_obj(); + + // retrieve main values + bSuccess = json_spirit::find_value(responseObj, "Success").get_bool(); + sType = getStr("RequestType"); + sIV = DecodeBase64(getStr("Nonce")); +} + +std::string CKeePassIntegrator::CKeePassResponse::getStr(std::string sName) +{ + std::string sValue(json_spirit::find_value(responseObj, sName).get_str()); + return sValue; +} + +SecureString CKeePassIntegrator::CKeePassResponse::getSecureStr(std::string sName) +{ + std::string sValueBase64Encrypted(json_spirit::find_value(responseObj, sName).get_str()); + SecureString sValue; + try + { + sValue = decrypt(sValueBase64Encrypted); + } + catch (std::exception &e) + { + std::string sErrorMessage = "Exception occured while decrypting "; + sErrorMessage += sName + ": " + e.what(); + throw std::runtime_error(sErrorMessage); + } + return sValue; +} + +SecureString CKeePassIntegrator::CKeePassResponse::decrypt(std::string sValueBase64Encrypted) +{ + std::string sValueEncrypted = DecodeBase64(sValueBase64Encrypted); + SecureString sValue; + if(!DecryptAES256(sKey, sValueEncrypted, sIV, sValue)) + { + throw std::runtime_error("Unable to decrypt value."); + } + return sValue; +} + +std::vector CKeePassIntegrator::CKeePassResponse::getEntries() +{ + + std::vector vEntries; + + json_spirit::Array aEntries = json_spirit::find_value(responseObj, "Entries").get_array(); + for(json_spirit::Array::iterator it = aEntries.begin(); it != aEntries.end(); ++it) + { + SecureString sEntryUuid(decrypt(json_spirit::find_value((*it).get_obj(), "Uuid").get_str().c_str())); + SecureString sEntryName(decrypt(json_spirit::find_value((*it).get_obj(), "Name").get_str().c_str())); + SecureString sEntryLogin(decrypt(json_spirit::find_value((*it).get_obj(), "Login").get_str().c_str())); + SecureString sEntryPassword(decrypt(json_spirit::find_value((*it).get_obj(), "Password").get_str().c_str())); + CKeePassEntry entry(sEntryUuid, sEntryUuid, sEntryLogin, sEntryPassword); + vEntries.push_back(entry); + } + + return vEntries; + +} + +SecureString CKeePassIntegrator::generateRandomKey(size_t nSize) +{ + // Generates random key + SecureString key; + key.resize(nSize); + + RandAddSeedPerfmon(); + RAND_bytes((unsigned char *) &key[0], nSize); + + return key; +} + +// Construct POST body for RPC JSON call +std::string CKeePassIntegrator::constructHTTPPost(const std::string& strMsg, const std::map& mapRequestHeaders) +{ + std::ostringstream s; + s << "POST / HTTP/1.1\r\n" + << "User-Agent: genius-json-rpc/" << FormatFullVersion() << "\r\n" + << "Host: localhost\r\n" + << "Content-Type: application/json\r\n" + << "Content-Length: " << strMsg.size() << "\r\n" + << "Connection: close\r\n" + << "Accept: application/json\r\n"; + BOOST_FOREACH(const PAIRTYPE(std::string, std::string)& item, mapRequestHeaders) + s << item.first << ": " << item.second << "\r\n"; + s << "\r\n" << strMsg; + + return s.str(); +} + +// Send RPC message to KeePassHttp +void CKeePassIntegrator::doHTTPPost(const std::string& sRequest, int& nStatus, std::string& sResponse) +{ + // Prepare communication + boost::asio::io_service io_service; + + // Get a list of endpoints corresponding to the server name. + tcp::resolver resolver(io_service); + tcp::resolver::query query(KEEPASS_KEEPASSHTTP_HOST, boost::lexical_cast(nPort)); + tcp::resolver::iterator endpoint_iterator = resolver.resolve(query); + tcp::resolver::iterator end; + + // Try each endpoint until we successfully establish a connection. + tcp::socket socket(io_service); + boost::system::error_code error = boost::asio::error::host_not_found; + while (error && endpoint_iterator != end) + { + socket.close(); + socket.connect(*endpoint_iterator++, error); + } + + if(error) + { + throw boost::system::system_error(error); + } + + // Form the request. + std::map mapRequestHeaders; + std::string strPost = constructHTTPPost(sRequest, mapRequestHeaders); + + // Logging of actual post data disabled as to not write passphrase in debug.log. Only enable temporarily when needed + //if(fDebug) LogPrintf("CKeePassIntegrator::doHTTPPost - send POST data: %s\n", strPost.c_str()); + if(fDebug) LogPrintf("CKeePassIntegrator::doHTTPPost - send POST data\n"); + + boost::asio::streambuf request; + std::ostream request_stream(&request); + request_stream << strPost; + + // Send the request. + boost::asio::write(socket, request); + + if(fDebug) LogPrintf("CKeePassIntegrator::doHTTPPost - request written\n"); + + // Read the response status line. The response streambuf will automatically + // grow to accommodate the entire line. The growth may be limited by passing + // a maximum size to the streambuf constructor. + boost::asio::streambuf response; + boost::asio::read_until(socket, response, "\r\n"); + + if(fDebug) LogPrintf("CKeePassIntegrator::doHTTPPost - request status line read\n"); + + // Receive HTTP reply status + int nProto = 0; + std::istream response_stream(&response); + nStatus = ReadHTTPStatus(response_stream, nProto); + + if(fDebug) LogPrintf("CKeePassIntegrator::doHTTPPost - reading response body start\n"); + // Read until EOF, writing data to output as we go. + while (boost::asio::read(socket, response, boost::asio::transfer_at_least(1), error)) + { + if (error != boost::asio::error::eof) + { + if (error != 0) + { // 0 is success + throw boost::system::system_error(error); + } + } + } + if(fDebug) LogPrintf("CKeePassIntegrator::doHTTPPost - reading response body end\n"); + + // Receive HTTP reply message headers and body + std::map mapHeaders; + ReadHTTPMessage(response_stream, mapHeaders, sResponse, nProto, MAX_SIZE); + if(fDebug) LogPrintf("CKeePassIntegrator::doHTTPPost - Processed body\n"); +} + +void CKeePassIntegrator::rpcTestAssociation(bool bTriggerUnlock) +{ + CKeePassRequest request(sKey, "test-associate"); + request.addStrParameter("TriggerUnlock", std::string(bTriggerUnlock ? "true" : "false")); + + int nStatus; + std::string sResponse; + + doHTTPPost(request.getJson(), nStatus, sResponse); + + if(fDebug) LogPrintf("CKeePassIntegrator::rpcTestAssociation - send result: status: %d response: %s\n", nStatus, sResponse.c_str()); +} + +std::vector CKeePassIntegrator::rpcGetLogins() +{ + + // Convert key format + SecureString sKey = DecodeBase64Secure(sKeyBase64); + + CKeePassRequest request(sKey, "get-logins"); + request.addStrParameter("addStrParameter", std::string("true")); + request.addStrParameter("TriggerUnlock", std::string("true")); + request.addStrParameter("Id", sKeePassId); + request.addStrParameter("Url", sUrl); + + int nStatus; + std::string sResponse; + + doHTTPPost(request.getJson(), nStatus, sResponse); + + // Logging of actual response data disabled as to not write passphrase in debug.log. Only enable temporarily when needed + //if(fDebug) LogPrintf("CKeePassIntegrator::rpcGetLogins - send result: status: %d response: %s\n", nStatus, sResponse.c_str()); + if(fDebug) LogPrintf("CKeePassIntegrator::rpcGetLogins - send result: status: %d\n", nStatus); + + if(nStatus != 200) + { + std::string sErrorMessage = "Error returned by KeePassHttp: HTTP code "; + sErrorMessage += boost::lexical_cast(nStatus); + sErrorMessage += " - Response: "; + sErrorMessage += " response: ["; + sErrorMessage += sResponse; + sErrorMessage += "]"; + throw std::runtime_error(sErrorMessage); + } + + // Parse the response + CKeePassResponse response(sKey, sResponse); + + if(!response.getSuccess()) + { + std::string sErrorMessage = "KeePassHttp returned failure status"; + throw std::runtime_error(sErrorMessage); + } + + return response.getEntries(); +} + +void CKeePassIntegrator::rpcSetLogin(const SecureString& strWalletPass, const SecureString& sEntryId) +{ + + // Convert key format + SecureString sKey = DecodeBase64Secure(sKeyBase64); + + CKeePassRequest request(sKey, "set-login"); + request.addStrParameter("Id", sKeePassId); + request.addStrParameter("Url", sUrl); + + if(fDebug) LogPrintf("CKeePassIntegrator::rpcSetLogin - send Url: %s\n", sUrl.c_str()); + + //request.addStrParameter("SubmitUrl", sSubmitUrl); // Is used to construct the entry title + request.addStrParameter("Login", SecureString("genius")); + request.addStrParameter("Password", strWalletPass); + if(sEntryId.size() != 0) + { + request.addStrParameter("Uuid", sEntryId); // Update existing + } + + int nStatus; + std::string sResponse; + + doHTTPPost(request.getJson(), nStatus, sResponse); + + + if(fDebug) LogPrintf("CKeePassIntegrator::rpcSetLogin - send result: status: %d response: %s\n", nStatus, sResponse.c_str()); + + if(nStatus != 200) + { + std::string sErrorMessage = "Error returned: HTTP code "; + sErrorMessage += boost::lexical_cast(nStatus); + sErrorMessage += " - Response: "; + sErrorMessage += " response: ["; + sErrorMessage += sResponse; + sErrorMessage += "]"; + throw std::runtime_error(sErrorMessage); + } + + // Parse the response + CKeePassResponse response(sKey, sResponse); + + if(!response.getSuccess()) + { + throw std::runtime_error("KeePassHttp returned failure status"); + } +} + + +SecureString CKeePassIntegrator::generateKeePassKey() +{ + SecureString sKey = generateRandomKey(KEEPASS_CRYPTO_KEY_SIZE); + SecureString sKeyBase64 = EncodeBase64Secure(sKey); + return sKeyBase64; +} + +void CKeePassIntegrator::rpcAssociate(std::string& sId, SecureString& sKeyBase64) +{ + sKey = generateRandomKey(KEEPASS_CRYPTO_KEY_SIZE); + CKeePassRequest request(sKey, "associate"); + + sKeyBase64 = EncodeBase64Secure(sKey); + request.addStrParameter("Key", std::string(&sKeyBase64[0], sKeyBase64.size())); + + int nStatus; + std::string sResponse; + + doHTTPPost(request.getJson(), nStatus, sResponse); + + if(fDebug) LogPrintf("CKeePassIntegrator::rpcAssociate - send result: status: %d response: %s\n", nStatus, sResponse.c_str()); + + if(nStatus != 200) + { + std::string sErrorMessage = "Error returned: HTTP code "; + sErrorMessage += boost::lexical_cast(nStatus); + sErrorMessage += " - Response: "; + sErrorMessage += " response: ["; + sErrorMessage += sResponse; + sErrorMessage += "]"; + throw std::runtime_error(sErrorMessage); + } + + // Parse the response + CKeePassResponse response(sKey, sResponse); + + if(!response.getSuccess()) + { + throw std::runtime_error("KeePassHttp returned failure status"); + } + + // If we got here, we were successful. Return the information + sId = response.getStr("Id"); +} + +// Retrieve wallet passphrase from KeePass +SecureString CKeePassIntegrator::retrievePassphrase() +{ + + // Check we have all required information + if(sKey.size() == 0) + { + throw std::runtime_error("keepasskey parameter is not defined. Please specify the configuration parameter."); + } + if(sKeePassId.size() == 0) + { + throw std::runtime_error("keepassid parameter is not defined. Please specify the configuration parameter."); + } + if(sKeePassEntryName == "") + { + throw std::runtime_error("keepassname parameter is not defined. Please specify the configuration parameter."); + } + + // Retrieve matching logins from KeePass + std::vector entries = rpcGetLogins(); + + // Only accept one unique match + if(entries.size() == 0) + { + throw std::runtime_error("KeePassHttp returned 0 matches, please verify the keepassurl setting."); + } + if(entries.size() > 1) + { + throw std::runtime_error("KeePassHttp returned multiple matches, bailing out."); + } + + return entries[0].getPassword(); +} + +// Update wallet passphrase in keepass +void CKeePassIntegrator::updatePassphrase(const SecureString& sWalletPassphrase) +{ + // Check we have all required information + if(sKey.size() == 0) + { + throw std::runtime_error("keepasskey parameter is not defined. Please specify the configuration parameter."); + } + if(sKeePassId.size() == 0) + { + throw std::runtime_error("keepassid parameter is not defined. Please specify the configuration parameter."); + } + if(sKeePassEntryName == "") + { + throw std::runtime_error("keepassname parameter is not defined. Please specify the configuration parameter."); + } + + SecureString sEntryId(""); + + std::string sErrorMessage; + + // Lookup existing entry + std::vector vEntries = rpcGetLogins(); + + if(vEntries.size() > 1) + { + throw std::runtime_error("KeePassHttp returned multiple matches, bailing out."); + } + + if(vEntries.size() == 1) + { + sEntryId = vEntries[0].getUuid(); + } + + // Update wallet passphrase in KeePass + rpcSetLogin(sWalletPassphrase, sEntryId); +} diff --git a/src/keepass.h b/src/keepass.h new file mode 100644 index 0000000..23af898 --- /dev/null +++ b/src/keepass.h @@ -0,0 +1,133 @@ +// Copyright (c) 2014 The Darkcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef _KEEPASS_H_ +#define _KEEPASS_H_ + +#define KEEPASS_CRYPTO_KEY_SIZE 32 +#define KEEPASS_CRYPTO_BLOCK_SIZE 16 +#define KEEPASS_KEEPASSHTTP_HOST "localhost" +#define KEEPASS_KEEPASSHTTP_PORT 19855 + +#include +#include +#include + +#include "json/json_spirit_value.h" + +#include "allocators.h" + +class CKeePassIntegrator { + + bool bIsActive; + unsigned int nPort; + SecureString sKeyBase64; + SecureString sKey; + SecureString sUrl; + //SecureString sSubmitUrl; + std::string sKeePassId; + std::string sKeePassEntryName; + + class CKeePassRequest { + + json_spirit::Object requestObj; + std::string sType; + std::string sIV; + SecureString sKey; + + void init(); + + public: + void addStrParameter(std::string sName, std::string sValue); // Regular + void addStrParameter(std::string sName, SecureString sValue); // Encrypt + std::string getJson(); + + CKeePassRequest(SecureString sKey, std::string sType) + { + this->sKey = sKey; + this->sType = sType; + init(); + }; + }; + + + class CKeePassEntry { + + SecureString uuid; + SecureString name; + SecureString login; + SecureString password; + + public: + CKeePassEntry(SecureString uuid, SecureString name, SecureString login, SecureString password) : + uuid(uuid), name(name), login(login), password(password) { + } + + SecureString getUuid() { + return uuid; + } + + SecureString getName() { + return name; + } + + SecureString getLogin() { + return login; + } + + SecureString getPassword() { + return password; + } + + }; + + + class CKeePassResponse { + + bool bSuccess; + std::string sType; + std::string sIV; + SecureString sKey; + + void parseResponse(std::string sResponse); + + public: + json_spirit::Object responseObj; + CKeePassResponse(SecureString sKey, std::string sResponse) { + this->sKey = sKey; + parseResponse(sResponse); + } + + bool getSuccess() { + return bSuccess; + } + + SecureString getSecureStr(std::string sName); + std::string getStr(std::string sName); + std::vector getEntries(); + + SecureString decrypt(std::string sValue); // DecodeBase64 and decrypt arbitrary string value + + }; + + static SecureString generateRandomKey(size_t nSize); + static std::string constructHTTPPost(const std::string& strMsg, const std::map& mapRequestHeaders); + void doHTTPPost(const std::string& sRequest, int& nStatus, std::string& sResponse); + void rpcTestAssociation(bool bTriggerUnlock); + std::vector rpcGetLogins(); + void rpcSetLogin(const SecureString& strWalletPass, const SecureString& sEntryId); + +public: + CKeePassIntegrator(); + void init(); + static SecureString generateKeePassKey(); + void rpcAssociate(std::string& sId, SecureString& sKeyBase64); + SecureString retrievePassphrase(); + void updatePassphrase(const SecureString& sWalletPassphrase); + +}; + +extern CKeePassIntegrator keePassInt; + +#endif diff --git a/src/key.cpp b/src/key.cpp index f72e36d..b435c82 100644 --- a/src/key.cpp +++ b/src/key.cpp @@ -2,16 +2,41 @@ // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. -#include +// NOTE: libsecp256k1 verification methods presently not working, +// so here, we include both openssl libs and libsecp256k1 +// to at least gain what we can from it. + #include #include #include +#include #include "key.h" +#ifdef USE_SECP256K1 +#include +#endif +//#else +//#include + +//#endif // anonymous namespace with local implementation code (OpenSSL interaction) namespace { +#ifdef USE_SECP256K1 +class CSecp256k1Init { +public: + secp256k1_context_t* ctx; + CSecp256k1Init() { + ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); + } + ~CSecp256k1Init() { + secp256k1_context_destroy(ctx); + } +}; +static CSecp256k1Init instance_of_csecp256k1; +#endif +//#else // Generate a private key from just the secret parameter int EC_KEY_regenerate_key(EC_KEY *eckey, BIGNUM *priv_key) @@ -330,6 +355,8 @@ class CECKey { } }; +//#endif + int CompareBigEndian(const unsigned char *c1, size_t c1len, const unsigned char *c2, size_t c2len) { while (c1len > c2len) { if (*c1) @@ -375,6 +402,7 @@ const unsigned char vchZero[0] = {}; }; // end of anonymous namespace + bool CKey::Check(const unsigned char *vch) { // Do not convert to OpenSSL's data structures for range-checking keys, // it's easy enough to do directly. @@ -439,10 +467,15 @@ void CKey::MakeNewKey(bool fCompressedIn) { } bool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) { +#ifdef USE_SECP256K1 + if (!secp256k1_ec_privkey_import(instance_of_csecp256k1.ctx, (unsigned char*)begin(), &privkey[0], privkey.size())) + return false; +#else CECKey key; if (!key.SetPrivKey(privkey)) return false; key.GetSecretBytes(vch); +#endif fCompressed = fCompressedIn; fValid = true; return true; @@ -450,50 +483,97 @@ bool CKey::SetPrivKey(const CPrivKey &privkey, bool fCompressedIn) { CPrivKey CKey::GetPrivKey() const { assert(fValid); + CPrivKey privkey; +#ifdef USE_SECP256K1 + privkey.resize(279); + int privkeylen = 279; + int ret = secp256k1_ec_privkey_export(instance_of_csecp256k1.ctx, begin(), (unsigned char*)&privkey[0], &privkeylen, fCompressed); + assert(ret); + privkey.resize(privkeylen); +#else CECKey key; key.SetSecretBytes(vch); - CPrivKey privkey; key.GetPrivKey(privkey, fCompressed); +#endif return privkey; } CPubKey CKey::GetPubKey() const { assert(fValid); + CPubKey pubkey; +#ifdef USE_SECP256K1 + int clen = 65; + int ret = secp256k1_ec_pubkey_create(instance_of_csecp256k1.ctx, (unsigned char*)pubkey.begin(), &clen, begin(), fCompressed); + assert(ret); + assert(pubkey.IsValid()); + assert((int)pubkey.size() == clen); +#else CECKey key; key.SetSecretBytes(vch); - CPubKey pubkey; key.GetPubKey(pubkey, fCompressed); +#endif return pubkey; } bool CKey::Sign(const uint256 &hash, std::vector& vchSig) const { if (!fValid) return false; +#ifdef USE_SECP256K1 + vchSig.resize(72); + int nSigLen = 72; + CKey nonce; + do { + nonce.MakeNewKey(true); + + if (secp256k1_ecdsa_sign(instance_of_csecp256k1.ctx, hash.begin(), (unsigned char*)&vchSig[0], &nSigLen, begin(), secp256k1_nonce_function_rfc6979, NULL)) + //if (secp256k1_ecdsa_sign((const unsigned char*)&hash, 32, (unsigned char*)&vchSig[0], &nSigLen, begin(), nonce.begin())) + + //if (secp256k1_ecdsa_sign((const unsigned char*)&hash, 32, vchSig.begin(), &nSigLen, begin(), nonce.begin())) + break; + } while(true); + vchSig.resize(nSigLen); + return true; +#else CECKey key; key.SetSecretBytes(vch); return key.Sign(hash, vchSig); +#endif } bool CKey::SignCompact(const uint256 &hash, std::vector& vchSig) const { if (!fValid) return false; - CECKey key; - key.SetSecretBytes(vch); vchSig.resize(65); int rec = -1; +#ifdef USE_SECP256K1 + CKey nonce; + do { + nonce.MakeNewKey(true); + if (int ret = secp256k1_ecdsa_sign_compact(instance_of_csecp256k1.ctx, hash.begin(), &vchSig[1], begin(), secp256k1_nonce_function_rfc6979, NULL, &rec)) + break; + } while(true); +#else + CECKey key; + key.SetSecretBytes(vch); if (!key.SignCompact(hash, &vchSig[1], rec)) return false; +#endif assert(rec != -1); vchSig[0] = 27 + rec + (fCompressed ? 4 : 0); return true; } bool CKey::Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck=false) { +#ifdef USE_SECP256K1 + if (!secp256k1_ec_privkey_import(instance_of_csecp256k1.ctx, (unsigned char*)begin(), &privkey[0], privkey.size())) + return false; +#else CECKey key; if (!key.SetPrivKey(privkey, fSkipCheck)) return false; key.GetSecretBytes(vch); +#endif fCompressed = vchPubKey.IsCompressed(); fValid = true; @@ -509,21 +589,37 @@ bool CKey::Load(CPrivKey &privkey, CPubKey &vchPubKey, bool fSkipCheck=false) { bool CPubKey::Verify(const uint256 &hash, const std::vector& vchSig) const { if (!IsValid()) return false; +/*#ifdef USE_SECP256K1 + if (secp256k1_ecdsa_verify(hash.begin(), 32, &vchSig[0], vchSig.size(), begin(), size()) != 1) + return false; +#else*/ CECKey key; if (!key.SetPubKey(*this)) return false; if (!key.Verify(hash, vchSig)) return false; +//#endif return true; } bool CPubKey::RecoverCompact(const uint256 &hash, const std::vector& vchSig) { if (vchSig.size() != 65) return false; + int recid = (vchSig[0] - 27) & 3; + bool fComp = (vchSig[0] - 27) & 4; +/*#ifdef USE_SECP256K1 + int pubkeylen = 65; + if (!secp256k1_ecdsa_recover_compact(hash.begin(), 32, &vchSig[1], begin(), &pubkeylen, fComp, recid)) + return false; + assert((int)size() == pubkeylen); +#else*/ CECKey key; - if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4)) + //if (!key.Recover(hash, &vchSig[1], (vchSig[0] - 27) & ~4)) + if (!key.Recover(hash, &vchSig[1], recid)) return false; - key.GetPubKey(*this, (vchSig[0] - 27) & 4); + //key.GetPubKey(*this, (vchSig[0] - 27) & 4); + key.GetPubKey(*this, fComp); +//#endif return true; } @@ -532,11 +628,20 @@ bool CPubKey::VerifyCompact(const uint256 &hash, const std::vector Raw() const { + std::vector r; + r.insert(r.end(), vch, vch+size()); + return r; + } }; // secure_allocator is defined in allocators.h // CPrivKey is a serialized private key, with all parameters included (279 bytes) typedef std::vector > CPrivKey; +// CSecret is a serialization of just the secret parameter (32 bytes) +typedef std::vector > CSecret; /** An encapsulated private key. */ class CKey { diff --git a/src/keystore.cpp b/src/keystore.cpp index 9a2bd97..de15eef 100644 --- a/src/keystore.cpp +++ b/src/keystore.cpp @@ -6,6 +6,7 @@ #include "keystore.h" #include "script.h" + bool CKeyStore::GetPubKey(const CKeyID &address, CPubKey &vchPubKeyOut) const { CKey key; @@ -53,3 +54,6 @@ bool CBasicKeyStore::GetCScript(const CScriptID &hash, CScript& redeemScriptOut) } return false; } + + + diff --git a/src/keystore.h b/src/keystore.h index e04d3e2..38fd142 100644 --- a/src/keystore.h +++ b/src/keystore.h @@ -8,6 +8,8 @@ #include "key.h" #include "sync.h" #include +#include "script.h" + class CScript; @@ -90,4 +92,6 @@ class CBasicKeyStore : public CKeyStore typedef std::map > > CryptedKeyMap; + + #endif diff --git a/src/lz4/LICENSE b/src/lz4/LICENSE new file mode 100644 index 0000000..b566df3 --- /dev/null +++ b/src/lz4/LICENSE @@ -0,0 +1,24 @@ +LZ4 Library +Copyright (c) 2011-2014, Yann Collet +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, +are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* 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. + +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. \ No newline at end of file diff --git a/src/lz4/lz4.c b/src/lz4/lz4.c new file mode 100644 index 0000000..fd229ef --- /dev/null +++ b/src/lz4/lz4.c @@ -0,0 +1,880 @@ +/* + LZ4 - Fast LZ compression algorithm + Copyright (C) 2011-2014, Yann Collet. + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + + 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 + OWNER 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. + + You can contact the author at : + - LZ4 source repository : http://code.google.com/p/lz4/ + - LZ4 public forum : https://groups.google.com/forum/#!forum/lz4c +*/ + +/************************************** + Tuning parameters +**************************************/ +/* + * MEMORY_USAGE : + * Memory usage formula : N->2^N Bytes (examples : 10 -> 1KB; 12 -> 4KB ; 16 -> 64KB; 20 -> 1MB; etc.) + * Increasing memory usage improves compression ratio + * Reduced memory usage can improve speed, due to cache effect + * Default value is 14, for 16KB, which nicely fits into Intel x86 L1 cache + */ +#define MEMORY_USAGE 14 + +/* + * HEAPMODE : + * Select how default compression functions will allocate memory for their hash table, + * in memory stack (0:default, fastest), or in memory heap (1:requires memory allocation (malloc)). + */ +#define HEAPMODE 0 + + +/************************************** + CPU Feature Detection +**************************************/ +/* 32 or 64 bits ? */ +#if (defined(__x86_64__) || defined(_M_X64) || defined(_WIN64) \ + || defined(__powerpc64__) || defined(__ppc64__) || defined(__PPC64__) \ + || defined(__64BIT__) || defined(_LP64) || defined(__LP64__) \ + || defined(__ia64) || defined(__itanium__) || defined(_M_IA64) ) /* Detects 64 bits mode */ +# define LZ4_ARCH64 1 +#else +# define LZ4_ARCH64 0 +#endif + +/* + * Little Endian or Big Endian ? + * Overwrite the #define below if you know your architecture endianess + */ +#if defined (__GLIBC__) +# include +# if (__BYTE_ORDER == __BIG_ENDIAN) +# define LZ4_BIG_ENDIAN 1 +# endif +#elif (defined(__BIG_ENDIAN__) || defined(__BIG_ENDIAN) || defined(_BIG_ENDIAN)) && !(defined(__LITTLE_ENDIAN__) || defined(__LITTLE_ENDIAN) || defined(_LITTLE_ENDIAN)) +# define LZ4_BIG_ENDIAN 1 +#elif defined(__sparc) || defined(__sparc__) \ + || defined(__powerpc__) || defined(__ppc__) || defined(__PPC__) \ + || defined(__hpux) || defined(__hppa) \ + || defined(_MIPSEB) || defined(__s390__) +# define LZ4_BIG_ENDIAN 1 +#else +/* Little Endian assumed. PDP Endian and other very rare endian format are unsupported. */ +#endif + +/* + * Unaligned memory access is automatically enabled for "common" CPU, such as x86. + * For others CPU, such as ARM, the compiler may be more cautious, inserting unnecessary extra code to ensure aligned access property + * If you know your target CPU supports unaligned memory access, you want to force this option manually to improve performance + */ +#if defined(__ARM_FEATURE_UNALIGNED) +# define LZ4_FORCE_UNALIGNED_ACCESS 1 +#endif + +/* Define this parameter if your target system or compiler does not support hardware bit count */ +#if defined(_MSC_VER) && defined(_WIN32_WCE) /* Visual Studio for Windows CE does not support Hardware bit count */ +# define LZ4_FORCE_SW_BITCOUNT +#endif + +/* + * BIG_ENDIAN_NATIVE_BUT_INCOMPATIBLE : + * This option may provide a small boost to performance for some big endian cpu, although probably modest. + * You may set this option to 1 if data will remain within closed environment. + * This option is useless on Little_Endian CPU (such as x86) + */ + +/* #define BIG_ENDIAN_NATIVE_BUT_INCOMPATIBLE 1 */ + + +/************************************** + Compiler Options +**************************************/ +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */ +/* "restrict" is a known keyword */ +#else +# define restrict /* Disable restrict */ +#endif + +#ifdef _MSC_VER /* Visual Studio */ +# define FORCE_INLINE static __forceinline +# include /* For Visual 2005 */ +# if LZ4_ARCH64 /* 64-bits */ +# pragma intrinsic(_BitScanForward64) /* For Visual 2005 */ +# pragma intrinsic(_BitScanReverse64) /* For Visual 2005 */ +# else /* 32-bits */ +# pragma intrinsic(_BitScanForward) /* For Visual 2005 */ +# pragma intrinsic(_BitScanReverse) /* For Visual 2005 */ +# endif +# pragma warning(disable : 4127) /* disable: C4127: conditional expression is constant */ +#else +# ifdef __GNUC__ +# define FORCE_INLINE static inline __attribute__((always_inline)) +# else +# define FORCE_INLINE static inline +# endif +#endif + +#ifdef _MSC_VER /* Visual Studio */ +# define lz4_bswap16(x) _byteswap_ushort(x) +#else +# define lz4_bswap16(x) ((unsigned short int) ((((x) >> 8) & 0xffu) | (((x) & 0xffu) << 8))) +#endif + +#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) + +#if (GCC_VERSION >= 302) || (__INTEL_COMPILER >= 800) || defined(__clang__) +# define expect(expr,value) (__builtin_expect ((expr),(value)) ) +#else +# define expect(expr,value) (expr) +#endif + +#define likely(expr) expect((expr) != 0, 1) +#define unlikely(expr) expect((expr) != 0, 0) + + +/************************************** + Memory routines +**************************************/ +#include /* malloc, calloc, free */ +#define ALLOCATOR(n,s) calloc(n,s) +#define FREEMEM free +#include /* memset, memcpy */ +#define MEM_INIT memset + + +/************************************** + Includes +**************************************/ +#include "lz4.h" + + +/************************************** + Basic Types +**************************************/ +#if defined (__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) /* C99 */ +# include + typedef uint8_t BYTE; + typedef uint16_t U16; + typedef uint32_t U32; + typedef int32_t S32; + typedef uint64_t U64; +#else + typedef unsigned char BYTE; + typedef unsigned short U16; + typedef unsigned int U32; + typedef signed int S32; + typedef unsigned long long U64; +#endif + +#if defined(__GNUC__) && !defined(LZ4_FORCE_UNALIGNED_ACCESS) +# define _PACKED __attribute__ ((packed)) +#else +# define _PACKED +#endif + +#if !defined(LZ4_FORCE_UNALIGNED_ACCESS) && !defined(__GNUC__) +# if defined(__IBMC__) || defined(__SUNPRO_C) || defined(__SUNPRO_CC) +# pragma pack(1) +# else +# pragma pack(push, 1) +# endif +#endif + +typedef struct { U16 v; } _PACKED U16_S; +typedef struct { U32 v; } _PACKED U32_S; +typedef struct { U64 v; } _PACKED U64_S; +typedef struct {size_t v;} _PACKED size_t_S; + +#if !defined(LZ4_FORCE_UNALIGNED_ACCESS) && !defined(__GNUC__) +# if defined(__SUNPRO_C) || defined(__SUNPRO_CC) +# pragma pack(0) +# else +# pragma pack(pop) +# endif +#endif + +#define A16(x) (((U16_S *)(x))->v) +#define A32(x) (((U32_S *)(x))->v) +#define A64(x) (((U64_S *)(x))->v) +#define AARCH(x) (((size_t_S *)(x))->v) + + +/************************************** + Constants +**************************************/ +#define LZ4_HASHLOG (MEMORY_USAGE-2) +#define HASHTABLESIZE (1 << MEMORY_USAGE) +#define HASHNBCELLS4 (1 << LZ4_HASHLOG) + +#define MINMATCH 4 + +#define COPYLENGTH 8 +#define LASTLITERALS 5 +#define MFLIMIT (COPYLENGTH+MINMATCH) +static const int LZ4_minLength = (MFLIMIT+1); + +#define KB *(1U<<10) +#define MB *(1U<<20) +#define GB *(1U<<30) + +#define LZ4_64KLIMIT ((64 KB) + (MFLIMIT-1)) +#define SKIPSTRENGTH 6 /* Increasing this value will make the compression run slower on incompressible data */ + +#define MAXD_LOG 16 +#define MAX_DISTANCE ((1 << MAXD_LOG) - 1) + +#define ML_BITS 4 +#define ML_MASK ((1U<=e; */ +#else +# define LZ4_WILDCOPY(d,s,e) { if (likely(e-d <= 8)) LZ4_COPY8(d,s) else do { LZ4_COPY8(d,s) } while (d>3); +# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (__builtin_clzll(val) >> 3); +# else + int r; + if (!(val>>32)) { r=4; } else { r=0; val>>=32; } + if (!(val>>16)) { r+=2; val>>=8; } else { val>>=24; } + r += (!val); + return r; +# endif +# else +# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) + unsigned long r = 0; + _BitScanForward64( &r, val ); + return (int)(r>>3); +# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (__builtin_ctzll(val) >> 3); +# else + static const int DeBruijnBytePos[64] = { 0, 0, 0, 0, 0, 1, 1, 2, 0, 3, 1, 3, 1, 4, 2, 7, 0, 2, 3, 6, 1, 5, 3, 5, 1, 3, 4, 4, 2, 5, 6, 7, 7, 0, 1, 2, 3, 3, 4, 6, 2, 6, 5, 5, 3, 4, 5, 6, 7, 1, 2, 4, 6, 4, 4, 5, 7, 2, 6, 5, 7, 6, 7, 7 }; + return DeBruijnBytePos[((U64)((val & -(long long)val) * 0x0218A392CDABBD3FULL)) >> 58]; +# endif +# endif +} + +#else + +FORCE_INLINE int LZ4_NbCommonBytes (register U32 val) +{ +# if defined(LZ4_BIG_ENDIAN) +# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) + unsigned long r = 0; + _BitScanReverse( &r, val ); + return (int)(r>>3); +# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (__builtin_clz(val) >> 3); +# else + int r; + if (!(val>>16)) { r=2; val>>=8; } else { r=0; val>>=24; } + r += (!val); + return r; +# endif +# else +# if defined(_MSC_VER) && !defined(LZ4_FORCE_SW_BITCOUNT) + unsigned long r; + _BitScanForward( &r, val ); + return (int)(r>>3); +# elif defined(__GNUC__) && (GCC_VERSION >= 304) && !defined(LZ4_FORCE_SW_BITCOUNT) + return (__builtin_ctz(val) >> 3); +# else + static const int DeBruijnBytePos[32] = { 0, 0, 3, 0, 3, 1, 3, 0, 3, 2, 2, 1, 3, 2, 0, 1, 3, 3, 1, 2, 2, 2, 2, 0, 3, 1, 2, 0, 1, 0, 1, 1 }; + return DeBruijnBytePos[((U32)((val & -(S32)val) * 0x077CB531U)) >> 27]; +# endif +# endif +} + +#endif + + +/**************************** + Compression functions +****************************/ +int LZ4_compressBound(int isize) { return LZ4_COMPRESSBOUND(isize); } + +FORCE_INLINE int LZ4_hashSequence(U32 sequence, tableType_t tableType) +{ + if (tableType == byU16) + return (((sequence) * 2654435761U) >> ((MINMATCH*8)-(LZ4_HASHLOG+1))); + else + return (((sequence) * 2654435761U) >> ((MINMATCH*8)-LZ4_HASHLOG)); +} + +FORCE_INLINE int LZ4_hashPosition(const BYTE* p, tableType_t tableType) { return LZ4_hashSequence(A32(p), tableType); } + +FORCE_INLINE void LZ4_putPositionOnHash(const BYTE* p, U32 h, void* tableBase, tableType_t tableType, const BYTE* srcBase) +{ + switch (tableType) + { + case byPtr: { const BYTE** hashTable = (const BYTE**) tableBase; hashTable[h] = p; break; } + case byU32: { U32* hashTable = (U32*) tableBase; hashTable[h] = (U32)(p-srcBase); break; } + case byU16: { U16* hashTable = (U16*) tableBase; hashTable[h] = (U16)(p-srcBase); break; } + } +} + +FORCE_INLINE void LZ4_putPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase) +{ + U32 h = LZ4_hashPosition(p, tableType); + LZ4_putPositionOnHash(p, h, tableBase, tableType, srcBase); +} + +FORCE_INLINE const BYTE* LZ4_getPositionOnHash(U32 h, void* tableBase, tableType_t tableType, const BYTE* srcBase) +{ + if (tableType == byPtr) { const BYTE** hashTable = (const BYTE**) tableBase; return hashTable[h]; } + if (tableType == byU32) { U32* hashTable = (U32*) tableBase; return hashTable[h] + srcBase; } + { U16* hashTable = (U16*) tableBase; return hashTable[h] + srcBase; } /* default, to ensure a return */ +} + +FORCE_INLINE const BYTE* LZ4_getPosition(const BYTE* p, void* tableBase, tableType_t tableType, const BYTE* srcBase) +{ + U32 h = LZ4_hashPosition(p, tableType); + return LZ4_getPositionOnHash(h, tableBase, tableType, srcBase); +} + + +FORCE_INLINE int LZ4_compress_generic( + void* ctx, + const char* source, + char* dest, + int inputSize, + int maxOutputSize, + + limitedOutput_directive limitedOutput, + tableType_t tableType, + prefix64k_directive prefix) +{ + const BYTE* ip = (const BYTE*) source; + const BYTE* const base = (prefix==withPrefix) ? ((LZ4_Data_Structure*)ctx)->base : (const BYTE*) source; + const BYTE* const lowLimit = ((prefix==withPrefix) ? ((LZ4_Data_Structure*)ctx)->bufferStart : (const BYTE*)source); + const BYTE* anchor = (const BYTE*) source; + const BYTE* const iend = ip + inputSize; + const BYTE* const mflimit = iend - MFLIMIT; + const BYTE* const matchlimit = iend - LASTLITERALS; + + BYTE* op = (BYTE*) dest; + BYTE* const oend = op + maxOutputSize; + + int length; + const int skipStrength = SKIPSTRENGTH; + U32 forwardH; + + /* Init conditions */ + if ((U32)inputSize > (U32)LZ4_MAX_INPUT_SIZE) return 0; /* Unsupported input size, too large (or negative) */ + if ((prefix==withPrefix) && (ip != ((LZ4_Data_Structure*)ctx)->nextBlock)) return 0; /* must continue from end of previous block */ + if (prefix==withPrefix) ((LZ4_Data_Structure*)ctx)->nextBlock=iend; /* do it now, due to potential early exit */ + if ((tableType == byU16) && (inputSize>=(int)LZ4_64KLIMIT)) return 0; /* Size too large (not within 64K limit) */ + if (inputSize> skipStrength; + ip = forwardIp; + forwardIp = ip + step; + + if (unlikely(forwardIp > mflimit)) { goto _last_literals; } + + forwardH = LZ4_hashPosition(forwardIp, tableType); + ref = LZ4_getPositionOnHash(h, ctx, tableType, base); + LZ4_putPositionOnHash(ip, h, ctx, tableType, base); + + } while ((ref + MAX_DISTANCE < ip) || (A32(ref) != A32(ip))); + + /* Catch up */ + while ((ip>anchor) && (ref > lowLimit) && (unlikely(ip[-1]==ref[-1]))) { ip--; ref--; } + + /* Encode Literal length */ + length = (int)(ip - anchor); + token = op++; + if ((limitedOutput) && (unlikely(op + length + (2 + 1 + LASTLITERALS) + (length/255) > oend))) return 0; /* Check output limit */ + if (length>=(int)RUN_MASK) + { + int len = length-RUN_MASK; + *token=(RUN_MASK<= 255 ; len-=255) *op++ = 255; + *op++ = (BYTE)len; + } + else *token = (BYTE)(length<>8) > oend))) return 0; /* Check output limit */ + if (length>=(int)ML_MASK) + { + *token += ML_MASK; + length -= ML_MASK; + for (; length > 509 ; length-=510) { *op++ = 255; *op++ = 255; } + if (length >= 255) { length-=255; *op++ = 255; } + *op++ = (BYTE)length; + } + else *token += (BYTE)(length); + + /* Test end of chunk */ + if (ip > mflimit) { anchor = ip; break; } + + /* Fill table */ + LZ4_putPosition(ip-2, ctx, tableType, base); + + /* Test next position */ + ref = LZ4_getPosition(ip, ctx, tableType, base); + LZ4_putPosition(ip, ctx, tableType, base); + if ((ref + MAX_DISTANCE >= ip) && (A32(ref) == A32(ip))) { token = op++; *token=0; goto _next_match; } + + /* Prepare next loop */ + anchor = ip++; + forwardH = LZ4_hashPosition(ip, tableType); + } + +_last_literals: + /* Encode Last Literals */ + { + int lastRun = (int)(iend - anchor); + if ((limitedOutput) && (((char*)op - dest) + lastRun + 1 + ((lastRun+255-RUN_MASK)/255) > (U32)maxOutputSize)) return 0; /* Check output limit */ + if (lastRun>=(int)RUN_MASK) { *op++=(RUN_MASK<= 255 ; lastRun-=255) *op++ = 255; *op++ = (BYTE) lastRun; } + else *op++ = (BYTE)(lastRun<hashTable, 0, sizeof(lz4ds->hashTable)); + lz4ds->bufferStart = base; + lz4ds->base = base; + lz4ds->nextBlock = base; +} + +int LZ4_resetStreamState(void* state, const char* inputBuffer) +{ + if ((((size_t)state) & 3) != 0) return 1; /* Error : pointer is not aligned on 4-bytes boundary */ + LZ4_init((LZ4_Data_Structure*)state, (const BYTE*)inputBuffer); + return 0; +} + +void* LZ4_create (const char* inputBuffer) +{ + void* lz4ds = ALLOCATOR(1, sizeof(LZ4_Data_Structure)); + LZ4_init ((LZ4_Data_Structure*)lz4ds, (const BYTE*)inputBuffer); + return lz4ds; +} + + +int LZ4_free (void* LZ4_Data) +{ + FREEMEM(LZ4_Data); + return (0); +} + + +char* LZ4_slideInputBuffer (void* LZ4_Data) +{ + LZ4_Data_Structure* lz4ds = (LZ4_Data_Structure*)LZ4_Data; + size_t delta = lz4ds->nextBlock - (lz4ds->bufferStart + 64 KB); + + if ( (lz4ds->base - delta > lz4ds->base) /* underflow control */ + || ((size_t)(lz4ds->nextBlock - lz4ds->base) > 0xE0000000) ) /* close to 32-bits limit */ + { + size_t deltaLimit = (lz4ds->nextBlock - 64 KB) - lz4ds->base; + int nH; + + for (nH=0; nH < HASHNBCELLS4; nH++) + { + if ((size_t)(lz4ds->hashTable[nH]) < deltaLimit) lz4ds->hashTable[nH] = 0; + else lz4ds->hashTable[nH] -= (U32)deltaLimit; + } + memcpy((void*)(lz4ds->bufferStart), (const void*)(lz4ds->nextBlock - 64 KB), 64 KB); + lz4ds->base = lz4ds->bufferStart; + lz4ds->nextBlock = lz4ds->base + 64 KB; + } + else + { + memcpy((void*)(lz4ds->bufferStart), (const void*)(lz4ds->nextBlock - 64 KB), 64 KB); + lz4ds->nextBlock -= delta; + lz4ds->base -= delta; + } + + return (char*)(lz4ds->nextBlock); +} + + +int LZ4_compress_continue (void* LZ4_Data, const char* source, char* dest, int inputSize) +{ + return LZ4_compress_generic(LZ4_Data, source, dest, inputSize, 0, notLimited, byU32, withPrefix); +} + + +int LZ4_compress_limitedOutput_continue (void* LZ4_Data, const char* source, char* dest, int inputSize, int maxOutputSize) +{ + return LZ4_compress_generic(LZ4_Data, source, dest, inputSize, maxOutputSize, limited, byU32, withPrefix); +} + + +/**************************** + Decompression functions +****************************/ +/* + * This generic decompression function cover all use cases. + * It shall be instanciated several times, using different sets of directives + * Note that it is essential this generic function is really inlined, + * in order to remove useless branches during compilation optimisation. + */ +FORCE_INLINE int LZ4_decompress_generic( + const char* source, + char* dest, + int inputSize, + int outputSize, /* If endOnInput==endOnInputSize, this value is the max size of Output Buffer. */ + + int endOnInput, /* endOnOutputSize, endOnInputSize */ + int prefix64k, /* noPrefix, withPrefix */ + int partialDecoding, /* full, partial */ + int targetOutputSize /* only used if partialDecoding==partial */ + ) +{ + /* Local Variables */ + const BYTE* restrict ip = (const BYTE*) source; + const BYTE* ref; + const BYTE* const iend = ip + inputSize; + + BYTE* op = (BYTE*) dest; + BYTE* const oend = op + outputSize; + BYTE* cpy; + BYTE* oexit = op + targetOutputSize; + + /*const size_t dec32table[] = {0, 3, 2, 3, 0, 0, 0, 0}; / static reduces speed for LZ4_decompress_safe() on GCC64 */ + const size_t dec32table[] = {4-0, 4-3, 4-2, 4-3, 4-0, 4-0, 4-0, 4-0}; /* static reduces speed for LZ4_decompress_safe() on GCC64 */ + static const size_t dec64table[] = {0, 0, 0, (size_t)-1, 0, 1, 2, 3}; + + + /* Special cases */ + if ((partialDecoding) && (oexit> oend-MFLIMIT)) oexit = oend-MFLIMIT; /* targetOutputSize too high => decode everything */ + if ((endOnInput) && (unlikely(outputSize==0))) return ((inputSize==1) && (*ip==0)) ? 0 : -1; /* Empty output buffer */ + if ((!endOnInput) && (unlikely(outputSize==0))) return (*ip==0?1:-1); + + + /* Main Loop */ + while (1) + { + unsigned token; + size_t length; + + /* get runlength */ + token = *ip++; + if ((length=(token>>ML_BITS)) == RUN_MASK) + { + unsigned s=255; + while (((endOnInput)?ip(partialDecoding?oexit:oend-MFLIMIT)) || (ip+length>iend-(2+1+LASTLITERALS))) ) + || ((!endOnInput) && (cpy>oend-COPYLENGTH))) + { + if (partialDecoding) + { + if (cpy > oend) goto _output_error; /* Error : write attempt beyond end of output buffer */ + if ((endOnInput) && (ip+length > iend)) goto _output_error; /* Error : read attempt beyond end of input buffer */ + } + else + { + if ((!endOnInput) && (cpy != oend)) goto _output_error; /* Error : block decoding must stop exactly there */ + if ((endOnInput) && ((ip+length != iend) || (cpy > oend))) goto _output_error; /* Error : input must be consumed */ + } + memcpy(op, ip, length); + ip += length; + op += length; + break; /* Necessarily EOF, due to parsing restrictions */ + } + LZ4_WILDCOPY(op, ip, cpy); ip -= (op-cpy); op = cpy; + + /* get offset */ + LZ4_READ_LITTLEENDIAN_16(ref,cpy,ip); ip+=2; + if ((prefix64k==noPrefix) && (unlikely(ref < (BYTE* const)dest))) goto _output_error; /* Error : offset outside destination buffer */ + + /* get matchlength */ + if ((length=(token&ML_MASK)) == ML_MASK) + { + while ((!endOnInput) || (ipoend-COPYLENGTH-(STEPSIZE-4))) + { + if (cpy > oend-LASTLITERALS) goto _output_error; /* Error : last 5 bytes must be literals */ + LZ4_SECURECOPY(op, ref, (oend-COPYLENGTH)); + while(op (unsigned int)LZ4_MAX_INPUT_SIZE ? 0 : (isize) + ((isize)/255) + 16) + +/* +LZ4_compressBound() : + Provides the maximum size that LZ4 may output in a "worst case" scenario (input data not compressible) + primarily useful for memory allocation of output buffer. + inline function is recommended for the general case, + macro is also provided when result needs to be evaluated at compilation (such as stack memory allocation). + + isize : is the input size. Max supported value is LZ4_MAX_INPUT_SIZE + return : maximum output size in a "worst case" scenario + or 0, if input size is too large ( > LZ4_MAX_INPUT_SIZE) +*/ +int LZ4_compressBound(int isize); + + +/* +LZ4_compress_limitedOutput() : + Compress 'inputSize' bytes from 'source' into an output buffer 'dest' of maximum size 'maxOutputSize'. + If it cannot achieve it, compression will stop, and result of the function will be zero. + This function never writes outside of provided output buffer. + + inputSize : Max supported value is LZ4_MAX_INPUT_VALUE + maxOutputSize : is the size of the destination buffer (which must be already allocated) + return : the number of bytes written in buffer 'dest' + or 0 if the compression fails +*/ +int LZ4_compress_limitedOutput (const char* source, char* dest, int inputSize, int maxOutputSize); + + +/* +LZ4_decompress_fast() : + originalSize : is the original and therefore uncompressed size + return : the number of bytes read from the source buffer (in other words, the compressed size) + If the source stream is malformed, the function will stop decoding and return a negative result. + note : This function is a bit faster than LZ4_decompress_safe() + This function never writes outside of output buffers, but may read beyond input buffer in case of malicious data packet. + Use this function preferably into a trusted environment (data to decode comes from a trusted source). + Destination buffer must be already allocated. Its size must be a minimum of 'outputSize' bytes. +*/ +int LZ4_decompress_fast (const char* source, char* dest, int originalSize); + + +/* +LZ4_decompress_safe_partial() : + This function decompress a compressed block of size 'inputSize' at position 'source' + into output buffer 'dest' of size 'maxOutputSize'. + The function tries to stop decompressing operation as soon as 'targetOutputSize' has been reached, + reducing decompression time. + return : the number of bytes decoded in the destination buffer (necessarily <= maxOutputSize) + Note : this number can be < 'targetOutputSize' should the compressed block to decode be smaller. + Always control how many bytes were decoded. + If the source stream is detected malformed, the function will stop decoding and return a negative result. + This function never writes outside of output buffer, and never reads outside of input buffer. It is therefore protected against malicious data packets +*/ +int LZ4_decompress_safe_partial (const char* source, char* dest, int inputSize, int targetOutputSize, int maxOutputSize); + + +/* +These functions are provided should you prefer to allocate memory for compression tables with your own allocation methods. +To know how much memory must be allocated for the compression tables, use : +int LZ4_sizeofState(); + +Note that tables must be aligned on 4-bytes boundaries, otherwise compression will fail (return code 0). + +The allocated memory can be provided to the compressions functions using 'void* state' parameter. +LZ4_compress_withState() and LZ4_compress_limitedOutput_withState() are equivalent to previously described functions. +They just use the externally allocated memory area instead of allocating their own (on stack, or on heap). +*/ +int LZ4_sizeofState(void); +int LZ4_compress_withState (void* state, const char* source, char* dest, int inputSize); +int LZ4_compress_limitedOutput_withState (void* state, const char* source, char* dest, int inputSize, int maxOutputSize); + + +/************************************** + Streaming Functions +**************************************/ +void* LZ4_create (const char* inputBuffer); +int LZ4_compress_continue (void* LZ4_Data, const char* source, char* dest, int inputSize); +int LZ4_compress_limitedOutput_continue (void* LZ4_Data, const char* source, char* dest, int inputSize, int maxOutputSize); +char* LZ4_slideInputBuffer (void* LZ4_Data); +int LZ4_free (void* LZ4_Data); + +/* +These functions allow the compression of dependent blocks, where each block benefits from prior 64 KB within preceding blocks. +In order to achieve this, it is necessary to start creating the LZ4 Data Structure, thanks to the function : + +void* LZ4_create (const char* inputBuffer); +The result of the function is the (void*) pointer on the LZ4 Data Structure. +This pointer will be needed in all other functions. +If the pointer returned is NULL, then the allocation has failed, and compression must be aborted. +The only parameter 'const char* inputBuffer' must, obviously, point at the beginning of input buffer. +The input buffer must be already allocated, and size at least 192KB. +'inputBuffer' will also be the 'const char* source' of the first block. + +All blocks are expected to lay next to each other within the input buffer, starting from 'inputBuffer'. +To compress each block, use either LZ4_compress_continue() or LZ4_compress_limitedOutput_continue(). +Their behavior are identical to LZ4_compress() or LZ4_compress_limitedOutput(), +but require the LZ4 Data Structure as their first argument, and check that each block starts right after the previous one. +If next block does not begin immediately after the previous one, the compression will fail (return 0). + +When it's no longer possible to lay the next block after the previous one (not enough space left into input buffer), a call to : +char* LZ4_slideInputBuffer(void* LZ4_Data); +must be performed. It will typically copy the latest 64KB of input at the beginning of input buffer. +Note that, for this function to work properly, minimum size of an input buffer must be 192KB. +==> The memory position where the next input data block must start is provided as the result of the function. + +Compression can then resume, using LZ4_compress_continue() or LZ4_compress_limitedOutput_continue(), as usual. + +When compression is completed, a call to LZ4_free() will release the memory used by the LZ4 Data Structure. +*/ + + +int LZ4_sizeofStreamState(void); +int LZ4_resetStreamState(void* state, const char* inputBuffer); + +/* +These functions achieve the same result as : +void* LZ4_create (const char* inputBuffer); + +They are provided here to allow the user program to allocate memory using its own routines. + +To know how much space must be allocated, use LZ4_sizeofStreamState(); +Note also that space must be 4-bytes aligned. + +Once space is allocated, you must initialize it using : LZ4_resetStreamState(void* state, const char* inputBuffer); +void* state is a pointer to the space allocated. +It must be aligned on 4-bytes boundaries, and be large enough. +The parameter 'const char* inputBuffer' must, obviously, point at the beginning of input buffer. +The input buffer must be already allocated, and size at least 192KB. +'inputBuffer' will also be the 'const char* source' of the first block. + +The same space can be re-used multiple times, just by initializing it each time with LZ4_resetStreamState(). +return value of LZ4_resetStreamState() must be 0 is OK. +Any other value means there was an error (typically, pointer is not aligned on 4-bytes boundaries). +*/ + + +int LZ4_decompress_safe_withPrefix64k (const char* source, char* dest, int inputSize, int maxOutputSize); +int LZ4_decompress_fast_withPrefix64k (const char* source, char* dest, int outputSize); + +/* +*_withPrefix64k() : + These decoding functions work the same as their "normal name" versions, + but can use up to 64KB of data in front of 'char* dest'. + These functions are necessary to decode inter-dependant blocks. +*/ + + +/************************************** + Obsolete Functions +**************************************/ +/* +These functions are deprecated and should no longer be used. +They are provided here for compatibility with existing user programs. +*/ +int LZ4_uncompress (const char* source, char* dest, int outputSize); +int LZ4_uncompress_unknownOutputSize (const char* source, char* dest, int isize, int maxOutputSize); + + +#if defined (__cplusplus) +} +#endif diff --git a/src/main.cpp b/src/main.cpp index 112fcc6..09f00d2 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -17,6 +17,11 @@ #include "txdb.h" #include "txmempool.h" #include "ui_interface.h" +#include "instantx.h" +#include "darksend.h" +#include "masternode.h" +#include "spork.h" +#include "smessage.h" using namespace std; using namespace boost; @@ -53,6 +58,7 @@ CBlockIndex* pindexBest = NULL; int64_t nTimeBestReceived = 0; bool fImporting = false; bool fReindex = false; +bool fAddrIndex = false; bool fHaveGUI = false; struct COrphanBlock { @@ -75,6 +81,8 @@ const string strMessageMagic = "Genius Signed Message:\n"; extern enum Checkpoints::CPMode CheckpointsMode; +std::set setValidatedTx; + ////////////////////////////////////////////////////////////////////////////// // // dispatching functions @@ -152,6 +160,16 @@ void UnregisterNodeSignals(CNodeSignals& nodeSignals) nodeSignals.SendMessages.disconnect(&SendMessages); } +bool AbortNode(const std::string &strMessage, const std::string &userMessage) { + strMiscWarning = strMessage; + LogPrintf("*** %s\n", strMessage); + uiInterface.ThreadSafeMessageBox( + userMessage.empty() ? _("Error: A fatal internal error occured, see debug.log for details") : userMessage, + "", CClientUIInterface::MSG_ERROR); + StartShutdown(); + return false; +} + ////////////////////////////////////////////////////////////////////////////// @@ -732,6 +750,7 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CTransaction &tx, bool fLimitFree, // Store transaction in memory pool.addUnchecked(hash, tx); + setValidatedTx.insert(hash); SyncWithWallets(tx, NULL); @@ -741,7 +760,133 @@ bool AcceptToMemoryPool(CTxMemPool& pool, CTransaction &tx, bool fLimitFree, return true; } +bool AcceptableInputs(CTxMemPool& pool, const CTransaction &txo, bool fLimitFree, + bool* pfMissingInputs) +{ + AssertLockHeld(cs_main); + if (pfMissingInputs) + *pfMissingInputs = false; + + CTransaction tx(txo); + + if (!tx.CheckTransaction()) + return error("AcceptableInputs : CheckTransaction failed"); + + // Coinbase is only valid in a block, not as a loose transaction + if (tx.IsCoinBase()) + return tx.DoS(100, error("AcceptableInputs : coinbase as individual tx")); + + // ppcoin: coinstake is also only valid in a block, not as a loose transaction + if (tx.IsCoinStake()) + return tx.DoS(100, error("AcceptableInputs : coinstake as individual tx")); + + // Rather not work on nonstandard transactions (unless -testnet) + string reason; + if (!TestNet() && !IsStandardTx(tx, reason)) + return error("AcceptableInputs : nonstandard transaction: %s", + reason); + + // is it already in the memory pool? + uint256 hash = tx.GetHash(); + if (pool.exists(hash)) + return false; + + // Check for conflicts with in-memory transactions + { + LOCK(pool.cs); // protect pool.mapNextTx + for (unsigned int i = 0; i < tx.vin.size(); i++) + { + COutPoint outpoint = tx.vin[i].prevout; + if (pool.mapNextTx.count(outpoint)) + { + // Disable replacement feature for now + return false; + } + } + } + + { + CTxDB txdb("r"); + // do we already have it? + if (txdb.ContainsTx(hash)) + return false; + + MapPrevTx mapInputs; + map mapUnused; + bool fInvalid = false; + if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid)) + { + if (fInvalid) + return error("AcceptableInputs : FetchInputs found invalid tx %s", hash.ToString()); + if (pfMissingInputs) + *pfMissingInputs = true; + return false; + } + + // Check for non-standard pay-to-script-hash in inputs + //if (!TestNet() && !AreInputsStandard(tx, mapInputs)) + // return error("AcceptToMemoryPool : nonstandard transaction input"); + + // Check that the transaction doesn't have an excessive number of + // sigops, making it impossible to mine. Since the coinbase transaction + // itself can contain sigops MAX_TX_SIGOPS is less than + // MAX_BLOCK_SIGOPS; we still consider this an invalid rather than + // merely non-standard transaction. + unsigned int nSigOps = GetLegacySigOpCount(tx); + nSigOps += GetP2SHSigOpCount(tx, mapInputs); + if (nSigOps > MAX_TX_SIGOPS) + return tx.DoS(0, + error("AcceptableInputs : too many sigops %s, %d > %d", + hash.ToString(), nSigOps, MAX_TX_SIGOPS)); + + int64_t nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut(); + unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION); + + // Don't accept it if it can't get into a block + int64_t txMinFee = GetMinFee(tx, 1000, GMF_RELAY, nSize); + if ((fLimitFree && nFees < txMinFee) || (!fLimitFree && nFees < MIN_TX_FEE)) + return error("AcceptableInputs : not enough fees %s, %d < %d", + hash.ToString(), + nFees, txMinFee); + + // Continuously rate-limit free transactions + // This mitigates 'penny-flooding' -- sending thousands of free transactions just to + // be annoying or make others' transactions take longer to confirm. + if (fLimitFree && nFees < MIN_RELAY_TX_FEE) + { + static CCriticalSection csFreeLimiter; + static double dFreeCount; + static int64_t nLastTime; + int64_t nNow = GetTime(); + + LOCK(csFreeLimiter); + + // Use an exponentially decaying ~10-minute window: + dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime)); + nLastTime = nNow; + // -limitfreerelay unit is thousand-bytes-per-minute + // At default rate it would take over a month to fill 1GB + if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000) + return error("AcceptableInputs : free transaction rejected by rate limiter"); + LogPrint("mempool", "Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize); + dFreeCount += nSize; + } + + // Check against previous transactions + // This is done last to help prevent CPU exhaustion denial-of-service attacks. + if (!tx.ConnectInputs(txdb, mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, true, false, STANDARD_SCRIPT_VERIFY_FLAGS, false)) + { + return error("AcceptableInputs : ConnectInputs failed %s", hash.ToString()); + } + } + + + LogPrint("mempool", "AcceptableInputs : accepted %s (poolsz %u)\n", + hash.ToString(), + pool.mapTx.size()); + return true; +} int CMerkleTx::GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const @@ -820,6 +965,25 @@ bool CWalletTx::AcceptWalletTransaction() return AcceptWalletTransaction(txdb); } +int GetInputAge(CTxIn& vin) +{ + const uint256& prevHash = vin.prevout.hash; + CTransaction tx; + uint256 hashBlock; + bool fFound = GetTransaction(prevHash, tx, hashBlock); + if(fFound) + { + if(mapBlockIndex.find(hashBlock) != mapBlockIndex.end()) + { + return pindexBest->nHeight - mapBlockIndex[hashBlock]->nHeight; + } + else + return 0; + } + else + return 0; +} + int CTxIndex::GetDepthInMainChain() const { // Read block header @@ -966,51 +1130,48 @@ static CBigNum GetProofOfStakeLimit(int nHeight) int64_t GetProofOfWorkReward(int64_t nFees) { int64_t nSubsidy = 10000 * COIN; + if(pindexBest->nHeight < 2500) { - nSubsidy = 120000 * COIN; + nSubsidy = 120000 * COIN; } else if(pindexBest->nHeight < 5000) { - nSubsidy = 90000 * COIN; + nSubsidy = 90000 * COIN; } else if(pindexBest->nHeight < 7500) { - nSubsidy = 60000 * COIN; + nSubsidy = 60000 * COIN; } else if(pindexBest->nHeight < 10000) { - nSubsidy = 30000 * COIN; + nSubsidy = 30000 * COIN; } else if(pindexBest->nHeight < 15000) { - nSubsidy = 20000 * COIN; + nSubsidy = 20000 * COIN; } else if(pindexBest->nHeight < 20000) { - nSubsidy = 15000 * COIN; + nSubsidy = 15000 * COIN; } - else if(pindexBest->nHeight <= 30000) + else if(pindexBest->nHeight < 30000) { - nSubsidy = 10000 * COIN; + nSubsidy = 10000 * COIN; } - LogPrint("creation", "GetProofOfWorkReward() : create=%s nSubsidy=%d\n", FormatMoney(nSubsidy), nSubsidy); - return nSubsidy + nFees; } // miner's coin stake reward based on coin age spent (coin-days) int64_t GetProofOfStakeReward(int64_t nCoinAge, int64_t nFees) { - int64_t nSubsidy = 1000 * COIN; //nCoinAge * COIN_YEAR_REWARD * 33 / (365 * 33 + 8); - - LogPrint("creation", "GetProofOfStakeReward(): create=%s nCoinAge=%d\n", FormatMoney(nSubsidy), nCoinAge); + int64_t nSubsidy = 1000 * COIN; return nSubsidy + nFees; } -static const int64_t nTargetTimespan = 60 * 60; // 60 mins +static int64_t nTargetTimespan = 60 * 60; // 60 mins // // maximum nBits value could possible be required nTime after @@ -1061,7 +1222,7 @@ const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfSta int nTargetSpacing = 60; unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake) -{ +{ CBigNum bnTargetLimit = fProofOfStake ? GetProofOfStakeLimit(pindexLast->nHeight) : Params().ProofOfWorkLimit(); if (pindexLast == NULL) @@ -1124,6 +1285,32 @@ bool IsInitialBlockDownload() pindexBest->GetBlockTime() < GetTime() - 8 * 60 * 60); } +// Requires cs_main. +void Misbehaving(NodeId pnode, int howmuch) +{ + if (howmuch == 0) + return; + + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pn, vNodes) + { + if(pn->GetId() == pnode) + { + pn->nMisbehavior += howmuch; + int banscore = GetArg("-banscore", 100); + if (pn->nMisbehavior >= banscore && pn->nMisbehavior - howmuch < banscore) + { + LogPrintf("Misbehaving: %s (%d -> %d) BAN THRESHOLD EXCEEDED\n", pn->addrName, pn->nMisbehavior-howmuch, pn->nMisbehavior); + //pn->fShouldBan = true; + } + else + LogPrintf("Misbehaving: %s (%d -> %d)\n", pn->addrName, pn->nMisbehavior-howmuch, pn->nMisbehavior); + + break; + } + } +} + void static InvalidChainFound(CBlockIndex* pindexNew) { if (pindexNew->nChainTrust > nBestInvalidTrust) @@ -1155,13 +1342,6 @@ void CBlock::UpdateTime(const CBlockIndex* pindexPrev) - - - - - - - bool CTransaction::DisconnectInputs(CTxDB& txdb) { // Relinquish previous transactions' spent pointers @@ -1297,7 +1477,7 @@ int64_t CTransaction::GetValueIn(const MapPrevTx& inputs) const } bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map& mapTestPool, const CDiskTxPos& posThisTx, - const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, unsigned int flags) + const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, unsigned int flags, bool fValidateSig) { // Take over previous transactions' spent pointers // fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain @@ -1349,6 +1529,8 @@ bool CTransaction::ConnectInputs(CTxDB& txdb, MapPrevTx inputs, map& addrIds) +{ + CScript::const_iterator pc = script.begin(); + CScript::const_iterator pend = script.end(); + std::vector data; + opcodetype opcode; + bool fHaveData = false; + while (pc < pend) { + script.GetOp(pc, opcode, data); + if (0 <= opcode && opcode <= OP_PUSHDATA4 && data.size() >= 8) { // data element + uint160 addrid = 0; + if (data.size() <= 20) { + memcpy(&addrid, &data[0], data.size()); + } else { + addrid = Hash160(data); + } + addrIds.push_back(addrid); + fHaveData = true; + } + } + if (!fHaveData) { + uint160 addrid = Hash160(script); + addrIds.push_back(addrid); + return true; + } + else + { + if(addrIds.size() > 0) + return true; + else + return false; + } +} + +bool FindTransactionsByDestination(const CTxDestination &dest, std::vector &vtxhash) { + uint160 addrid = 0; + const CKeyID *pkeyid = boost::get(&dest); + if (pkeyid) + addrid = static_cast(*pkeyid); + if (!addrid) { + const CScriptID *pscriptid = boost::get(&dest); + if (pscriptid) + addrid = static_cast(*pscriptid); + } + if (!addrid) + { + LogPrintf("FindTransactionsByDestination(): Couldn't parse dest into addrid\n"); + return false; + } + + LOCK(cs_main); + CTxDB txdb("r"); + if(!txdb.ReadAddrIndex(addrid, vtxhash)) + { + LogPrintf("FindTransactionsByDestination(): txdb.ReadAddrIndex failed\n"); + return false; + } + return true; +} + +void CBlock::RebuildAddressIndex(CTxDB& txdb) +{ + BOOST_FOREACH(CTransaction& tx, vtx) + { + uint256 hashTx = tx.GetHash(); + // inputs + if(!tx.IsCoinBase()) + { + MapPrevTx mapInputs; + map mapQueuedChangesT; + bool fInvalid; + if (!tx.FetchInputs(txdb, mapQueuedChangesT, true, false, mapInputs, fInvalid)) + return; + + MapPrevTx::const_iterator mi; + for(MapPrevTx::const_iterator mi = mapInputs.begin(); mi != mapInputs.end(); ++mi) + { + BOOST_FOREACH(const CTxOut &atxout, (*mi).second.second.vout) + { + std::vector addrIds; + if(BuildAddrIndex(atxout.scriptPubKey, addrIds)) + { + BOOST_FOREACH(uint160 addrId, addrIds) + { + if(!txdb.WriteAddrIndex(addrId, hashTx)) + LogPrintf("RebuildAddressIndex(): txins WriteAddrIndex failed addrId: %s txhash: %s\n", addrId.ToString().c_str(), hashTx.ToString().c_str()); + } + } + } + } + + } + // outputs + BOOST_FOREACH(const CTxOut &atxout, tx.vout) { + std::vector addrIds; + if(BuildAddrIndex(atxout.scriptPubKey, addrIds)) + { + BOOST_FOREACH(uint160 addrId, addrIds) + { + if(!txdb.WriteAddrIndex(addrId, hashTx)) + LogPrintf("RebuildAddressIndex(): txouts WriteAddrIndex failed addrId: %s txhash: %s\n", addrId.ToString().c_str(), hashTx.ToString().c_str()); + } + } + } + } +} + bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck) { // Check it again in case a previous version let a bad block in, but skip BlockSig checking @@ -1458,10 +1748,13 @@ bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck) int64_t nValueIn = 0; int64_t nValueOut = 0; int64_t nStakeReward = 0; - unsigned int nSigOps = 0; + unsigned int nSigOps = 0; + int nInputs = 0; + BOOST_FOREACH(CTransaction& tx, vtx) { uint256 hashTx = tx.GetHash(); + nInputs += tx.vin.size(); // Do not allow blocks that contain transactions which 'overwrite' older transactions, // unless those are already completely spent. @@ -1515,13 +1808,14 @@ bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck) if (tx.IsCoinStake()) nStakeReward = nTxValueOut - nTxValueIn; + if (!tx.ConnectInputs(txdb, mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, flags)) return false; } mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size()); } - + if (IsProofOfWork()) { int64_t nReward = GetProofOfWorkReward(nFees); @@ -1560,6 +1854,58 @@ bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck) return error("ConnectBlock() : UpdateTxIndex failed"); } + + if(GetBoolArg("-addrindex", false)) + { + + // Write Address Index + BOOST_FOREACH(CTransaction& tx, vtx) + { + uint256 hashTx = tx.GetHash(); + // inputs + if(!tx.IsCoinBase()) + { + MapPrevTx mapInputs; + map mapQueuedChangesT; + bool fInvalid; + if (!tx.FetchInputs(txdb, mapQueuedChangesT, true, false, mapInputs, fInvalid)) + return false; + + MapPrevTx::const_iterator mi; + for(MapPrevTx::const_iterator mi = mapInputs.begin(); mi != mapInputs.end(); ++mi) + { + BOOST_FOREACH(const CTxOut &atxout, (*mi).second.second.vout) + { + std::vector addrIds; + if(BuildAddrIndex(atxout.scriptPubKey, addrIds)) + { + BOOST_FOREACH(uint160 addrId, addrIds) + { + if(!txdb.WriteAddrIndex(addrId, hashTx)) + LogPrintf("ConnectBlock(): txins WriteAddrIndex failed addrId: %s txhash: %s\n", addrId.ToString().c_str(), hashTx.ToString().c_str()); + } + } + } + } + + } + + // outputs + BOOST_FOREACH(const CTxOut &atxout, tx.vout) { + std::vector addrIds; + if(BuildAddrIndex(atxout.scriptPubKey, addrIds)) + { + BOOST_FOREACH(uint160 addrId, addrIds) + { + if(!txdb.WriteAddrIndex(addrId, hashTx)) + LogPrintf("ConnectBlock(): txouts WriteAddrIndex failed addrId: %s txhash: %s\n", addrId.ToString().c_str(), hashTx.ToString().c_str()); + } + } + } + } + + } + // Update block index on disk without changing it in memory. // The memory index structure will be changed after the db commits. if (pindex->pprev) @@ -1979,6 +2325,91 @@ bool CBlock::CheckBlock(bool fCheckPOW, bool fCheckMerkleRoot, bool fCheckSig) c if (fCheckSig && !CheckBlockSignature()) return DoS(100, error("CheckBlock() : bad proof-of-stake block signature")); + +// ----------- instantX transaction scanning ----------- + + + BOOST_FOREACH(const CTransaction& tx, vtx){ + if (!tx.IsCoinBase()){ + //only reject blocks when it's based on complete consensus + BOOST_FOREACH(const CTxIn& in, tx.vin){ + if(mapLockedInputs.count(in.prevout)){ + if(mapLockedInputs[in.prevout] != tx.GetHash()){ + if(fDebug) { LogPrintf("CheckBlock() : found conflicting transaction with transaction lock %s %s\n", mapLockedInputs[in.prevout].ToString().c_str(), tx.GetHash().ToString().c_str()); } + return DoS(0, error("CheckBlock() : found conflicting transaction with transaction lock")); + } + } + } + } + } + + + + // ----------- masternode payments ----------- + + bool MasternodePayments = false; + + if(nTime > START_MASTERNODE_PAYMENTS) MasternodePayments = true; + + if(MasternodePayments) + { + LOCK2(cs_main, mempool.cs); + + CBlockIndex *pindex = pindexBest; + if(IsProofOfStake() && pindex != NULL){ + if(pindex->GetBlockHash() == hashPrevBlock){ + CAmount masternodePaymentAmount = GetMasternodePayment(pindex->nHeight+1, vtx[1].GetValueOut()); + bool fIsInitialDownload = IsInitialBlockDownload(); + + // If we don't already have its previous block, skip masternode payment step + if (!fIsInitialDownload && pindex != NULL) + { + bool foundPaymentAmount = false; + bool foundPayee = false; + bool foundPaymentAndPayee = false; + + CScript payee; + if(!masternodePayments.GetBlockPayee(pindexBest->nHeight+1, payee) || payee == CScript()){ + foundPayee = true; //doesn't require a specific payee + foundPaymentAmount = true; + foundPaymentAndPayee = true; + if(fDebug) { LogPrintf("CheckBlock() : Using non-specific masternode payments %d\n", pindexBest->nHeight+1); } + } + + for (unsigned int i = 0; i < vtx[1].vout.size(); i++) { + if(vtx[1].vout[i].nValue == masternodePaymentAmount ) + foundPaymentAmount = true; + if(vtx[1].vout[i].scriptPubKey == payee ) + foundPayee = true; + if(vtx[1].vout[i].nValue == masternodePaymentAmount && vtx[1].vout[i].scriptPubKey == payee) + foundPaymentAndPayee = true; + } + + if(!foundPaymentAndPayee) { + CTxDestination address1; + ExtractDestination(payee, address1); + CBitcoinAddress address2(address1); + + if(fDebug) { LogPrintf("CheckBlock() : Couldn't find masternode payment(%d|%d) or payee(%d|%s) nHeight %d. \n", foundPaymentAmount, masternodePaymentAmount, foundPayee, address2.ToString().c_str(), pindexBest->nHeight+1); } + return DoS(100, error("CheckBlock() : Couldn't find masternode payment or payee")); + } else { + if(fDebug) { LogPrintf("CheckBlock() : Found masternode payment %d\n", pindexBest->nHeight+1); } + } + } else { + if(fDebug) { LogPrintf("CheckBlock() : Is initial download, skipping masternode payment check %d\n", pindexBest->nHeight+1); } + } + } else { + if(fDebug) { LogPrintf("CheckBlock() : Skipping masternode payment check - nHeight %d Hash %s\n", pindexBest->nHeight+1, GetHash().ToString().c_str()); } + } + } else { + if(fDebug) { LogPrintf("CheckBlock() : pindex is null, skipping masternode payment check\n"); } + } + } else { + if(fDebug) { LogPrintf("CheckBlock() : skipping masternode payment checks\n"); } + } + + + // Check transactions BOOST_FOREACH(const CTransaction& tx, vtx) { @@ -2772,6 +3203,15 @@ bool static AlreadyHave(CTxDB& txdb, const CInv& inv) case MSG_BLOCK: return mapBlockIndex.count(inv.hash) || mapOrphanBlocks.count(inv.hash); + case MSG_TXLOCK_REQUEST: + return mapTxLockReq.count(inv.hash) || + mapTxLockReqRejected.count(inv.hash); + case MSG_TXLOCK_VOTE: + return mapTxLockVote.count(inv.hash); + case MSG_SPORK: + return mapSporks.count(inv.hash); + case MSG_MASTERNODE_WINNER: + return mapSeenMasternodeVotes.count(inv.hash); } // Don't know what it is, just say we already got one return true; @@ -2834,12 +3274,62 @@ void static ProcessGetData(CNode* pfrom) } } if (!pushed && inv.type == MSG_TX) { - CTransaction tx; - if (mempool.lookup(inv.hash, tx)) { + if(mapDarksendBroadcastTxes.count(inv.hash)){ CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); ss.reserve(1000); - ss << tx; - pfrom->PushMessage("tx", ss); + ss << + mapDarksendBroadcastTxes[inv.hash].tx << + mapDarksendBroadcastTxes[inv.hash].vin << + mapDarksendBroadcastTxes[inv.hash].vchSig << + mapDarksendBroadcastTxes[inv.hash].sigTime; + + pfrom->PushMessage("dstx", ss); + pushed = true; + } else { + CTransaction tx; + if (mempool.lookup(inv.hash, tx)) { + CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); + ss.reserve(1000); + ss << tx; + pfrom->PushMessage("tx", ss); + pushed = true; + } + } + } + if (!pushed && inv.type == MSG_TXLOCK_VOTE) { + if(mapTxLockVote.count(inv.hash)){ + CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); + ss.reserve(1000); + ss << mapTxLockVote[inv.hash]; + pfrom->PushMessage("txlvote", ss); + pushed = true; + } + } + if (!pushed && inv.type == MSG_TXLOCK_REQUEST) { + if(mapTxLockReq.count(inv.hash)){ + CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); + ss.reserve(1000); + ss << mapTxLockReq[inv.hash]; + pfrom->PushMessage("txlreq", ss); + pushed = true; + } + } + if (!pushed && inv.type == MSG_SPORK) { + if(mapSporks.count(inv.hash)){ + CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); + ss.reserve(1000); + ss << mapSporks[inv.hash]; + pfrom->PushMessage("spork", ss); + pushed = true; + } + } + if (!pushed && inv.type == MSG_MASTERNODE_WINNER) { + if(mapSeenMasternodeVotes.count(inv.hash)){ + CDataStream ss(SER_NETWORK, PROTOCOL_VERSION); + int a = 0; + ss.reserve(1000); + ss << mapSeenMasternodeVotes[inv.hash] << a; + pfrom->PushMessage("mnw", ss); pushed = true; } } @@ -2911,6 +3401,8 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, if (!vRecv.empty()) vRecv >> pfrom->nStartingHeight; + pfrom->cleanSubVer = SanitizeString(pfrom->strSubVer); + // Disconnect if we connected to ourself if (nNonce == nLocalHostNonce && nNonce > 1) { @@ -2922,6 +3414,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, pfrom->addrLocal = addrMe; if (pfrom->fInbound && addrMe.IsRoutable()) { + addrSeenByPeer = addrMe; SeenLocal(addrMe); } @@ -3316,6 +3809,9 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, if (ProcessBlock(pfrom, &block)) mapAlreadyAskedFor.erase(inv); if (block.nDoS) pfrom->Misbehaving(block.nDoS); + + if (fSecMsgEnabled) + SecureMsgScanBlock(block); } @@ -3461,6 +3957,14 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv, else { + if (fSecMsgEnabled) + SecureMsgReceiveData(pfrom, strCommand, vRecv); + + ProcessMessageDarksend(pfrom, strCommand, vRecv); + ProcessMessageMasternode(pfrom, strCommand, vRecv); + ProcessMessageInstantX(pfrom, strCommand, vRecv); + ProcessSpork(pfrom, strCommand, vRecv); + // Ignore unknown commands for extensibility } @@ -3761,6 +4265,18 @@ bool SendMessages(CNode* pto, bool fSendTrickle) if (!vGetData.empty()) pto->PushMessage("getdata", vGetData); + if (fSecMsgEnabled) + SecureMsgSendData(pto, fSendTrickle); // should be in cs_main? + } return true; } + + + +int64_t GetMasternodePayment(int nHeight, int64_t blockValue) +{ + int64_t ret = blockValue * 1/2; //50% + + return ret; +} diff --git a/src/main.h b/src/main.h index 7a7f553..abdf9f4 100644 --- a/src/main.h +++ b/src/main.h @@ -15,6 +15,41 @@ #include +class CValidationState; + +#define START_MASTERNODE_PAYMENTS_TESTNET 1435017599 //Mon, 22 Jun 2015 23:59:59 GMT +#define START_MASTERNODE_PAYMENTS 1435017599 //Mon, 22 Jun 2015 23:59:59 GMT + +static const int64_t DARKSEND_COLLATERAL = (5000000*COIN); +static const int64_t DARKSEND_FEE = (0.75*COIN); +static const int64_t DARKSEND_POOL_MAX = (50000999.99*COIN); + +/* + At 15 signatures, 1/2 of the masternode network can be owned by + one party without comprimising the security of InstantX + (1000/2150.0)**15 = 1.031e-05 +*/ +#define INSTANTX_SIGNATURES_REQUIRED 20 +#define INSTANTX_SIGNATURES_TOTAL 30 + +#define MASTERNODE_NOT_PROCESSED 0 // initial state +#define MASTERNODE_IS_CAPABLE 1 +#define MASTERNODE_NOT_CAPABLE 2 +#define MASTERNODE_STOPPED 3 +#define MASTERNODE_INPUT_TOO_NEW 4 +#define MASTERNODE_PORT_NOT_OPEN 6 +#define MASTERNODE_PORT_OPEN 7 +#define MASTERNODE_SYNC_IN_PROCESS 8 +#define MASTERNODE_REMOTELY_ENABLED 9 + +#define MASTERNODE_MIN_CONFIRMATIONS 7 +#define MASTERNODE_MIN_DSEEP_SECONDS (20*60) +#define MASTERNODE_MIN_DSEE_SECONDS (1*60) +#define MASTERNODE_PING_SECONDS (20) //(1*60) +#define MASTERNODE_EXPIRATION_SECONDS (65*60) +#define MASTERNODE_REMOVAL_SECONDS (70*60) + + class CBlock; class CBlockIndex; class CInv; @@ -46,7 +81,7 @@ static const int64_t MIN_TX_FEE = 50000000; /** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */ static const int64_t MIN_RELAY_TX_FEE = MIN_TX_FEE; /** No amount larger than this (in satoshi) is valid */ -static const int64_t MAX_MONEY = 40000000000 * COIN; +static const int64_t MAX_MONEY = 40000000000 * COIN; inline bool MoneyRange(int64_t nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); } /** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */ static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC @@ -146,10 +181,19 @@ void ThreadStakeMiner(CWallet *pwallet); bool AcceptToMemoryPool(CTxMemPool& pool, CTransaction &tx, bool fLimitFree, bool* pfMissingInputs); +bool AcceptableInputs(CTxMemPool& pool, const CTransaction &txo, bool fLimitFree, + bool* pfMissingInputs); +bool FindTransactionsByDestination(const CTxDestination &dest, std::vector &vtxhash); +int GetInputAge(CTxIn& vin); +/** Abort with a message */ +bool AbortNode(const std::string &msg, const std::string &userMessage=""); +/** Increase a node's misbehavior score. */ +void Misbehaving(NodeId nodeid, int howmuch); +int64_t GetMasternodePayment(int nHeight, int64_t blockValue); /** Position on disk for a particular transaction. */ @@ -212,6 +256,8 @@ typedef std::map > MapPrevTx; int64_t GetMinFee(const CTransaction& tx, unsigned int nBlockSize = 1, enum GetMinFee_mode mode = GMF_BLOCK, unsigned int nBytes = 0); + + /** The basic transaction that is broadcasted on the network and contained in * blocks. A transaction can contain multiple inputs and outputs. */ @@ -234,6 +280,7 @@ class CTransaction SetNull(); } + IMPLEMENT_SERIALIZE ( READWRITE(this->nVersion); @@ -391,13 +438,16 @@ class CTransaction */ bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs, std::map& mapTestPool, const CDiskTxPos& posThisTx, - const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, unsigned int flags = STANDARD_SCRIPT_VERIFY_FLAGS); + const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, unsigned int flags = STANDARD_SCRIPT_VERIFY_FLAGS, bool fValidateSig = true); bool CheckTransaction() const; bool GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const; // ppcoin: get transaction coin age const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const; }; + + + /** wrapper for CTxOut that provides a more compact serialization */ class CTxOutCompressor { @@ -496,6 +546,8 @@ class CMerkleTx : public CTransaction bool IsInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; } int GetBlocksToMaturity() const; bool AcceptToMemoryPool(bool fLimitFree=true); + int GetTransactionLockSignatures() const; + bool IsTransactionLockTimedOut() const; }; @@ -651,7 +703,7 @@ class CBlock uint256 GetPoWHash() const { - return scrypt_blockhash(CVOIDBEGIN(nVersion)); + return scrypt_blockhash(CVOIDBEGIN(nVersion)); } int64_t GetBlockTime() const @@ -832,6 +884,7 @@ class CBlock bool AcceptBlock(); bool SignBlock(CWallet& keystore, int64_t nFees); bool CheckBlockSignature() const; + void RebuildAddressIndex(CTxDB& txdb); private: bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew); @@ -1291,6 +1344,69 @@ class CBlockLocator +/** Capture information about block/transaction validation */ +class CValidationState { +private: + enum mode_state { + MODE_VALID, //! everything ok + MODE_INVALID, //! network rule violation (DoS value may be set) + MODE_ERROR, //! run-time error + } mode; + int nDoS; + std::string strRejectReason; + unsigned char chRejectCode; + bool corruptionPossible; +public: + CValidationState() : mode(MODE_VALID), nDoS(0), chRejectCode(0), corruptionPossible(false) {} + bool DoS(int level, bool ret = false, + unsigned char chRejectCodeIn=0, std::string strRejectReasonIn="", + bool corruptionIn=false) { + chRejectCode = chRejectCodeIn; + strRejectReason = strRejectReasonIn; + corruptionPossible = corruptionIn; + if (mode == MODE_ERROR) + return ret; + nDoS += level; + mode = MODE_INVALID; + return ret; + } + bool Invalid(bool ret = false, + unsigned char _chRejectCode=0, std::string _strRejectReason="") { + return DoS(0, ret, _chRejectCode, _strRejectReason); + } + bool Error(std::string strRejectReasonIn="") { + if (mode == MODE_VALID) + strRejectReason = strRejectReasonIn; + mode = MODE_ERROR; + return false; + } + bool Abort(const std::string &msg) { + AbortNode(msg); + return Error(msg); + } + bool IsValid() const { + return mode == MODE_VALID; + } + bool IsInvalid() const { + return mode == MODE_INVALID; + } + bool IsError() const { + return mode == MODE_ERROR; + } + bool IsInvalid(int &nDoSOut) const { + if (IsInvalid()) { + nDoSOut = nDoS; + return true; + } + return false; + } + bool CorruptionPossible() const { + return corruptionPossible; + } + unsigned char GetRejectCode() const { return chRejectCode; } + std::string GetRejectReason() const { return strRejectReason; } +}; + diff --git a/src/makefile.unix b/src/makefile.unix index 8238b5a..0811c42 100644 --- a/src/makefile.unix +++ b/src/makefile.unix @@ -9,7 +9,7 @@ LINK:=$(CXX) ARCH:=$(system lscpu | head -n 1 | awk '{print $2}') DEFS=-DBOOST_SPIRIT_THREADSAFE - +DEFS += -DUSE_SECP256K1 DEFS += $(addprefix -I,$(CURDIR) $(CURDIR)/obj $(BOOST_INCLUDE_PATH) $(BDB_INCLUDE_PATH) $(OPENSSL_INCLUDE_PATH)) LIBS = $(addprefix -L,$(BOOST_LIB_PATH) $(BDB_LIB_PATH) $(OPENSSL_LIB_PATH)) @@ -22,6 +22,10 @@ ifdef STATIC endif endif +LIBS += \ + -Wl,-B$(LMODE) \ + -l secp256k1 + # for boost 1.37, add -mt to the boost libraries LIBS += \ -Wl,-B$(LMODE) \ @@ -107,6 +111,7 @@ OBJS= \ obj/addrman.o \ obj/crypter.o \ obj/key.o \ + obj/eckey.o \ obj/init.o \ obj/bitcoind.o \ obj/keystore.o \ @@ -121,8 +126,13 @@ OBJS= \ obj/rpcnet.o \ obj/rpcblockchain.o \ obj/rpcrawtransaction.o \ + obj/rpcsmessage.o \ obj/timedata.o \ obj/script.o \ + obj/scrypt.o \ + obj/scrypt-arm.o \ + obj/scrypt-x86.o \ + obj/scrypt-x86_64.o \ obj/sync.o \ obj/txmempool.o \ obj/util.o \ @@ -130,12 +140,24 @@ OBJS= \ obj/noui.o \ obj/kernel.o \ obj/pbkdf2.o \ - obj/scrypt.o \ - obj/scrypt-arm.o \ - obj/scrypt-x86.o \ - obj/scrypt-x86_64.o \ obj/chainparams.o \ - obj/irc.o + obj/stealth.o \ + obj/activemasternode.o \ + obj/darksend.o \ + obj/eccryptoverify.o \ + obj/instantx.o \ + obj/masternodeconfig.o \ + obj/masternode.o \ + obj/rpcdarksend.o \ + obj/spork.o \ + obj/crypto/hmac_sha256.o \ + obj/crypto/hmac_sha512.o \ + obj/crypto/rfc6979_hmac_sha256.o \ + obj/crypto/ripemd160.o \ + obj/crypto/sha1.o \ + obj/crypto/sha256.o \ + obj/crypto/sha512.o \ + obj/smessage.o ifeq (${USE_WALLET}, 1) DEFS += -DENABLE_WALLET diff --git a/src/masternode.cpp b/src/masternode.cpp new file mode 100644 index 0000000..ad12acb --- /dev/null +++ b/src/masternode.cpp @@ -0,0 +1,838 @@ +#include "masternode.h" +#include "activemasternode.h" +#include "darksend.h" +//#include "primitives/transaction.h" +#include "main.h" +#include "util.h" +#include "addrman.h" +#include + + +int CMasterNode::minProtoVersion = MIN_MN_PROTO_VERSION; + +CCriticalSection cs_masternodes; + +/** The list of active masternodes */ +std::vector vecMasternodes; +/** Object for who's going to get paid on which blocks */ +CMasternodePayments masternodePayments; +// keep track of masternode votes I've seen +map mapSeenMasternodeVotes; +// keep track of the scanning errors I've seen +map mapSeenMasternodeScanningErrors; +// who's asked for the masternode list and the last time +std::map askedForMasternodeList; +// which masternodes we've asked for +std::map askedForMasternodeListEntry; +// cache block hashes as we calculate them +std::map mapCacheBlockHashes; + +// manage the masternode connections +void ProcessMasternodeConnections(){ + LOCK(cs_vNodes); + + BOOST_FOREACH(CNode* pnode, vNodes) + { + //if it's our masternode, let it be + if(darkSendPool.submittedToMasternode == pnode->addr) continue; + + if(pnode->fDarkSendMaster){ + LogPrintf("Closing masternode connection %s \n", pnode->addr.ToString().c_str()); + pnode->CloseSocketDisconnect(); + } + } +} + +void ProcessMessageMasternode(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) +{ + + if (strCommand == "dsee") { //DarkSend Election Entry + if(fLiteMode) return; //disable all darksend/masternode related functionality + + bool fIsInitialDownload = IsInitialBlockDownload(); + if(fIsInitialDownload) return; + + CTxIn vin; + CService addr; + CPubKey pubkey; + CPubKey pubkey2; + vector vchSig; + int64_t sigTime; + int count; + int current; + int64_t lastUpdated; + int protocolVersion; + std::string strMessage; + + // 70047 and greater + vRecv >> vin >> addr >> vchSig >> sigTime >> pubkey >> pubkey2 >> count >> current >> lastUpdated >> protocolVersion; + + // make sure signature isn't in the future (past is OK) + if (sigTime > GetAdjustedTime() + 60 * 60) { + LogPrintf("dsee - Signature rejected, too far into the future %s\n", vin.ToString().c_str()); + return; + } + + bool isLocal = addr.IsRFC1918() || addr.IsLocal(); + //if(Params().MineBlocksOnDemand()) isLocal = false; + + std::string vchPubKey(pubkey.begin(), pubkey.end()); + std::string vchPubKey2(pubkey2.begin(), pubkey2.end()); + + strMessage = addr.ToString() + boost::lexical_cast(sigTime) + vchPubKey + vchPubKey2 + boost::lexical_cast(protocolVersion); + + if(protocolVersion < MIN_MN_PROTO_VERSION) { + LogPrintf("dsee - ignoring outdated masternode %s protocol version %d\n", vin.ToString().c_str(), protocolVersion); + return; + } + + CScript pubkeyScript; + pubkeyScript =GetScriptForDestination(pubkey.GetID()); + + if(pubkeyScript.size() != 25) { + LogPrintf("dsee - pubkey the wrong size\n"); + Misbehaving(pfrom->GetId(), 100); + return; + } + + CScript pubkeyScript2; + pubkeyScript2 =GetScriptForDestination(pubkey2.GetID()); + + if(pubkeyScript2.size() != 25) { + LogPrintf("dsee - pubkey2 the wrong size\n"); + Misbehaving(pfrom->GetId(), 100); + return; + } + + std::string errorMessage = ""; + if(!darkSendSigner.VerifyMessage(pubkey, vchSig, strMessage, errorMessage)){ + LogPrintf("dsee - Got bad masternode address signature\n"); + Misbehaving(pfrom->GetId(), 100); + return; + } + + + + //search existing masternode list, this is where we update existing masternodes with new dsee broadcasts + LOCK(cs_masternodes); + BOOST_FOREACH(CMasterNode& mn, vecMasternodes) { + if(mn.vin.prevout == vin.prevout) { + // count == -1 when it's a new entry + // e.g. We don't want the entry relayed/time updated when we're syncing the list + // mn.pubkey = pubkey, IsVinAssociatedWithPubkey is validated once below, + // after that they just need to match + if(count == -1 && mn.pubkey == pubkey && !mn.UpdatedWithin(MASTERNODE_MIN_DSEE_SECONDS)){ + mn.UpdateLastSeen(); + + if(mn.now < sigTime){ //take the newest entry + LogPrintf("dsee - Got updated entry for %s\n", addr.ToString().c_str()); + mn.pubkey2 = pubkey2; + mn.now = sigTime; + mn.sig = vchSig; + mn.protocolVersion = protocolVersion; + mn.addr = addr; + + RelayDarkSendElectionEntry(vin, addr, vchSig, sigTime, pubkey, pubkey2, count, current, lastUpdated, protocolVersion); + } + } + + return; + } + } + + // make sure the vout that was signed is related to the transaction that spawned the masternode + // - this is expensive, so it's only done once per masternode + if(!darkSendSigner.IsVinAssociatedWithPubkey(vin, pubkey)) { + LogPrintf("dsee - Got mismatched pubkey and vin\n"); + Misbehaving(pfrom->GetId(), 100); + return; + } + + if(fDebug) LogPrintf("dsee - Got NEW masternode entry %s\n", addr.ToString().c_str()); + + // make sure it's still unspent + // - this is checked later by .check() in many places and by ThreadCheckDarkSendPool() + + CValidationState state; + CTransaction tx = CTransaction(); + CTxOut vout = CTxOut(4999*COIN, darkSendPool.collateralPubKey); + tx.vin.push_back(vin); + tx.vout.push_back(vout); + //if(AcceptableInputs(mempool, state, tx)){ + bool* pfMissingInputs = false; + if(AcceptableInputs(mempool, tx, false, pfMissingInputs)){ + if(fDebug) LogPrintf("dsee - Accepted masternode entry %i %i\n", count, current); + + if(GetInputAge(vin) < MASTERNODE_MIN_CONFIRMATIONS){ + LogPrintf("dsee - Input must have least %d confirmations\n", MASTERNODE_MIN_CONFIRMATIONS); + Misbehaving(pfrom->GetId(), 20); + return; + } + + // use this as a peer + addrman.Add(CAddress(addr), pfrom->addr, 2*60*60); + + // add our masternode + CMasterNode mn(addr, vin, pubkey, vchSig, sigTime, pubkey2, protocolVersion); + mn.UpdateLastSeen(lastUpdated); + vecMasternodes.push_back(mn); + + // if it matches our masternodeprivkey, then we've been remotely activated + if(pubkey2 == activeMasternode.pubKeyMasternode && protocolVersion == PROTOCOL_VERSION){ + activeMasternode.EnableHotColdMasterNode(vin, addr); + } + + if(count == -1 && !isLocal) + RelayDarkSendElectionEntry(vin, addr, vchSig, sigTime, pubkey, pubkey2, count, current, lastUpdated, protocolVersion); + + } else { + LogPrintf("dsee - Rejected masternode entry %s\n", addr.ToString().c_str()); + + int nDoS = 0; + if (state.IsInvalid(nDoS)) + { + LogPrintf("dsee - %s from %s %s was not accepted into the memory pool\n", tx.GetHash().ToString().c_str(), + pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str()); + if (nDoS > 0) + Misbehaving(pfrom->GetId(), nDoS); + } + } + } + + else if (strCommand == "dseep") { //DarkSend Election Entry Ping + if(fLiteMode) return; //disable all darksend/masternode related functionality + bool fIsInitialDownload = IsInitialBlockDownload(); + if(fIsInitialDownload) return; + + CTxIn vin; + vector vchSig; + int64_t sigTime; + bool stop; + vRecv >> vin >> vchSig >> sigTime >> stop; + + //LogPrintf("dseep - Received: vin: %s sigTime: %lld stop: %s\n", vin.ToString().c_str(), sigTime, stop ? "true" : "false"); + + if (sigTime > GetAdjustedTime() + 60 * 60) { + LogPrintf("dseep - Signature rejected, too far into the future %s\n", vin.ToString().c_str()); + return; + } + + if (sigTime <= GetAdjustedTime() - 60 * 60) { + LogPrintf("dseep - Signature rejected, too far into the past %s - %d %d \n", vin.ToString().c_str(), sigTime, GetAdjustedTime()); + return; + } + + // see if we have this masternode + LOCK(cs_masternodes); + BOOST_FOREACH(CMasterNode& mn, vecMasternodes) { + if(mn.vin.prevout == vin.prevout) { + // LogPrintf("dseep - Found corresponding mn for vin: %s\n", vin.ToString().c_str()); + // take this only if it's newer + if(mn.lastDseep < sigTime){ + std::string strMessage = mn.addr.ToString() + boost::lexical_cast(sigTime) + boost::lexical_cast(stop); + + std::string errorMessage = ""; + if(!darkSendSigner.VerifyMessage(mn.pubkey2, vchSig, strMessage, errorMessage)){ + LogPrintf("dseep - Got bad masternode address signature %s \n", vin.ToString().c_str()); + //Misbehaving(pfrom->GetId(), 100); + return; + } + + mn.lastDseep = sigTime; + + if(!mn.UpdatedWithin(MASTERNODE_MIN_DSEEP_SECONDS)){ + mn.UpdateLastSeen(); + if(stop) { + mn.Disable(); + mn.Check(); + } + RelayDarkSendElectionEntryPing(vin, vchSig, sigTime, stop); + } + } + return; + } + } + + if(fDebug) LogPrintf("dseep - Couldn't find masternode entry %s\n", vin.ToString().c_str()); + + std::map::iterator i = askedForMasternodeListEntry.find(vin.prevout); + if (i != askedForMasternodeListEntry.end()){ + int64_t t = (*i).second; + if (GetTime() < t) { + // we've asked recently + return; + } + } + + // ask for the dsee info once from the node that sent dseep + + LogPrintf("dseep - Asking source node for missing entry %s\n", vin.ToString().c_str()); + pfrom->PushMessage("dseg", vin); + int64_t askAgain = GetTime()+(60*60*24); + askedForMasternodeListEntry[vin.prevout] = askAgain; + + } else if (strCommand == "dseg") { //Get masternode list or specific entry + if(fLiteMode) return; //disable all darksend/masternode related functionality + CTxIn vin; + vRecv >> vin; + + if(vin == CTxIn()) { //only should ask for this once + //local network + //Note tor peers show up as local proxied addrs //if(!pfrom->addr.IsRFC1918())//&& !Params().MineBlocksOnDemand()) + //{ + std::map::iterator i = askedForMasternodeList.find(pfrom->addr); + if (i != askedForMasternodeList.end()) + { + int64_t t = (*i).second; + if (GetTime() < t) { + //Misbehaving(pfrom->GetId(), 34); + //LogPrintf("dseg - peer already asked me for the list\n"); + //return; + } + } + + int64_t askAgain = GetTime()+(60*60*3); + askedForMasternodeList[pfrom->addr] = askAgain; + //} + } //else, asking for a specific node which is ok + + LOCK(cs_masternodes); + int count = vecMasternodes.size(); + int i = 0; + + BOOST_FOREACH(CMasterNode mn, vecMasternodes) { + + if(mn.addr.IsRFC1918()) continue; //local network + + if(vin == CTxIn()){ + mn.Check(); + if(mn.IsEnabled()) { + if(fDebug) LogPrintf("dseg - Sending masternode entry - %s \n", mn.addr.ToString().c_str()); + pfrom->PushMessage("dsee", mn.vin, mn.addr, mn.sig, mn.now, mn.pubkey, mn.pubkey2, count, i, mn.lastTimeSeen, mn.protocolVersion); + } + } else if (vin == mn.vin) { + if(fDebug) LogPrintf("dseg - Sending masternode entry - %s \n", mn.addr.ToString().c_str()); + pfrom->PushMessage("dsee", mn.vin, mn.addr, mn.sig, mn.now, mn.pubkey, mn.pubkey2, count, i, mn.lastTimeSeen, mn.protocolVersion); + LogPrintf("dseg - Sent 1 masternode entries to %s\n", pfrom->addr.ToString().c_str()); + return; + } + i++; + } + + LogPrintf("dseg - Sent %d masternode entries to %s\n", count, pfrom->addr.ToString().c_str()); + } + + else if (strCommand == "mnget") { //Masternode Payments Request Sync + if(fLiteMode) return; //disable all darksend/masternode related functionality + + /*if(pfrom->HasFulfilledRequest("mnget")) { + LogPrintf("mnget - peer already asked me for the list\n"); + Misbehaving(pfrom->GetId(), 20); + return; + }*/ + + pfrom->FulfilledRequest("mnget"); + masternodePayments.Sync(pfrom); + LogPrintf("mnget - Sent masternode winners to %s\n", pfrom->addr.ToString().c_str()); + } + else if (strCommand == "mnw") { //Masternode Payments Declare Winner + //this is required in litemode + CMasternodePaymentWinner winner; + int a = 0; + vRecv >> winner >> a; + + if(pindexBest == NULL) return; + + uint256 hash = winner.GetHash(); + if(mapSeenMasternodeVotes.count(hash)) { + if(fDebug) LogPrintf("mnw - seen vote %s Height %d bestHeight %d\n", hash.ToString().c_str(), winner.nBlockHeight, pindexBest->nHeight); + return; + } + + if(winner.nBlockHeight < pindexBest->nHeight - 10 || winner.nBlockHeight > pindexBest->nHeight+20){ + LogPrintf("mnw - winner out of range %s Height %d bestHeight %d\n", winner.vin.ToString().c_str(), winner.nBlockHeight, pindexBest->nHeight); + return; + } + + if(winner.vin.nSequence != std::numeric_limits::max()){ + LogPrintf("mnw - invalid nSequence\n"); + Misbehaving(pfrom->GetId(), 100); + return; + } + + LogPrintf("mnw - winning vote %s Height %d bestHeight %d\n", winner.vin.ToString().c_str(), winner.nBlockHeight, pindexBest->nHeight); + + if(!masternodePayments.CheckSignature(winner)){ + LogPrintf("mnw - invalid signature\n"); + Misbehaving(pfrom->GetId(), 100); + return; + } + + mapSeenMasternodeVotes.insert(make_pair(hash, winner)); + + if(masternodePayments.AddWinningMasternode(winner)){ + masternodePayments.Relay(winner); + } + } +} + +struct CompareValueOnly +{ + bool operator()(const pair& t1, + const pair& t2) const + { + return t1.first < t2.first; + } +}; + +struct CompareValueOnly2 +{ + bool operator()(const pair& t1, + const pair& t2) const + { + return t1.first < t2.first; + } +}; + +int CountMasternodesAboveProtocol(int protocolVersion) +{ + int i = 0; + LOCK(cs_masternodes); + BOOST_FOREACH(CMasterNode& mn, vecMasternodes) { + if(mn.protocolVersion < protocolVersion) continue; + i++; + } + + return i; + +} + + +int GetMasternodeByVin(CTxIn& vin) +{ + int i = 0; + LOCK(cs_masternodes); + BOOST_FOREACH(CMasterNode& mn, vecMasternodes) { + if (mn.vin == vin) return i; + i++; + } + + return -1; +} + +int GetCurrentMasterNode(int mod, int64_t nBlockHeight, int minProtocol) +{ + int i = 0; + unsigned int score = 0; + int winner = -1; + LOCK(cs_masternodes); + // scan for winner + BOOST_FOREACH(CMasterNode mn, vecMasternodes) { + mn.Check(); + if(mn.protocolVersion < minProtocol) continue; + if(!mn.IsEnabled()) { + i++; + continue; + } + + // calculate the score for each masternode + uint256 n = mn.CalculateScore(mod, nBlockHeight); + unsigned int n2 = 0; + memcpy(&n2, &n, sizeof(n2)); + + // determine the winner + if(n2 > score){ + score = n2; + winner = i; + } + i++; + } + + return winner; +} + +int GetMasternodeByRank(int findRank, int64_t nBlockHeight, int minProtocol) +{ + LOCK(cs_masternodes); + int i = 0; + + std::vector > vecMasternodeScores; + + i = 0; + BOOST_FOREACH(CMasterNode mn, vecMasternodes) { + mn.Check(); + if(mn.protocolVersion < minProtocol) continue; + if(!mn.IsEnabled()) { + i++; + continue; + } + + uint256 n = mn.CalculateScore(1, nBlockHeight); + unsigned int n2 = 0; + memcpy(&n2, &n, sizeof(n2)); + + vecMasternodeScores.push_back(make_pair(n2, i)); + i++; + } + + sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareValueOnly2()); + + int rank = 0; + BOOST_FOREACH (PAIRTYPE(unsigned int, int)& s, vecMasternodeScores){ + rank++; + if(rank == findRank) return s.second; + } + + return -1; +} + +int GetMasternodeRank(CTxIn& vin, int64_t nBlockHeight, int minProtocol) +{ + LOCK(cs_masternodes); + std::vector > vecMasternodeScores; + + BOOST_FOREACH(CMasterNode& mn, vecMasternodes) { + mn.Check(); + + if(mn.protocolVersion < minProtocol) continue; + if(!mn.IsEnabled()) { + continue; + } + + uint256 n = mn.CalculateScore(1, nBlockHeight); + unsigned int n2 = 0; + memcpy(&n2, &n, sizeof(n2)); + + vecMasternodeScores.push_back(make_pair(n2, mn.vin)); + } + + sort(vecMasternodeScores.rbegin(), vecMasternodeScores.rend(), CompareValueOnly()); + + unsigned int rank = 0; + BOOST_FOREACH (PAIRTYPE(unsigned int, CTxIn)& s, vecMasternodeScores){ + rank++; + if(s.second == vin) { + return rank; + } + } + + return -1; +} + +//Get the last hash that matches the modulus given. Processed in reverse order +bool GetBlockHash(uint256& hash, int nBlockHeight) +{ + if (pindexBest == NULL) return false; + + if(nBlockHeight == 0) + nBlockHeight = pindexBest->nHeight; + + if(mapCacheBlockHashes.count(nBlockHeight)){ + hash = mapCacheBlockHashes[nBlockHeight]; + return true; + } + + const CBlockIndex *BlockLastSolved = pindexBest; + const CBlockIndex *BlockReading = pindexBest; + + if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || pindexBest->nHeight+1 < nBlockHeight) return false; + + int nBlocksAgo = 0; + if(nBlockHeight > 0) nBlocksAgo = (pindexBest->nHeight+1)-nBlockHeight; + assert(nBlocksAgo >= 0); + + int n = 0; + for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) { + if(n >= nBlocksAgo){ + hash = BlockReading->GetBlockHash(); + mapCacheBlockHashes[nBlockHeight] = hash; + return true; + } + n++; + + if (BlockReading->pprev == NULL) { assert(BlockReading); break; } + BlockReading = BlockReading->pprev; + } + + return false; +} + +// +// Deterministically calculate a given "score" for a masternode depending on how close it's hash is to +// the proof of work for that block. The further away they are the better, the furthest will win the election +// and get paid this block +// +uint256 CMasterNode::CalculateScore(int mod, int64_t nBlockHeight) +{ + if(pindexBest == NULL) return 0; + + uint256 hash = 0; + uint256 aux = vin.prevout.hash + vin.prevout.n; + + if(!GetBlockHash(hash, nBlockHeight)) return 0; + + uint256 hash2 = Hash(BEGIN(hash), END(hash)); + uint256 hash3 = Hash(BEGIN(hash), END(aux)); + + uint256 r = (hash3 > hash2 ? hash3 - hash2 : hash2 - hash3); + + return r; +} + +void CMasterNode::Check() +{ + //once spent, stop doing the checks + if(enabled==3) return; + + + if(!UpdatedWithin(MASTERNODE_REMOVAL_SECONDS)){ + enabled = 4; + return; + } + + if(!UpdatedWithin(MASTERNODE_EXPIRATION_SECONDS)){ + enabled = 2; + return; + } + + if(!unitTest){ + CValidationState state; + CTransaction tx = CTransaction(); + CTxOut vout = CTxOut(4999*COIN, darkSendPool.collateralPubKey); + tx.vin.push_back(vin); + tx.vout.push_back(vout); + + //if(!AcceptableInputs(mempool, state, tx)){ + bool* pfMissingInputs = false; + if(!AcceptableInputs(mempool, tx, false, pfMissingInputs)){ + enabled = 3; + return; + } + } + + enabled = 1; // OK +} + +bool CMasternodePayments::CheckSignature(CMasternodePaymentWinner& winner) +{ + //note: need to investigate why this is failing + std::string strMessage = winner.vin.ToString().c_str() + boost::lexical_cast(winner.nBlockHeight) + winner.payee.ToString(); + std::string strPubKey = strMainPubKey ; + CPubKey pubkey(ParseHex(strPubKey)); + + std::string errorMessage = ""; + if(!darkSendSigner.VerifyMessage(pubkey, winner.vchSig, strMessage, errorMessage)){ + return false; + } + + return true; +} + +bool CMasternodePayments::Sign(CMasternodePaymentWinner& winner) +{ + std::string strMessage = winner.vin.ToString().c_str() + boost::lexical_cast(winner.nBlockHeight) + winner.payee.ToString(); + + CKey key2; + CPubKey pubkey2; + std::string errorMessage = ""; + + if(!darkSendSigner.SetKey(strMasterPrivKey, errorMessage, key2, pubkey2)) + { + LogPrintf("CMasternodePayments::Sign - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage.c_str()); + return false; + } + + if(!darkSendSigner.SignMessage(strMessage, errorMessage, winner.vchSig, key2)) { + LogPrintf("CMasternodePayments::Sign - Sign message failed"); + return false; + } + + if(!darkSendSigner.VerifyMessage(pubkey2, winner.vchSig, strMessage, errorMessage)) { + LogPrintf("CMasternodePayments::Sign - Verify message failed"); + return false; + } + + return true; +} + +uint64_t CMasternodePayments::CalculateScore(uint256 blockHash, CTxIn& vin) +{ + uint256 n1 = blockHash; + uint256 n2 = Hash(BEGIN(n1), END(n1)); + uint256 n3 = Hash(BEGIN(vin.prevout.hash), END(vin.prevout.hash)); + uint256 n4 = n3 > n2 ? (n3 - n2) : (n2 - n3); + + //printf(" -- CMasternodePayments CalculateScore() n2 = %d \n", n2.Get64()); + //printf(" -- CMasternodePayments CalculateScore() n3 = %d \n", n3.Get64()); + //printf(" -- CMasternodePayments CalculateScore() n4 = %d \n", n4.Get64()); + + return n4.Get64(); +} + +bool CMasternodePayments::GetBlockPayee(int nBlockHeight, CScript& payee) +{ + BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning){ + if(winner.nBlockHeight == nBlockHeight) { + payee = winner.payee; + return true; + } + } + + return false; +} + +bool CMasternodePayments::GetWinningMasternode(int nBlockHeight, CTxIn& vinOut) +{ + BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning){ + if(winner.nBlockHeight == nBlockHeight) { + vinOut = winner.vin; + return true; + } + } + + return false; +} + +bool CMasternodePayments::AddWinningMasternode(CMasternodePaymentWinner& winnerIn) +{ + uint256 blockHash = 0; + if(!GetBlockHash(blockHash, winnerIn.nBlockHeight-576)) { + return false; + } + + winnerIn.score = CalculateScore(blockHash, winnerIn.vin); + + bool foundBlock = false; + BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning){ + if(winner.nBlockHeight == winnerIn.nBlockHeight) { + foundBlock = true; + if(winner.score < winnerIn.score){ + winner.score = winnerIn.score; + winner.vin = winnerIn.vin; + winner.payee = winnerIn.payee; + winner.vchSig = winnerIn.vchSig; + + return true; + } + } + } + + // if it's not in the vector + if(!foundBlock){ + vWinning.push_back(winnerIn); + mapSeenMasternodeVotes.insert(make_pair(winnerIn.GetHash(), winnerIn)); + + return true; + } + + return false; +} + +void CMasternodePayments::CleanPaymentList() +{ + LOCK(cs_masternodes); + if(pindexBest == NULL) return; + + int nLimit = std::max(((int)vecMasternodes.size())*2, 1000); + + vector::iterator it; + for(it=vWinning.begin();itnHeight - (*it).nBlockHeight > nLimit){ + if(fDebug) LogPrintf("CMasternodePayments::CleanPaymentList - Removing old masternode payment - block %d\n", (*it).nBlockHeight); + vWinning.erase(it); + break; + } + } +} + +bool CMasternodePayments::ProcessBlock(int nBlockHeight) +{ + LOCK(cs_masternodes); + if(!enabled) return false; + CMasternodePaymentWinner winner; + + std::vector vecLastPayments; + int c = 0; + BOOST_REVERSE_FOREACH(CMasternodePaymentWinner& winner, vWinning){ + vecLastPayments.push_back(winner.vin); + //if we have one full payment cycle, break + if(++c > (int)vecMasternodes.size()) break; + } + + std::random_shuffle ( vecMasternodes.begin(), vecMasternodes.end() ); + BOOST_FOREACH(CMasterNode& mn, vecMasternodes) { + bool found = false; + BOOST_FOREACH(CTxIn& vin, vecLastPayments) + if(mn.vin == vin) found = true; + + if(found) continue; + + mn.Check(); + if(!mn.IsEnabled()) { + continue; + } + + winner.score = 0; + winner.nBlockHeight = nBlockHeight; + winner.vin = mn.vin; + winner.payee =GetScriptForDestination(mn.pubkey.GetID()); + + break; + } + + //if we can't find someone to get paid, pick randomly + if(winner.nBlockHeight == 0 && vecMasternodes.size() > 0) { + winner.score = 0; + winner.nBlockHeight = nBlockHeight; + winner.vin = vecMasternodes[0].vin; + winner.payee =GetScriptForDestination(vecMasternodes[0].pubkey.GetID()); + } + + if(Sign(winner)){ + if(AddWinningMasternode(winner)){ + Relay(winner); + return true; + } + } + + return false; +} + +void CMasternodePayments::Relay(CMasternodePaymentWinner& winner) +{ + CInv inv(MSG_MASTERNODE_WINNER, winner.GetHash()); + + vector vInv; + vInv.push_back(inv); + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes){ + pnode->PushMessage("inv", vInv); + } +} + +void CMasternodePayments::Sync(CNode* node) +{ + int a = 0; + BOOST_FOREACH(CMasternodePaymentWinner& winner, vWinning) + if(winner.nBlockHeight >= pindexBest->nHeight-10 && winner.nBlockHeight <= pindexBest->nHeight + 20) + node->PushMessage("mnw", winner, a); +} + + +bool CMasternodePayments::SetPrivKey(std::string strPrivKey) +{ + CMasternodePaymentWinner winner; + + // Test signing successful, proceed + strMasterPrivKey = strPrivKey; + + Sign(winner); + + if(CheckSignature(winner)){ + LogPrintf("CMasternodePayments::SetPrivKey - Successfully initialized as masternode payments master\n"); + enabled = true; + return true; + } else { + return false; + } +} diff --git a/src/masternode.h b/src/masternode.h new file mode 100644 index 0000000..3a41fb5 --- /dev/null +++ b/src/masternode.h @@ -0,0 +1,247 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2012 The Darkcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. +#ifndef MASTERNODE_H +#define MASTERNODE_H + +#include "uint256.h" +#include "uint256.h" +#include "sync.h" +#include "net.h" +#include "key.h" +#include "util.h" +#include "base58.h" +#include "main.h" +#include "timedata.h" +#include "script.h" + +class CMasterNode; +class CMasternodePayments; +class uint256; + +#define MASTERNODE_NOT_PROCESSED 0 // initial state +#define MASTERNODE_IS_CAPABLE 1 +#define MASTERNODE_NOT_CAPABLE 2 +#define MASTERNODE_STOPPED 3 +#define MASTERNODE_INPUT_TOO_NEW 4 +#define MASTERNODE_PORT_NOT_OPEN 6 +#define MASTERNODE_PORT_OPEN 7 +#define MASTERNODE_SYNC_IN_PROCESS 8 +#define MASTERNODE_REMOTELY_ENABLED 9 + +#define MASTERNODE_MIN_CONFIRMATIONS 7 +#define MASTERNODE_MIN_DSEEP_SECONDS (20*60) +#define MASTERNODE_MIN_DSEE_SECONDS (1*60) +#define MASTERNODE_PING_SECONDS (20) //(1*60) +#define MASTERNODE_EXPIRATION_SECONDS (65*60) +#define MASTERNODE_REMOVAL_SECONDS (70*60) + +using namespace std; + +class CMasternodePaymentWinner; + +extern CCriticalSection cs_masternodes; +extern std::vector vecMasternodes; +extern CMasternodePayments masternodePayments; +extern std::vector vecMasternodeAskedFor; +extern map mapSeenMasternodeVotes; +extern map mapCacheBlockHashes; + + +// manage the masternode connections +void ProcessMasternodeConnections(); +int CountMasternodesAboveProtocol(int protocolVersion); + + +void ProcessMessageMasternode(CNode* pfrom, std::string& strCommand, CDataStream& vRecv); + +// +// The Masternode Class. For managing the darksend process. It contains the input of the 1000GENIUS, signature to prove +// it's the one who own that ip address and code for calculating the payment election. +// +class CMasterNode +{ +public: + static int minProtoVersion; + CService addr; + CTxIn vin; + int64_t lastTimeSeen; + CPubKey pubkey; + CPubKey pubkey2; + std::vector sig; + int64_t now; //dsee message times + int64_t lastDseep; + int cacheInputAge; + int cacheInputAgeBlock; + int enabled; + bool unitTest; + bool allowFreeTx; + int protocolVersion; + + //the dsq count from the last dsq broadcast of this node + int64_t nLastDsq; + + CMasterNode(CService newAddr, CTxIn newVin, CPubKey newPubkey, std::vector newSig, int64_t newNow, CPubKey newPubkey2, int protocolVersionIn) + { + addr = newAddr; + vin = newVin; + pubkey = newPubkey; + pubkey2 = newPubkey2; + sig = newSig; + now = newNow; + enabled = 1; + lastTimeSeen = 0; + unitTest = false; + cacheInputAge = 0; + cacheInputAgeBlock = 0; + nLastDsq = 0; + lastDseep = 0; + allowFreeTx = true; + protocolVersion = protocolVersionIn; + } + + uint256 CalculateScore(int mod=1, int64_t nBlockHeight=0); + + void UpdateLastSeen(int64_t override=0) + { + if(override == 0){ + lastTimeSeen = GetAdjustedTime(); + } else { + lastTimeSeen = override; + } + } + + inline uint64_t SliceHash(uint256& hash, int slice) + { + uint64_t n = 0; + memcpy(&n, &hash+slice*64, 64); + return n; + } + + void Check(); + + bool UpdatedWithin(int seconds) + { + // LogPrintf("UpdatedWithin %d, %d -- %d \n", GetAdjustedTime() , lastTimeSeen, (GetAdjustedTime() - lastTimeSeen) < seconds); + + return (GetAdjustedTime() - lastTimeSeen) < seconds; + } + + void Disable() + { + lastTimeSeen = 0; + } + + bool IsEnabled() + { + return enabled == 1; + } + + int GetMasternodeInputAge() + { + if(pindexBest == NULL) return 0; + + if(cacheInputAge == 0){ + cacheInputAge = GetInputAge(vin); + cacheInputAgeBlock = pindexBest->nHeight; + } + + return cacheInputAge+(pindexBest->nHeight-cacheInputAgeBlock); + } +}; + + +// Get the current winner for this block +int GetCurrentMasterNode(int mod=1, int64_t nBlockHeight=0, int minProtocol=CMasterNode::minProtoVersion); + +int GetMasternodeByVin(CTxIn& vin); +int GetMasternodeRank(CTxIn& vin, int64_t nBlockHeight=0, int minProtocol=CMasterNode::minProtoVersion); +int GetMasternodeByRank(int findRank, int64_t nBlockHeight=0, int minProtocol=CMasterNode::minProtoVersion); + + +// for storing the winning payments +class CMasternodePaymentWinner +{ +public: + int nBlockHeight; + CTxIn vin; + CScript payee; + std::vector vchSig; + uint64_t score; + + CMasternodePaymentWinner() { + nBlockHeight = 0; + score = 0; + vin = CTxIn(); + payee = CScript(); + } + + uint256 GetHash(){ + uint256 n2 = Hash(BEGIN(nBlockHeight), END(nBlockHeight)); + uint256 n3 = vin.prevout.hash > n2 ? (vin.prevout.hash - n2) : (n2 - vin.prevout.hash); + + return n3; + } + + ADD_SERIALIZE_METHODS; + + template + inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion){ + unsigned int nSerSize = 0; + READWRITE(nBlockHeight); + READWRITE(payee); + READWRITE(vin); + READWRITE(score); + READWRITE(vchSig); + } +}; + +// +// Masternode Payments Class +// Keeps track of who should get paid for which blocks +// + +class CMasternodePayments +{ +private: + std::vector vWinning; + int nSyncedFromPeer; + std::string strMasterPrivKey; + std::string strTestPubKey; + std::string strMainPubKey; + bool enabled; + +public: + + CMasternodePayments() { + strMainPubKey = "0419e538a30d8acd730f592f1fe49e71c09ff4dd24ff09ae43e93a39c32bc5b2c17d762cfd332078075525e0882a92848b411f578d5b91ca6f71f78cd518e2a260"; + strTestPubKey = "0419e538a30d8acd730f592f1fe49e71c09ff4dd24ff09ae43e93a39c32bc5b2c17d762cfd332078075525e0882a92848b411f578d5b91ca6f71f78cd518e2a260"; + enabled = false; + } + + bool SetPrivKey(std::string strPrivKey); + bool CheckSignature(CMasternodePaymentWinner& winner); + bool Sign(CMasternodePaymentWinner& winner); + + // Deterministically calculate a given "score" for a masternode depending on how close it's hash is + // to the blockHeight. The further away they are the better, the furthest will win the election + // and get paid this block + // + + uint64_t CalculateScore(uint256 blockHash, CTxIn& vin); + bool GetWinningMasternode(int nBlockHeight, CTxIn& vinOut); + bool AddWinningMasternode(CMasternodePaymentWinner& winner); + bool ProcessBlock(int nBlockHeight); + void Relay(CMasternodePaymentWinner& winner); + void Sync(CNode* node); + void CleanPaymentList(); + int LastPayment(CMasterNode& mn); + + //slow + bool GetBlockPayee(int nBlockHeight, CScript& payee); +}; + + + +#endif diff --git a/src/masternodeconfig.cpp b/src/masternodeconfig.cpp new file mode 100644 index 0000000..4f32dd5 --- /dev/null +++ b/src/masternodeconfig.cpp @@ -0,0 +1,43 @@ + +#include "net.h" +#include "masternodeconfig.h" +#include "util.h" + +CMasternodeConfig masternodeConfig; + +void CMasternodeConfig::add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex) { + CMasternodeEntry cme(alias, ip, privKey, txHash, outputIndex); + entries.push_back(cme); +} + +bool CMasternodeConfig::read(std::string& strErr) { + boost::filesystem::ifstream streamConfig(GetMasternodeConfigFile()); + if (!streamConfig.good()) { + return true; // No masternode.conf file is OK + } + + for(std::string line; std::getline(streamConfig, line); ) + { + if(line.empty()) { + continue; + } + std::istringstream iss(line); + std::string alias, ip, privKey, txHash, outputIndex; + if (!(iss >> alias >> ip >> privKey >> txHash >> outputIndex)) { + strErr = "Could not parse masternode.conf line: " + line; + streamConfig.close(); + return false; + } + +/* if(CService(ip).GetPort() != 19999 && CService(ip).GetPort() != 9999) { + strErr = "Invalid port (must be 9999 for mainnet or 19999 for testnet) detected in masternode.conf: " + line; + streamConfig.close(); + return false; + }*/ + + add(alias, ip, privKey, txHash, outputIndex); + } + + streamConfig.close(); + return true; +} diff --git a/src/masternodeconfig.h b/src/masternodeconfig.h new file mode 100644 index 0000000..c5afb68 --- /dev/null +++ b/src/masternodeconfig.h @@ -0,0 +1,102 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2012 The Bitcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#ifndef SRC_MASTERNODECONFIG_H_ +#define SRC_MASTERNODECONFIG_H_ + +#include +#include + +#include +#include + +class CMasternodeConfig; +extern CMasternodeConfig masternodeConfig; + +class CMasternodeConfig +{ + +public: + class CMasternodeEntry { + + private: + std::string alias; + std::string ip; + std::string privKey; + std::string txHash; + std::string outputIndex; + + public: + + CMasternodeEntry(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex) { + this->alias = alias; + this->ip = ip; + this->privKey = privKey; + this->txHash = txHash; + this->outputIndex = outputIndex; + } + + const std::string& getAlias() const { + return alias; + } + + void setAlias(const std::string& alias) { + this->alias = alias; + } + + const std::string& getOutputIndex() const { + return outputIndex; + } + + void setOutputIndex(const std::string& outputIndex) { + this->outputIndex = outputIndex; + } + + const std::string& getPrivKey() const { + return privKey; + } + + void setPrivKey(const std::string& privKey) { + this->privKey = privKey; + } + + const std::string& getTxHash() const { + return txHash; + } + + void setTxHash(const std::string& txHash) { + this->txHash = txHash; + } + + const std::string& getIp() const { + return ip; + } + + void setIp(const std::string& ip) { + this->ip = ip; + } + }; + + CMasternodeConfig() { + entries = std::vector(); + } + + void clear(); + bool read(std::string& strErr); + void add(std::string alias, std::string ip, std::string privKey, std::string txHash, std::string outputIndex); + + std::vector& getEntries() { + return entries; + } + +private: + std::vector entries; + + +}; + + +#endif /* SRC_MASTERNODECONFIG_H_ */ + diff --git a/src/miner.cpp b/src/miner.cpp index 2608731..03d6aa1 100644 --- a/src/miner.cpp +++ b/src/miner.cpp @@ -7,6 +7,8 @@ #include "txdb.h" #include "miner.h" #include "kernel.h" +#include "masternode.h" + using namespace std; @@ -160,12 +162,13 @@ CBlock* CreateNewBlock(CReserveKey& reservekey, bool fProofOfStake, int64_t* pFe pblock->nBits = GetNextTargetRequired(pindexPrev, fProofOfStake); + // Collect memory pool transactions into the block int64_t nFees = 0; { LOCK2(cs_main, mempool.cs); CTxDB txdb("r"); - +//>GENIUS< // Priority order to process transactions list vOrphan; // list memory doesn't move map > mapDependers; @@ -353,7 +356,7 @@ CBlock* CreateNewBlock(CReserveKey& reservekey, bool fProofOfStake, int64_t* pFe if (fDebug && GetBoolArg("-printpriority", false)) LogPrintf("CreateNewBlock(): total size %u\n", nBlockSize); - +// >GENIUS< if (!fProofOfStake) pblock->vtx[0].vout[0].nValue = GetProofOfWorkReward(nFees); @@ -545,11 +548,17 @@ void ThreadStakeMiner(CWallet *pwallet) fTryToSync = false; if (vNodes.size() < 3 || pindexBest->GetBlockTime() < GetTime() - 10 * 60) { - MilliSleep(60000); + MilliSleep(10000); continue; } } + if (fMasterNode) + { + MilliSleep(10000); + continue; + } + // // Create new block // diff --git a/src/net.cpp b/src/net.cpp index 80b239b..118a1c5 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -4,13 +4,14 @@ // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "init.h" -#include "irc.h" #include "chainparams.h" #include "db.h" #include "net.h" #include "main.h" #include "addrman.h" #include "ui_interface.h" +#include "darksend.h" +#include "wallet.h" #ifdef WIN32 #include @@ -29,7 +30,7 @@ using namespace std; using namespace boost; -static const int MAX_OUTBOUND_CONNECTIONS = 32; +static const int MAX_OUTBOUND_CONNECTIONS = 20; bool OpenNetworkConnection(const CAddress& addrConnect, CSemaphoreGrant *grantOutbound = NULL, const char *strDest = NULL, bool fOneShot = false); @@ -49,6 +50,7 @@ static map mapLocalHost; static bool vfReachable[NET_MAX] = {}; static bool vfLimited[NET_MAX] = {}; static CNode* pnodeLocalHost = NULL; +CAddress addrSeenByPeer(CService("0.0.0.0", 0), nLocalServices); static CNode* pnodeSync = NULL; uint64_t nLocalHostNonce = 0; static std::vector vhListenSocket; @@ -70,6 +72,9 @@ CCriticalSection cs_setservAddNodeAddresses; vector vAddedNodes; CCriticalSection cs_vAddedNodes; +NodeId nLastNodeId = 0; +CCriticalSection cs_nLastNodeId; + static CSemaphore *semOutbound = NULL; // Signals for message handling @@ -350,7 +355,7 @@ CNode* FindNode(const CService& addr) return NULL; } -CNode* ConnectNode(CAddress addrConnect, const char *pszDest) +CNode* ConnectNode(CAddress addrConnect, const char *pszDest, bool darkSendMaster) { if (pszDest == NULL) { if (IsLocal(addrConnect)) @@ -360,6 +365,9 @@ CNode* ConnectNode(CAddress addrConnect, const char *pszDest) CNode* pnode = FindNode((CService)addrConnect); if (pnode) { + if(darkSendMaster) + pnode->fDarkSendMaster = true; + pnode->AddRef(); return pnode; } @@ -500,12 +508,14 @@ bool CNode::Misbehaving(int howmuch) #define X(name) stats.name = name void CNode::copyStats(CNodeStats &stats) { + stats.nodeid = this->GetId(); X(nServices); X(nLastSend); X(nLastRecv); X(nTimeConnected); X(addrName); X(nVersion); + X(cleanSubVer); X(strSubVer); X(fInbound); X(nStartingHeight); @@ -828,7 +838,7 @@ void ThreadSocketHandler() if (nErr != WSAEWOULDBLOCK) LogPrintf("socket error accept failed: %d\n", nErr); } - else if (nInbound >= GetArg("-maxconnections", 125) - MAX_OUTBOUND_CONNECTIONS) + else if (nInbound >= GetArg("-maxconnections", 25) - MAX_OUTBOUND_CONNECTIONS) { closesocket(hSocket); } @@ -1641,7 +1651,7 @@ void StartNode(boost::thread_group& threadGroup) { if (semOutbound == NULL) { // initialize semaphore - int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 125)); + int nMaxOutbound = min(MAX_OUTBOUND_CONNECTIONS, (int)GetArg("-maxconnections", 25)); semOutbound = new CSemaphore(nMaxOutbound); } @@ -1664,9 +1674,6 @@ void StartNode(boost::thread_group& threadGroup) MapPort(GetBoolArg("-upnp", USE_UPNP)); #endif - // Get addresses from IRC and advertise ours - threadGroup.create_thread(boost::bind(&TraceThread, "irc", &ThreadIRCSeed)); - // Send and receive from sockets, accept connections threadGroup.create_thread(boost::bind(&TraceThread, "net", &ThreadSocketHandler)); @@ -1748,6 +1755,102 @@ void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataSt RelayInventory(inv); } +void RelayTransactionLockReq(const CTransaction& tx, const uint256& hash, bool relayToAll) +{ + CInv inv(MSG_TXLOCK_REQUEST, tx.GetHash()); + + //broadcast the new lock + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + if(!relayToAll && !pnode->fRelayTxes) + continue; + + pnode->PushMessage("txlreq", tx); + } + +} + +void RelayDarkSendFinalTransaction(const int sessionID, const CTransaction& txNew) +{ + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + pnode->PushMessage("dsf", sessionID, txNew); + } +} + +void RelayDarkSendIn(const std::vector& in, const int64_t& nAmount, const CTransaction& txCollateral, const std::vector& out) +{ + LOCK(cs_vNodes); + + BOOST_FOREACH(CNode* pnode, vNodes) + { + if((CNetAddr)darkSendPool.submittedToMasternode != (CNetAddr)pnode->addr) continue; + LogPrintf("RelayDarkSendIn - found master, relaying message - %s \n", pnode->addr.ToString().c_str()); + pnode->PushMessage("dsi", in, nAmount, txCollateral, out); + } +} + +void RelayDarkSendStatus(const int sessionID, const int newState, const int newEntriesCount, const int newAccepted, const std::string error) +{ + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + pnode->PushMessage("dssu", sessionID, newState, newEntriesCount, newAccepted, error); + } +} + +void RelayDarkSendElectionEntry(const CTxIn vin, const CService addr, const std::vector vchSig, const int64_t nNow, const CPubKey pubkey, const CPubKey pubkey2, const int count, const int current, const int64_t lastUpdated, const int protocolVersion) +{ + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + if(!pnode->fRelayTxes) continue; + + pnode->PushMessage("dsee", vin, addr, vchSig, nNow, pubkey, pubkey2, count, current, lastUpdated, protocolVersion); + } +} + +void SendDarkSendElectionEntry(const CTxIn vin, const CService addr, const std::vector vchSig, const int64_t nNow, const CPubKey pubkey, const CPubKey pubkey2, const int count, const int current, const int64_t lastUpdated, const int protocolVersion) +{ + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + pnode->PushMessage("dsee", vin, addr, vchSig, nNow, pubkey, pubkey2, count, current, lastUpdated, protocolVersion); + } +} + +void RelayDarkSendElectionEntryPing(const CTxIn vin, const std::vector vchSig, const int64_t nNow, const bool stop) +{ + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + if(!pnode->fRelayTxes) continue; + + pnode->PushMessage("dseep", vin, vchSig, nNow, stop); + } +} + +void SendDarkSendElectionEntryPing(const CTxIn vin, const std::vector vchSig, const int64_t nNow, const bool stop) +{ + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + pnode->PushMessage("dseep", vin, vchSig, nNow, stop); + } +} + +void RelayDarkSendCompletedTransaction(const int sessionID, const bool error, const std::string errorMessage) +{ + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + pnode->PushMessage("dsc", sessionID, error, errorMessage); + } +} + + void CNode::RecordBytesRecv(uint64_t bytes) { LOCK(cs_totalBytesRecv); diff --git a/src/net.h b/src/net.h index 7bd07ce..5a243db 100644 --- a/src/net.h +++ b/src/net.h @@ -21,6 +21,7 @@ #include "protocol.h" #include "addrman.h" #include "hash.h" +#include "core.h" class CNode; class CBlockIndex; @@ -28,12 +29,12 @@ extern int nBestHeight; /** Time between pings automatically sent out for latency probing and keepalive (in seconds). */ -static const int PING_INTERVAL = 2 * 60; +static const int PING_INTERVAL = 1 * 60; /** Time after which to disconnect, after waiting for a ping response (or inactivity). */ static const int TIMEOUT_INTERVAL = 20 * 60; -inline unsigned int ReceiveFloodSize() { return 1000*GetArg("-maxreceivebuffer", 5*1000); } -inline unsigned int SendBufferSize() { return 1000*GetArg("-maxsendbuffer", 1*1000); } +inline unsigned int ReceiveFloodSize() { return 2000*GetArg("-maxreceivebuffer", 5*1000); } +inline unsigned int SendBufferSize() { return 5000*GetArg("-maxsendbuffer", 1*1000); } void AddOneShot(std::string strDest); bool RecvLine(SOCKET hSocket, std::string& strLine); @@ -41,7 +42,7 @@ void AddressCurrentlyConnected(const CService& addr); CNode* FindNode(const CNetAddr& ip); CNode* FindNode(const std::string& addrName); CNode* FindNode(const CService& ip); -CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL); +CNode* ConnectNode(CAddress addrConnect, const char *strDest = NULL, bool darkSendMaster=false); void MapPort(bool fUseUPnP); unsigned short GetListenPort(); bool BindListenPort(const CService &bindAddr, std::string& strError=REF(std::string())); @@ -58,6 +59,7 @@ struct CNodeSignals CNodeSignals& GetNodeSignals(); +typedef int NodeId; enum { @@ -86,15 +88,22 @@ void SetReachable(enum Network net, bool fFlag = true); CAddress GetLocalAddress(const CNetAddr *paddrPeer = NULL); -enum -{ +enum { MSG_TX = 1, MSG_BLOCK, + // Nodes may always request a MSG_FILTERED_BLOCK in a getdata, however, + // MSG_FILTERED_BLOCK should not appear in any invs except as a part of getdata. + MSG_FILTERED_BLOCK, + MSG_TXLOCK_REQUEST, + MSG_TXLOCK_VOTE, + MSG_SPORK, + MSG_MASTERNODE_WINNER }; extern bool fDiscover; extern uint64_t nLocalServices; extern uint64_t nLocalHostNonce; +extern CAddress addrSeenByPeer; extern CAddrMan addrman; extern std::vector vNodes; @@ -107,18 +116,21 @@ extern std::map mapAlreadyAskedFor; extern std::vector vAddedNodes; extern CCriticalSection cs_vAddedNodes; - +extern NodeId nLastNodeId; +extern CCriticalSection cs_nLastNodeId; class CNodeStats { public: + NodeId nodeid; uint64_t nServices; int64_t nLastSend; int64_t nLastRecv; int64_t nTimeConnected; std::string addrName; int nVersion; + std::string cleanSubVer; std::string strSubVer; bool fInbound; int nStartingHeight; @@ -173,6 +185,29 @@ class CNetMessage { }; +class SecMsgNode +{ +public: + SecMsgNode() + { + lastSeen = 0; + lastMatched = 0; + ignoreUntil = 0; + nWakeCounter = 0; + nPeerId = 0; + fEnabled = false; + }; + + ~SecMsgNode() {}; + + int64_t lastSeen; + int64_t lastMatched; + int64_t ignoreUntil; + uint32_t nWakeCounter; + uint32_t nPeerId; + bool fEnabled; + +}; @@ -203,24 +238,38 @@ class CNode std::string addrName; CService addrLocal; int nVersion; - std::string strSubVer; + // strSubVer is whatever byte array we read from the wire. However, this field is intended + // to be printed out, displayed to humans in various forms and so on. So we sanitize it and + // store the sanitized version in cleanSubVer. The original should be used when dealing with + // the network or wire types and the cleaned string used when displayed or logged. + std::string strSubVer, cleanSubVer; bool fOneShot; bool fClient; bool fInbound; bool fNetworkNode; bool fSuccessfullyConnected; bool fDisconnect; + // We use fRelayTxes for two purposes - + // a) it allows us to not relay tx invs before receiving the peer's version message + // b) the peer may tell us in their version message that we should not relay tx invs + // until they have initialized their bloom filter. + bool fRelayTxes; + bool fDarkSendMaster; CSemaphoreGrant grantOutbound; int nRefCount; + NodeId id; protected: // Denial-of-service detection/prevention // Key is IP address, value is banned-until-time static std::map setBanned; static CCriticalSection cs_setBanned; - int nMisbehavior; + + + std::vector vecRequestsFulfilled; //keep track of what client has asked for public: + int nMisbehavior; uint256 hashContinue; CBlockIndex* pindexLastGetBlocksBegin; uint256 hashLastGetBlocksEnd; @@ -240,6 +289,8 @@ class CNode CCriticalSection cs_inventory; std::multimap mapAskFor; + SecMsgNode smsgData; + // Ping time measurement: // The pong reply we're expecting, or 0 if no pong expected. uint64_t nPingNonceSent; @@ -287,6 +338,11 @@ class CNode nPingUsecTime = 0; fPingQueued = false; + { + LOCK(cs_nLastNodeId); + id = nLastNodeId++; + } + // Be shy and don't send version until we hear if (hSocket != INVALID_SOCKET && !fInbound) PushVersion(); @@ -312,7 +368,9 @@ class CNode void operator=(const CNode&); public: - + NodeId GetId() const { + return id; + } int GetRefCount() { @@ -623,6 +681,37 @@ class CNode } } +template + void PushMessage(const char* pszCommand, const T1& a1, const T2& a2, const T3& a3, const T4& a4, const T5& a5, const T6& a6, const T7& a7, const T8& a8, const T9& a9, const T10& a10) + { + try + { + BeginMessage(pszCommand); + ssSend << a1 << a2 << a3 << a4 << a5 << a6 << a7 << a8 << a9 << a10; + EndMessage(); + } + catch (...) + { + AbortMessage(); + throw; + } + } + + bool HasFulfilledRequest(std::string strRequest) + { + BOOST_FOREACH(std::string& type, vecRequestsFulfilled) + { + if(type == strRequest) return true; + } + return false; + } + + void FulfilledRequest(std::string strRequest) + { + if(HasFulfilledRequest(strRequest)) return; + vecRequestsFulfilled.push_back(strRequest); + } + bool IsSubscribed(unsigned int nChannel); void Subscribe(unsigned int nChannel, unsigned int nHops=0); void CancelSubscribe(unsigned int nChannel); @@ -668,6 +757,16 @@ inline void RelayInventory(const CInv& inv) class CTransaction; void RelayTransaction(const CTransaction& tx, const uint256& hash); void RelayTransaction(const CTransaction& tx, const uint256& hash, const CDataStream& ss); +void RelayTransactionLockReq(const CTransaction& tx, const uint256& hash, bool relayToAll=false); +void RelayDarkSendFinalTransaction(const int sessionID, const CTransaction& txNew); +void RelayDarkSendIn(const std::vector& in, const int64_t& nAmount, const CTransaction& txCollateral, const std::vector& out); +void RelayDarkSendStatus(const int sessionID, const int newState, const int newEntriesCount, const int newAccepted, const std::string error=""); +void RelayDarkSendElectionEntry(const CTxIn vin, const CService addr, const std::vector vchSig, const int64_t nNow, const CPubKey pubkey, const CPubKey pubkey2, const int count, const int current, const int64_t lastUpdated, const int protocolVersion); +void SendDarkSendElectionEntry(const CTxIn vin, const CService addr, const std::vector vchSig, const int64_t nNow, const CPubKey pubkey, const CPubKey pubkey2, const int count, const int current, const int64_t lastUpdated, const int protocolVersion); +void RelayDarkSendElectionEntryPing(const CTxIn vin, const std::vector vchSig, const int64_t nNow, const bool stop); +void SendDarkSendElectionEntryPing(const CTxIn vin, const std::vector vchSig, const int64_t nNow, const bool stop); +void RelayDarkSendCompletedTransaction(const int sessionID, const bool error, const std::string errorMessage); +void RelayDarkSendMasterNodeContestant(); /** Access to the (IP) address database (peers.dat) */ class CAddrDB diff --git a/src/protocol.h b/src/protocol.h index f8b8277..df6d4d6 100644 --- a/src/protocol.h +++ b/src/protocol.h @@ -124,4 +124,6 @@ class CInv uint256 hash; }; + + #endif // __INCLUDED_PROTOCOL_H__ diff --git a/src/qt/addeditadrenalinenode.cpp b/src/qt/addeditadrenalinenode.cpp new file mode 100644 index 0000000..8c0b969 --- /dev/null +++ b/src/qt/addeditadrenalinenode.cpp @@ -0,0 +1,103 @@ +#include "addeditadrenalinenode.h" +#include "ui_addeditadrenalinenode.h" + +#include "walletdb.h" +#include "wallet.h" +#include "ui_interface.h" +#include "util.h" +#include "key.h" +#include "script.h" +#include "init.h" +#include "base58.h" +#include + +AddEditAdrenalineNode::AddEditAdrenalineNode(QWidget *parent) : + QDialog(parent), + ui(new Ui::AddEditAdrenalineNode) +{ + ui->setupUi(this); + +} + +AddEditAdrenalineNode::~AddEditAdrenalineNode() +{ + delete ui; +} + + +void AddEditAdrenalineNode::on_okButton_clicked() +{ + if(ui->aliasLineEdit->text() == "") + { + QMessageBox msg; + msg.setText("Please enter an alias."); + msg.exec(); + return; + } + else if(ui->addressLineEdit->text() == "") + { + QMessageBox msg; + msg.setText("Please enter an address."); + msg.exec(); + return; + } + else + { + CAdrenalineNodeConfig c; + c.sAlias = ui->aliasLineEdit->text().toStdString(); + c.sAddress = ui->addressLineEdit->text().toStdString(); + CKey secret; + secret.MakeNewKey(false); + c.sMasternodePrivKey = CBitcoinSecret(secret).ToString(); + + CWalletDB walletdb(pwalletMain->strWalletFile); + CAccount account; + walletdb.ReadAccount(c.sAlias, account); + bool bKeyUsed = false; + bool bForceNew = false; + + // Check if the current key has been used + if (account.vchPubKey.IsValid()) + { + CScript scriptPubKey; + scriptPubKey.SetDestination(account.vchPubKey.GetID()); + for (map::iterator it = pwalletMain->mapWallet.begin(); + it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); + ++it) + { + const CWalletTx& wtx = (*it).second; + BOOST_FOREACH(const CTxOut& txout, wtx.vout) + if (txout.scriptPubKey == scriptPubKey) + bKeyUsed = true; + } + } + + // Generate a new key + if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) + { + if (!pwalletMain->GetKeyFromPool(account.vchPubKey)) + { + QMessageBox msg; + msg.setText("Keypool ran out, please call keypoolrefill first."); + msg.exec(); + return; + } + pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), c.sAlias); + walletdb.WriteAccount(c.sAlias, account); + } + + c.sCollateralAddress = CBitcoinAddress(account.vchPubKey.GetID()).ToString(); + + pwalletMain->mapMyAdrenalineNodes.insert(make_pair(c.sAddress, c)); + walletdb.WriteAdrenalineNodeConfig(c.sAddress, c); + uiInterface.NotifyAdrenalineNodeChanged(c); + + accept(); + } +} + +void AddEditAdrenalineNode::on_cancelButton_clicked() +{ + reject(); +} + diff --git a/src/qt/addeditadrenalinenode.h b/src/qt/addeditadrenalinenode.h new file mode 100644 index 0000000..4dff3f4 --- /dev/null +++ b/src/qt/addeditadrenalinenode.h @@ -0,0 +1,31 @@ +#ifndef ADDEDITADRENALINENODE_H +#define ADDEDITADRENALINENODE_H + +#include + +namespace Ui { +class AddEditAdrenalineNode; +} + + +class AddEditAdrenalineNode : public QDialog +{ + Q_OBJECT + +public: + explicit AddEditAdrenalineNode(QWidget *parent = 0); + ~AddEditAdrenalineNode(); + +protected: + +private slots: + void on_okButton_clicked(); + void on_cancelButton_clicked(); + +signals: + +private: + Ui::AddEditAdrenalineNode *ui; +}; + +#endif // ADDEDITADRENALINENODE_H diff --git a/src/qt/addresstablemodel.cpp b/src/qt/addresstablemodel.cpp index 1416574..b70acfe 100644 --- a/src/qt/addresstablemodel.cpp +++ b/src/qt/addresstablemodel.cpp @@ -22,10 +22,11 @@ struct AddressTableEntry Type type; QString label; QString address; + bool stealth; AddressTableEntry() {} - AddressTableEntry(Type type, const QString &label, const QString &address): - type(type), label(label), address(address) {} + AddressTableEntry(Type type, const QString &label, const QString &address, const bool &stealth = false): + type(type), label(label), address(address), stealth(stealth) {} }; struct AddressTableEntryLessThan @@ -69,6 +70,16 @@ class AddressTablePriv QString::fromStdString(strName), QString::fromStdString(address.ToString()))); } + + std::set::iterator it; + for (it = wallet->stealthAddresses.begin(); it != wallet->stealthAddresses.end(); ++it) + { + bool fMine = !(it->scan_secret.size() < 1); + cachedAddressTable.append(AddressTableEntry(fMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending, + QString::fromStdString(it->label), + QString::fromStdString(it->Encoded()), + true)); + }; } // qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan()); @@ -218,7 +229,7 @@ bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, AddressTableEntry *rec = static_cast(index.internalPointer()); editStatus = OK; - + std::string strTemp, strValue; if(role == Qt::EditRole) { switch(index.column()) @@ -230,9 +241,25 @@ bool AddressTableModel::setData(const QModelIndex &index, const QVariant &value, editStatus = NO_CHANGES; return false; } - wallet->SetAddressBookName(CBitcoinAddress(rec->address.toStdString()).Get(), value.toString().toStdString()); + + strTemp = rec->address.toStdString(); + if (IsStealthAddress(strTemp)) + { + strValue = value.toString().toStdString(); + wallet->UpdateStealthAddress(strTemp, strValue, false); + } else + { + wallet->SetAddressBookName(CBitcoinAddress(strTemp).Get(), value.toString().toStdString()); + } break; case Address: + std::string sTemp = value.toString().toStdString(); + if (IsStealthAddress(sTemp)) + { + printf("TODO\n"); + editStatus = INVALID_ADDRESS; + return false; + } // Do nothing, if old address == new address if(CBitcoinAddress(rec->address.toStdString()) == CBitcoinAddress(value.toString().toStdString())) { @@ -319,7 +346,7 @@ void AddressTableModel::updateEntry(const QString &address, const QString &label priv->updateEntry(address, label, isMine, status); } -QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address) +QString AddressTableModel::addRow(const QString &type, const QString &label, const QString &address, int addressType) { std::string strLabel = label.toStdString(); std::string strAddress = address.toStdString(); @@ -328,52 +355,94 @@ QString AddressTableModel::addRow(const QString &type, const QString &label, con if(type == Send) { - if(!walletModel->validateAddress(address)) + if (strAddress.length() > 75) { - editStatus = INVALID_ADDRESS; - return QString(); - } - // Check for duplicate addresses + CStealthAddress sxAddr; + if (!sxAddr.SetEncoded(strAddress)) + { + editStatus = INVALID_ADDRESS; + return QString(); + } + + // -- Check for duplicate addresses + { + LOCK(wallet->cs_wallet); + + if (wallet->stealthAddresses.count(sxAddr)) + { + editStatus = DUPLICATE_ADDRESS; + return QString(); + }; + + sxAddr.label = strLabel; + wallet->AddStealthAddress(sxAddr); + } + + } else { - LOCK(wallet->cs_wallet); - if(wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) + if (!walletModel->validateAddress(address)) { - editStatus = DUPLICATE_ADDRESS; + editStatus = INVALID_ADDRESS; return QString(); + }; + // Check for duplicate addresses + { + LOCK(wallet->cs_wallet); + if (wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) + { + editStatus = DUPLICATE_ADDRESS; + return QString(); + }; + + wallet->SetAddressBookName(CBitcoinAddress(strAddress).Get(), strLabel); } } } else if(type == Receive) { // Generate a new address to associate with given label - CPubKey newKey; - if(!wallet->GetKeyFromPool(newKey)) + WalletModel::UnlockContext ctx(walletModel->requestUnlock()); + + if(!ctx.isValid()) { - WalletModel::UnlockContext ctx(walletModel->requestUnlock()); - if(!ctx.isValid()) + // Unlock wallet failed or was cancelled + editStatus = WALLET_UNLOCK_FAILURE; + return QString(); + } + + if (addressType == AT_Stealth) + { + CStealthAddress newStealthAddr; + std::string sError; + if (!wallet->NewStealthAddress(sError, strLabel, newStealthAddr) + || !wallet->AddStealthAddress(newStealthAddr)) { - // Unlock wallet failed or was cancelled - editStatus = WALLET_UNLOCK_FAILURE; + editStatus = KEY_GENERATION_FAILURE; return QString(); } + strAddress = newStealthAddr.Encoded(); + } else + { + CPubKey newKey; if(!wallet->GetKeyFromPool(newKey)) { editStatus = KEY_GENERATION_FAILURE; return QString(); } + strAddress = CBitcoinAddress(newKey.GetID()).ToString(); + + { + LOCK(wallet->cs_wallet); + wallet->SetAddressBookName(CBitcoinAddress(strAddress).Get(), strLabel); + } } - strAddress = CBitcoinAddress(newKey.GetID()).ToString(); } else { return QString(); } - // Add entry - { - LOCK(wallet->cs_wallet); - wallet->SetAddressBookName(CBitcoinAddress(strAddress).Get(), strLabel); - } + return QString::fromStdString(strAddress); } @@ -400,11 +469,28 @@ QString AddressTableModel::labelForAddress(const QString &address) const { { LOCK(wallet->cs_wallet); - CBitcoinAddress address_parsed(address.toStdString()); - std::map::iterator mi = wallet->mapAddressBook.find(address_parsed.Get()); - if (mi != wallet->mapAddressBook.end()) + std::string sAddr = address.toStdString(); + + if (sAddr.length() > 75) { - return QString::fromStdString(mi->second); + CStealthAddress sxAddr; + if (!sxAddr.SetEncoded(sAddr)) + return QString(); + + std::set::iterator it; + it = wallet->stealthAddresses.find(sxAddr); + if (it == wallet->stealthAddresses.end()) + return QString(); + + return QString::fromStdString(it->label); + } else + { + CBitcoinAddress address_parsed(sAddr); + std::map::iterator mi = wallet->mapAddressBook.find(address_parsed.Get()); + if (mi != wallet->mapAddressBook.end()) + { + return QString::fromStdString(mi->second); + } } } return QString(); diff --git a/src/qt/addresstablemodel.h b/src/qt/addresstablemodel.h index 48baff5..97537a2 100644 --- a/src/qt/addresstablemodel.h +++ b/src/qt/addresstablemodel.h @@ -19,9 +19,16 @@ class AddressTableModel : public QAbstractTableModel explicit AddressTableModel(CWallet *wallet, WalletModel *parent = 0); ~AddressTableModel(); + enum AddressType { + AT_Unknown = 0, /**< User specified label */ + AT_Normal = 1, /**< Bitcoin address */ + AT_Stealth = 2 /**< Stealth address */ + }; + enum ColumnIndex { Label = 0, /**< User specified label */ - Address = 1 /**< Bitcoin address */ + Address = 1, /**< Bitcoin address */ + Type = 2 /**< Address type */ }; enum RoleIndex { @@ -56,7 +63,7 @@ class AddressTableModel : public QAbstractTableModel /* Add an address to the model. Returns the added address on success, and an empty string otherwise. */ - QString addRow(const QString &type, const QString &label, const QString &address); + QString addRow(const QString &type, const QString &label, const QString &address, int addressType); /* Look up label for address in address book, if not found return empty string. */ diff --git a/src/qt/adrenalinenodeconfigdialog.cpp b/src/qt/adrenalinenodeconfigdialog.cpp new file mode 100644 index 0000000..ee0744e --- /dev/null +++ b/src/qt/adrenalinenodeconfigdialog.cpp @@ -0,0 +1,18 @@ +#include "adrenalinenodeconfigdialog.h" +#include "ui_adrenalinenodeconfigdialog.h" + +#include + +AdrenalineNodeConfigDialog::AdrenalineNodeConfigDialog(QWidget *parent, QString nodeAddress, QString privkey) : + QDialog(parent), + ui(new Ui::AdrenalineNodeConfigDialog) +{ + ui->setupUi(this); + QString desc = "rpcallowip=127.0.0.1
rpcuser=REPLACEME
rpcpassword=REPLACEME
staking=0
server=1
listen=1
port=REPLACEMEWITHYOURPORT
masternode=1
masternodeaddr=" + nodeAddress + "
masternodeprivkey=" + privkey + "
"; + ui->detailText->setHtml(desc); +} + +AdrenalineNodeConfigDialog::~AdrenalineNodeConfigDialog() +{ + delete ui; +} diff --git a/src/qt/adrenalinenodeconfigdialog.h b/src/qt/adrenalinenodeconfigdialog.h new file mode 100644 index 0000000..39b091f --- /dev/null +++ b/src/qt/adrenalinenodeconfigdialog.h @@ -0,0 +1,27 @@ +#ifndef ADRENALINENODECONFIGDIALOG_H +#define ADRENALINENODECONFIGDIALOG_H + +#include + +namespace Ui { + class AdrenalineNodeConfigDialog; +} + +QT_BEGIN_NAMESPACE +class QModelIndex; +QT_END_NAMESPACE + +/** Dialog showing transaction details. */ +class AdrenalineNodeConfigDialog : public QDialog +{ + Q_OBJECT + +public: + explicit AdrenalineNodeConfigDialog(QWidget *parent = 0, QString nodeAddress = "123.456.789.123:9999", QString privkey="MASTERNODEPRIVKEY"); + ~AdrenalineNodeConfigDialog(); + +private: + Ui::AdrenalineNodeConfigDialog *ui; +}; + +#endif // ADRENALINENODECONFIGDIALOG_H diff --git a/src/qt/bitcoin.cpp b/src/qt/bitcoin.cpp index bedd349..31e4f0d 100644 --- a/src/qt/bitcoin.cpp +++ b/src/qt/bitcoin.cpp @@ -8,6 +8,7 @@ #include "clientmodel.h" #include "walletmodel.h" #include "optionsmodel.h" +#include "messagemodel.h" #include "guiutil.h" #include "guiconstants.h" #include "init.h" @@ -270,9 +271,11 @@ int main(int argc, char *argv[]) ClientModel clientModel(&optionsModel); WalletModel walletModel(pwalletMain, &optionsModel); + MessageModel messageModel(pwalletMain, &walletModel); window.setClientModel(&clientModel); window.setWalletModel(&walletModel); + window.setMessageModel(&messageModel); // If -min option passed, start window minimized. if(GetBoolArg("-min", false)) @@ -294,6 +297,7 @@ int main(int argc, char *argv[]) window.hide(); window.setClientModel(0); window.setWalletModel(0); + window.setMessageModel(0); guiref = 0; } // Shutdown the core and its threads, but don't exit Bitcoin-Qt here diff --git a/src/qt/bitcoin.qrc b/src/qt/bitcoin.qrc index 844ecd7..cf58581 100644 --- a/src/qt/bitcoin.qrc +++ b/src/qt/bitcoin.qrc @@ -1,4 +1,4 @@ - + res/icons/novacoin-80.png res/icons/address-book.png @@ -43,6 +43,8 @@ res/icons/debugwindow.png res/icons/staking_off.png res/icons/staking_on.png + res/icons/onion.png + res/icons/onion-black.png res/icons/black/connect0_16.png diff --git a/src/qt/bitcoinaddressvalidator.h b/src/qt/bitcoinaddressvalidator.h index 2b6a593..7c32231 100644 --- a/src/qt/bitcoinaddressvalidator.h +++ b/src/qt/bitcoinaddressvalidator.h @@ -15,7 +15,7 @@ class BitcoinAddressValidator : public QValidator State validate(QString &input, int &pos) const; - static const int MaxAddressLength = 35; + static const int MaxAddressLength = 128; }; #endif // BITCOINADDRESSVALIDATOR_H diff --git a/src/qt/bitcoingui.cpp b/src/qt/bitcoingui.cpp index ddafa6c..77d291a 100644 --- a/src/qt/bitcoingui.cpp +++ b/src/qt/bitcoingui.cpp @@ -32,6 +32,9 @@ #include "wallet.h" #include "init.h" #include "ui_interface.h" +#include "masternodemanager.h" +#include "messagemodel.h" +#include "messagepage.h" #ifdef Q_OS_MAC #include "macdockiconhandler.h" @@ -57,9 +60,14 @@ #include #include #include +#include +#include +#include +#include #include +extern bool fOnlyTor; extern CWallet* pwalletMain; extern int64_t nLastCoinStakeSearchInterval; double GetPoSKernelPS(); @@ -80,7 +88,7 @@ BitcoinGUI::BitcoinGUI(QWidget *parent): prevBlocks(0), nWeight(0) { - resize(450, 400); + resize(600, 450); setWindowTitle(tr("Genius") + " - " + tr("Wallet")); #ifndef Q_OS_MAC qApp->setWindowIcon(QIcon(":icons/bitcoin")); @@ -89,6 +97,8 @@ BitcoinGUI::BitcoinGUI(QWidget *parent): //setUnifiedTitleAndToolBarOnMac(true); QApplication::setAttribute(Qt::AA_DontShowIconsInMenus); #endif + setObjectName("genius"); + setStyleSheet("#genius { background-color: qradialgradient(cx: -0.8, cy: 0, fx: -0.8, fy: 0, radius: 1.4, stop: 0 #efefef, stop: 1 #dedeff); }"); // Accept D&D of URIs setAcceptDrops(true); @@ -106,33 +116,38 @@ BitcoinGUI::BitcoinGUI(QWidget *parent): // Create tabs overviewPage = new OverviewPage(); + + transactionsPage = new QWidget(this); + QVBoxLayout *vbox = new QVBoxLayout(); + transactionView = new TransactionView(this); + vbox->addWidget(transactionView); + transactionsPage->setLayout(vbox); - //transactionsPage = new QWidget(this); - //QVBoxLayout *vbox = new QVBoxLayout(); - //transactionView = new TransactionView(this); - //vbox->addWidget(transactionView); - //transactionsPage->setLayout(vbox); - - //addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab); + addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab); - //receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab); + receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab); - //sendCoinsPage = new SendCoinsDialog(this); + sendCoinsPage = new SendCoinsDialog(this); signVerifyMessageDialog = new SignVerifyMessageDialog(this); + masternodeManagerPage = new MasternodeManager(this); + messagePage = new MessagePage(this); + centralStackedWidget = new QStackedWidget(this); + centralStackedWidget->setContentsMargins(0, 0, 0, 0); centralStackedWidget->addWidget(overviewPage); - //centralStackedWidget->addWidget(transactionsPage); - //centralStackedWidget->addWidget(addressBookPage); - //centralStackedWidget->addWidget(receiveCoinsPage); - //centralStackedWidget->addWidget(sendCoinsPage); + centralStackedWidget->addWidget(transactionsPage); + centralStackedWidget->addWidget(addressBookPage); + centralStackedWidget->addWidget(receiveCoinsPage); + centralStackedWidget->addWidget(sendCoinsPage); + centralStackedWidget->addWidget(masternodeManagerPage); + centralStackedWidget->addWidget(messagePage); QWidget *centralWidget = new QWidget(); QVBoxLayout *centralLayout = new QVBoxLayout(centralWidget); -#ifndef Q_OS_MAC - centralLayout->addWidget(appMenuBar); -#endif + centralLayout->setContentsMargins(0,0,0,0); + centralWidget->setContentsMargins(0,0,0,0); centralLayout->addWidget(centralStackedWidget); setCentralWidget(centralWidget); @@ -140,6 +155,9 @@ BitcoinGUI::BitcoinGUI(QWidget *parent): // Create status bar statusBar(); + // Disable size grip because it looks ugly and nobody needs it + statusBar()->setSizeGripEnabled(false); + // Status bar notification icons QWidget *frameBlocks = new QWidget(); frameBlocks->setContentsMargins(0,0,0,0); @@ -162,13 +180,15 @@ BitcoinGUI::BitcoinGUI(QWidget *parent): frameBlocksLayout->addStretch(); frameBlocksLayout->addWidget(labelBlocksIcon); frameBlocksLayout->addStretch(); - toolbar->addWidget(frameBlocks); + + frameBlocksLayout->addStretch(); + if (GetBoolArg("-staking", true)) { QTimer *timerStakingIcon = new QTimer(labelStakingIcon); connect(timerStakingIcon, SIGNAL(timeout()), this, SLOT(updateStakingIcon())); - timerStakingIcon->start(30 * 1000); + timerStakingIcon->start(20 * 1000); updateStakingIcon(); } @@ -193,15 +213,18 @@ BitcoinGUI::BitcoinGUI(QWidget *parent): statusBar()->addWidget(progressBarLabel); statusBar()->addWidget(progressBar); + statusBar()->addPermanentWidget(frameBlocks); + statusBar()->setObjectName("statusBar"); + statusBar()->setStyleSheet("#statusBar { color: #ffffff; background-color: qradialgradient(cx: -0.8, cy: 0, fx: -0.8, fy: 0, radius: 0.6, stop: 0 #101010, stop: 1 #404040); }"); syncIconMovie = new QMovie(fUseBlackTheme ? ":/movies/update_spinner_black" : ":/movies/update_spinner", "mng", this); // Clicking on a transaction on the overview page simply sends you to transaction history page connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage())); - //connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex))); + connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex))); // Double-clicking on a transaction on the transaction history page shows details - //connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails())); + connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails())); rpcConsole = new RPCConsole(this); connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show())); @@ -209,9 +232,9 @@ BitcoinGUI::BitcoinGUI(QWidget *parent): connect(quitAction, SIGNAL(triggered()), rpcConsole, SLOT(hide())); // Clicking on "Verify Message" in the address book sends you to the verify message tab - //connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString))); + connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString))); // Clicking on "Sign Message" in the receive coins page sends you to the sign message tab - //connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString))); + connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString))); gotoOverviewPage(); } @@ -235,8 +258,8 @@ void BitcoinGUI::createActions() overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1)); tabGroup->addAction(overviewAction); - receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive"), this); - receiveCoinsAction->setToolTip(tr("Show the list of addresses for receiving payments")); + receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Recieve"), this); + receiveCoinsAction->setToolTip(tr("Show the list of addresses for recieving coins")); receiveCoinsAction->setCheckable(true); receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2)); tabGroup->addAction(receiveCoinsAction); @@ -253,12 +276,22 @@ void BitcoinGUI::createActions() historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4)); tabGroup->addAction(historyAction); - addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Address Book"), this); + addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Addresses"), this); addressBookAction->setToolTip(tr("Edit the list of stored addresses and labels")); addressBookAction->setCheckable(true); addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5)); tabGroup->addAction(addressBookAction); + masternodeManagerAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Masternode"), this); + masternodeManagerAction->setToolTip(tr("Show Masternode status and configure your nodes.")); + masternodeManagerAction->setCheckable(true); + tabGroup->addAction(masternodeManagerAction); + + messageAction = new QAction(QIcon(":/icons/edit"), tr("&Messages"), this); + messageAction->setToolTip(tr("View and Send Encrypted messages")); + messageAction->setCheckable(true); + tabGroup->addAction(messageAction); + connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage())); connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); @@ -269,6 +302,10 @@ void BitcoinGUI::createActions() connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage())); connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage())); + connect(masternodeManagerAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); + connect(masternodeManagerAction, SIGNAL(triggered()), this, SLOT(gotoMasternodeManagerPage())); + connect(messageAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized())); + connect(messageAction, SIGNAL(triggered()), this, SLOT(gotoMessagePage())); quitAction = new QAction(tr("E&xit"), this); quitAction->setToolTip(tr("Quit application")); @@ -318,7 +355,11 @@ void BitcoinGUI::createActions() void BitcoinGUI::createMenuBar() { +#ifdef Q_OS_MAC appMenuBar = new QMenuBar(); +#else + appMenuBar = menuBar(); +#endif // Configure the menus QMenu *file = appMenuBar->addMenu(tr("&File")); @@ -347,8 +388,8 @@ void BitcoinGUI::createMenuBar() static QWidget* makeToolBarSpacer() { QWidget* spacer = new QWidget(); - spacer->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding); - spacer->setStyleSheet(fUseBlackTheme ? "QWidget { background: rgb(30,32,36); }" : "QWidget { background: none; }"); + spacer->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + spacer->setStyleSheet("QWidget { background: none; }"); return spacer; } @@ -357,39 +398,32 @@ void BitcoinGUI::createToolBars() toolbar = new QToolBar(tr("Tabs toolbar")); toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon); toolbar->setContextMenuPolicy(Qt::PreventContextMenu); - - if (fUseBlackTheme) - { - QWidget* header = new QWidget(); - header->setMinimumSize(160, 116); - header->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - header->setStyleSheet("QWidget { background-color: rgb(24,26,30); background-repeat: no-repeat; background-image: url(:/images/header); background-position: top center; }"); - toolbar->addWidget(header); - toolbar->addWidget(makeToolBarSpacer()); - } - + toolbar->setObjectName("tabs"); + toolbar->setStyleSheet("QToolButton { color: #ffffff; } QToolButton:hover { background-color: #FFD800 } QToolButton:checked { background-color: #C4A000 } QToolButton:pressed { background-color: #C4A000 } #tabs { color: #ffffff; background-color: qradialgradient(cx: -0.8, cy: 0, fx: -0.8, fy: 0, radius: 0.6, stop: 0 #404040, stop: 1 #101010); }"); + + QLabel* header = new QLabel(); + header->setMinimumSize(128, 128); + header->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + header->setPixmap(QPixmap(":/icons/bitcoin")); + header->setMaximumSize(180,180); + header->setScaledContents(true); + toolbar->addWidget(header); + + //QMenu *toolbarMenu = new QMenu(); toolbar->addAction(overviewAction); toolbar->addAction(receiveCoinsAction); toolbar->addAction(sendCoinsAction); toolbar->addAction(historyAction); toolbar->addAction(addressBookAction); + toolbar->addAction(masternodeManagerAction); + toolbar->addAction(messageAction); - toolbar->addWidget(makeToolBarSpacer()); - + QWidget *spacer = makeToolBarSpacer(); + toolbar->addWidget(spacer); toolbar->setOrientation(Qt::Vertical); toolbar->setMovable(false); addToolBar(Qt::LeftToolBarArea, toolbar); - - int w = 0; - - foreach(QAction *action, toolbar->actions()) { - w = std::max(w, toolbar->widgetForAction(action)->width()); - } - - foreach(QAction *action, toolbar->actions()) { - toolbar->widgetForAction(action)->setFixedWidth(w); - } } void BitcoinGUI::setClientModel(ClientModel *clientModel) @@ -427,8 +461,8 @@ void BitcoinGUI::setClientModel(ClientModel *clientModel) overviewPage->setClientModel(clientModel); rpcConsole->setClientModel(clientModel); - //addressBookPage->setOptionsModel(clientModel->getOptionsModel()); - //receiveCoinsPage->setOptionsModel(clientModel->getOptionsModel()); + addressBookPage->setOptionsModel(clientModel->getOptionsModel()); + receiveCoinsPage->setOptionsModel(clientModel->getOptionsModel()); } } @@ -441,11 +475,11 @@ void BitcoinGUI::setWalletModel(WalletModel *walletModel) connect(walletModel, SIGNAL(message(QString,QString,bool,unsigned int)), this, SLOT(message(QString,QString,bool,unsigned int))); // Put transaction list in tabs - //transactionView->setModel(walletModel); + transactionView->setModel(walletModel); overviewPage->setWalletModel(walletModel); - //addressBookPage->setModel(walletModel->getAddressTableModel()); - //receiveCoinsPage->setModel(walletModel->getAddressTableModel()); - //sendCoinsPage->setModel(walletModel); + addressBookPage->setModel(walletModel->getAddressTableModel()); + receiveCoinsPage->setModel(walletModel->getAddressTableModel()); + sendCoinsPage->setModel(walletModel); signVerifyMessageDialog->setModel(walletModel); setEncryptionStatus(walletModel->getEncryptionStatus()); @@ -460,6 +494,23 @@ void BitcoinGUI::setWalletModel(WalletModel *walletModel) } } +void BitcoinGUI::setMessageModel(MessageModel *messageModel) +{ + this->messageModel = messageModel; + if(messageModel) + { + // Report errors from message thread + connect(messageModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool))); + + // Put transaction list in tabs + messagePage->setModel(messageModel); + + // Balloon pop-up for new message + connect(messageModel, SIGNAL(rowsInserted(QModelIndex,int,int)), + this, SLOT(incomingMessage(QModelIndex,int,int))); + } +} + void BitcoinGUI::createTrayIcon() { QMenu *trayIconMenu; @@ -542,15 +593,6 @@ void BitcoinGUI::setNumConnections(int count) void BitcoinGUI::setNumBlocks(int count) { - // don't show / hide progress bar and its label if we have no connection to the network - if (!clientModel || (clientModel->getNumConnections() == 0 && !clientModel->isImporting())) - { - statusBar()->setVisible(false); - - return; - } - - bool fShowStatusBar = false; QString tooltip; QDateTime lastBlockDate = clientModel->getLastBlockDate(); @@ -604,8 +646,7 @@ void BitcoinGUI::setNumBlocks(int count) progressBar->setMaximum(totalSecs); progressBar->setValue(totalSecs - secs); progressBar->setVisible(true); - fShowStatusBar = true; - + tooltip = tr("Catching up...") + QString("
") + tooltip; labelBlocksIcon->setMovie(syncIconMovie); if(count != prevBlocks) @@ -627,7 +668,7 @@ void BitcoinGUI::setNumBlocks(int count) progressBarLabel->setToolTip(tooltip); progressBar->setToolTip(tooltip); - statusBar()->setVisible(fShowStatusBar); + statusBar()->setVisible(true); } void BitcoinGUI::message(const QString &title, const QString &message, bool modal, unsigned int style) @@ -759,6 +800,35 @@ void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int } } +void BitcoinGUI::incomingMessage(const QModelIndex & parent, int start, int end) +{ + if(!messageModel) + return; + + MessageModel *mm = messageModel; + + if (mm->index(start, MessageModel::TypeInt, parent).data().toInt() == MessageTableEntry::Received) + { + QString sent_datetime = mm->index(start, MessageModel::ReceivedDateTime, parent).data().toString(); + QString from_address = mm->index(start, MessageModel::FromAddress, parent).data().toString(); + QString to_address = mm->index(start, MessageModel::ToAddress, parent).data().toString(); + QString message = mm->index(start, MessageModel::Message, parent).data().toString(); + QTextDocument html; + html.setHtml(message); + QString messageText(html.toPlainText()); + notificator->notify(Notificator::Information, + tr("Incoming Message"), + tr("Date: %1\n" + "From Address: %2\n" + "To Address: %3\n" + "Message: %4\n") + .arg(sent_datetime) + .arg(from_address) + .arg(to_address) + .arg(messageText)); + }; +} + void BitcoinGUI::clearWidgets() { centralStackedWidget->setCurrentWidget(centralStackedWidget->widget(0)); @@ -769,11 +839,18 @@ void BitcoinGUI::clearWidgets() } } +void BitcoinGUI::gotoMasternodeManagerPage() +{ + masternodeManagerAction->setChecked(true); + centralStackedWidget->setCurrentWidget(masternodeManagerPage); + + exportAction->setEnabled(false); + disconnect(exportAction, SIGNAL(triggered()), 0, 0); +} + void BitcoinGUI::gotoOverviewPage() { overviewAction->setChecked(true); - - clearWidgets(); centralStackedWidget->setCurrentWidget(overviewPage); exportAction->setEnabled(false); @@ -783,20 +860,8 @@ void BitcoinGUI::gotoOverviewPage() void BitcoinGUI::gotoHistoryPage() { historyAction->setChecked(true); - clearWidgets(); - - transactionsPage = new QWidget(this); - QVBoxLayout *vbox = new QVBoxLayout(); - transactionView = new TransactionView(this); - vbox->addWidget(transactionView); - transactionsPage->setLayout(vbox); - centralStackedWidget->addWidget(transactionsPage); centralStackedWidget->setCurrentWidget(transactionsPage); - connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails())); - - transactionView->setModel(this->walletModel); - exportAction->setEnabled(true); disconnect(exportAction, SIGNAL(triggered()), 0, 0); connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked())); @@ -805,13 +870,6 @@ void BitcoinGUI::gotoHistoryPage() void BitcoinGUI::gotoAddressBookPage() { addressBookAction->setChecked(true); - clearWidgets(); - addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab); - addressBookPage->setOptionsModel(this->clientModel->getOptionsModel()); - addressBookPage->setModel(this->walletModel->getAddressTableModel()); - // Clicking on "Verify Message" in the address book sends you to the verify message tab - connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString))); - centralStackedWidget->addWidget(addressBookPage); centralStackedWidget->setCurrentWidget(addressBookPage); exportAction->setEnabled(true); @@ -822,13 +880,6 @@ void BitcoinGUI::gotoAddressBookPage() void BitcoinGUI::gotoReceiveCoinsPage() { receiveCoinsAction->setChecked(true); - clearWidgets(); - receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab); - receiveCoinsPage->setOptionsModel(this->clientModel->getOptionsModel()); - receiveCoinsPage->setModel(this->walletModel->getAddressTableModel()); - // Clicking on "Sign Message" in the receive coins page sends you to the sign message tab - connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString))); - centralStackedWidget->addWidget(receiveCoinsPage); centralStackedWidget->setCurrentWidget(receiveCoinsPage); exportAction->setEnabled(true); @@ -839,10 +890,7 @@ void BitcoinGUI::gotoReceiveCoinsPage() void BitcoinGUI::gotoSendCoinsPage() { sendCoinsAction->setChecked(true); - sendCoinsPage = new SendCoinsDialog(this); - centralStackedWidget->addWidget(sendCoinsPage); centralStackedWidget->setCurrentWidget(sendCoinsPage); - sendCoinsPage->setModel(this->walletModel); exportAction->setEnabled(false); disconnect(exportAction, SIGNAL(triggered()), 0, 0); @@ -866,6 +914,16 @@ void BitcoinGUI::gotoVerifyMessageTab(QString addr) signVerifyMessageDialog->setAddress_VM(addr); } +void BitcoinGUI::gotoMessagePage() +{ + messageAction->setChecked(true); + centralStackedWidget->setCurrentWidget(messagePage); + + exportAction->setEnabled(true); + disconnect(exportAction, SIGNAL(triggered()), 0, 0); + connect(exportAction, SIGNAL(triggered()), messagePage, SLOT(exportClicked())); +} + void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event) { // Accept only URIs @@ -909,6 +967,19 @@ void BitcoinGUI::handleURI(QString strURI) void BitcoinGUI::setEncryptionStatus(int status) { + if(fWalletUnlockStakingOnly) + { + labelEncryptionIcon->setPixmap(QIcon(fUseBlackTheme ? ":/icons/black/lock_open" : ":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE)); + labelEncryptionIcon->setToolTip(tr("Wallet is encrypted and currently unlocked for staking only")); + changePassphraseAction->setEnabled(false); + unlockWalletAction->setVisible(true); + lockWalletAction->setVisible(true); + encryptWalletAction->setEnabled(false); + + } + else + { + switch(status) { case WalletModel::Unencrypted: @@ -936,6 +1007,8 @@ void BitcoinGUI::setEncryptionStatus(int status) encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported break; } + + } } void BitcoinGUI::encryptWallet() diff --git a/src/qt/bitcoingui.h b/src/qt/bitcoingui.h index 3228403..f6600d5 100644 --- a/src/qt/bitcoingui.h +++ b/src/qt/bitcoingui.h @@ -16,12 +16,16 @@ class SendCoinsDialog; class SignVerifyMessageDialog; class Notificator; class RPCConsole; +class MasternodeManager; +class MessagePage; +class MessageModel; QT_BEGIN_NAMESPACE class QLabel; class QModelIndex; class QProgressBar; class QStackedWidget; +class QScrollArea; QT_END_NAMESPACE /** @@ -45,6 +49,7 @@ class BitcoinGUI : public QMainWindow functionality. */ void setWalletModel(WalletModel *walletModel); + void setMessageModel(MessageModel *messageModel); protected: void changeEvent(QEvent *e); @@ -55,17 +60,22 @@ class BitcoinGUI : public QMainWindow private: ClientModel *clientModel; WalletModel *walletModel; + MessageModel *messageModel; QToolBar *toolbar; QStackedWidget *centralStackedWidget; + QWidget *overviewWidget; + QScrollArea *overviewScroll; OverviewPage *overviewPage; QWidget *transactionsPage; AddressBookPage *addressBookPage; AddressBookPage *receiveCoinsPage; SendCoinsDialog *sendCoinsPage; SignVerifyMessageDialog *signVerifyMessageDialog; + MasternodeManager *masternodeManagerPage; + MessagePage *messagePage; QLabel *labelEncryptionIcon; QLabel *labelStakingIcon; @@ -94,6 +104,8 @@ class BitcoinGUI : public QMainWindow QAction *lockWalletAction; QAction *aboutQtAction; QAction *openRPCConsoleAction; + QAction *masternodeManagerAction; + QAction *messageAction; QSystemTrayIcon *trayIcon; Notificator *notificator; @@ -159,11 +171,15 @@ private slots: /** Switch to send coins page */ void gotoSendCoinsPage(); + void gotoMasternodeManagerPage(); + /** Show Sign/Verify Message dialog and switch to sign message tab */ void gotoSignMessageTab(QString addr = ""); /** Show Sign/Verify Message dialog and switch to verify message tab */ void gotoVerifyMessageTab(QString addr = ""); + void gotoMessagePage(); + /** Show configuration dialog */ void optionsClicked(); /** Show about dialog */ @@ -177,6 +193,7 @@ private slots: The new items are those between start and end inclusive, under the given parent item. */ void incomingTransaction(const QModelIndex & parent, int start, int end); + void incomingMessage(const QModelIndex & parent, int start, int end); /** Encrypt the wallet */ void encryptWallet(); /** Backup the wallet */ diff --git a/src/qt/bitcoinunits.cpp b/src/qt/bitcoinunits.cpp index da61168..22af060 100644 --- a/src/qt/bitcoinunits.cpp +++ b/src/qt/bitcoinunits.cpp @@ -45,9 +45,9 @@ QString BitcoinUnits::description(int unit) { switch(unit) { - case BTC: return QString("Geniuss"); - case mBTC: return QString("Milli-Geniuss (1 / 1,000)"); - case uBTC: return QString("Micro-Geniuss (1 / 1,000,000)"); + case BTC: return QString("Genius"); + case mBTC: return QString("Milli-Genius (1 / 1,000)"); + case uBTC: return QString("Micro-Genius (1 / 1,000,000)"); default: return QString("???"); } } diff --git a/src/qt/darksendconfig.cpp b/src/qt/darksendconfig.cpp new file mode 100644 index 0000000..e5be555 --- /dev/null +++ b/src/qt/darksendconfig.cpp @@ -0,0 +1,91 @@ +#include "darksendconfig.h" +#include "ui_darksendconfig.h" + +#include "bitcoinunits.h" +#include "guiconstants.h" +#include "optionsmodel.h" +#include "walletmodel.h" +#include "init.h" + +#include +#include +#include +#include + +DarksendConfig::DarksendConfig(QWidget *parent) : + QDialog(parent), + ui(new Ui::DarksendConfig), + model(0) +{ + ui->setupUi(this); + + connect(ui->buttonBasic, SIGNAL(clicked()), this, SLOT(clickBasic())); + connect(ui->buttonHigh, SIGNAL(clicked()), this, SLOT(clickHigh())); + connect(ui->buttonMax, SIGNAL(clicked()), this, SLOT(clickMax())); +} + +DarksendConfig::~DarksendConfig() +{ + delete ui; +} + +void DarksendConfig::setModel(WalletModel *model) +{ + this->model = model; +} + +void DarksendConfig::clickBasic() +{ + configure(true, 1000, 2); + + QString strAmount(BitcoinUnits::formatWithUnit( + model->getOptionsModel()->getDisplayUnit(), 1000 * COIN)); + QMessageBox::information(this, tr("Darksend Configuration"), + tr( + "Darksend was successfully set to basic (%1 and 2 rounds). You can change this at any time by opening Genius's configuration screen." + ).arg(strAmount) + ); + + close(); +} + +void DarksendConfig::clickHigh() +{ + configure(true, 1000, 8); + + QString strAmount(BitcoinUnits::formatWithUnit( + model->getOptionsModel()->getDisplayUnit(), 1000 * COIN)); + QMessageBox::information(this, tr("Darksend Configuration"), + tr( + "Darksend was successfully set to high (%1 and 8 rounds). You can change this at any time by opening Genius's configuration screen." + ).arg(strAmount) + ); + + close(); +} + +void DarksendConfig::clickMax() +{ + configure(true, 1000, 16); + + QString strAmount(BitcoinUnits::formatWithUnit( + model->getOptionsModel()->getDisplayUnit(), 1000 * COIN)); + QMessageBox::information(this, tr("Darksend Configuration"), + tr( + "Darksend was successfully set to maximum (%1 and 16 rounds). You can change this at any time by opening Bitcoin's configuration screen." + ).arg(strAmount) + ); + + close(); +} + +void DarksendConfig::configure(bool enabled, int coins, int rounds) { + + QSettings settings; + + settings.setValue("nDarksendRounds", rounds); + settings.setValue("nAnonymizeGeniusAmount", coins); + + nDarksendRounds = rounds; + nAnonymizeGeniusAmount = coins; +} diff --git a/src/qt/darksendconfig.h b/src/qt/darksendconfig.h new file mode 100644 index 0000000..788602f --- /dev/null +++ b/src/qt/darksendconfig.h @@ -0,0 +1,37 @@ +#ifndef DARKSENDCONFIG_H +#define DARKSENDCONFIG_H + +#include + +namespace Ui { + class DarksendConfig; +} +class WalletModel; + +/** Multifunctional dialog to ask for passphrases. Used for encryption, unlocking, and changing the passphrase. + */ +class DarksendConfig : public QDialog +{ + Q_OBJECT + +public: + + DarksendConfig(QWidget *parent = 0); + ~DarksendConfig(); + + void setModel(WalletModel *model); + + +private: + Ui::DarksendConfig *ui; + WalletModel *model; + void configure(bool enabled, int coins, int rounds); + +private slots: + + void clickBasic(); + void clickHigh(); + void clickMax(); +}; + +#endif // DARKSENDCONFIG_H diff --git a/src/qt/editaddressdialog.cpp b/src/qt/editaddressdialog.cpp index 27d9d4b..85be609 100644 --- a/src/qt/editaddressdialog.cpp +++ b/src/qt/editaddressdialog.cpp @@ -20,16 +20,24 @@ EditAddressDialog::EditAddressDialog(Mode mode, QWidget *parent) : case NewReceivingAddress: setWindowTitle(tr("New receiving address")); ui->addressEdit->setEnabled(false); + ui->addressEdit->setVisible(false); + ui->stealthCB->setEnabled(true); + ui->stealthCB->setVisible(true); break; case NewSendingAddress: setWindowTitle(tr("New sending address")); + ui->stealthCB->setVisible(false); break; case EditReceivingAddress: setWindowTitle(tr("Edit receiving address")); ui->addressEdit->setEnabled(false); + ui->addressEdit->setVisible(true); + ui->stealthCB->setEnabled(false); + ui->stealthCB->setVisible(true); break; case EditSendingAddress: setWindowTitle(tr("Edit sending address")); + ui->stealthCB->setVisible(false); break; } @@ -51,6 +59,7 @@ void EditAddressDialog::setModel(AddressTableModel *model) mapper->setModel(model); mapper->addMapping(ui->labelEdit, AddressTableModel::Label); mapper->addMapping(ui->addressEdit, AddressTableModel::Address); + mapper->addMapping(ui->stealthCB, AddressTableModel::Type); } void EditAddressDialog::loadRow(int row) @@ -67,10 +76,14 @@ bool EditAddressDialog::saveCurrentRow() { case NewReceivingAddress: case NewSendingAddress: + { + int typeInd = ui->stealthCB->isChecked() ? AddressTableModel::AT_Stealth : AddressTableModel::AT_Normal; address = model->addRow( mode == NewSendingAddress ? AddressTableModel::Send : AddressTableModel::Receive, ui->labelEdit->text(), - ui->addressEdit->text()); + ui->addressEdit->text(), + typeInd); + } break; case EditReceivingAddress: case EditSendingAddress: diff --git a/src/qt/flowlayout.cpp b/src/qt/flowlayout.cpp new file mode 100644 index 0000000..5c8ac04 --- /dev/null +++ b/src/qt/flowlayout.cpp @@ -0,0 +1,215 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * 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. +** * Neither the name of Digia Plc and its Subsidiary(-ies) 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 +** OWNER 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#include +#include +#include + +#include "flowlayout.h" +//! [1] +FlowLayout::FlowLayout(QWidget *parent, int margin, int hSpacing, int vSpacing) + : QLayout(parent), m_hSpace(hSpacing), m_vSpace(vSpacing) +{ + setContentsMargins(margin, margin, margin, margin); +} + +FlowLayout::FlowLayout(int margin, int hSpacing, int vSpacing) + : m_hSpace(hSpacing), m_vSpace(vSpacing) +{ + setContentsMargins(margin, margin, margin, margin); +} +//! [1] + +//! [2] +FlowLayout::~FlowLayout() +{ + QLayoutItem *item; + while ((item = takeAt(0))) + delete item; +} +//! [2] + +//! [3] +void FlowLayout::addItem(QLayoutItem *item) +{ + itemList.append(item); +} +//! [3] + +//! [4] +int FlowLayout::horizontalSpacing() const +{ + if (m_hSpace >= 0) { + return m_hSpace; + } else { + return smartSpacing(QStyle::PM_LayoutHorizontalSpacing); + } +} + +int FlowLayout::verticalSpacing() const +{ + if (m_vSpace >= 0) { + return m_vSpace; + } else { + return smartSpacing(QStyle::PM_LayoutVerticalSpacing); + } +} +//! [4] + +//! [5] +int FlowLayout::count() const +{ + return itemList.size(); +} + +QLayoutItem *FlowLayout::itemAt(int index) const +{ + return itemList.value(index); +} + +QLayoutItem *FlowLayout::takeAt(int index) +{ + if (index >= 0 && index < itemList.size()) + return itemList.takeAt(index); + else + return 0; +} +//! [5] + +//! [6] +Qt::Orientations FlowLayout::expandingDirections() const +{ + return 0; +} +//! [6] + +//! [7] +bool FlowLayout::hasHeightForWidth() const +{ + return true; +} + +int FlowLayout::heightForWidth(int width) const +{ + int height = doLayout(QRect(0, 0, width, 0), true); + return height; +} +//! [7] + +//! [8] +void FlowLayout::setGeometry(const QRect &rect) +{ + QLayout::setGeometry(rect); + doLayout(rect, false); +} + +QSize FlowLayout::sizeHint() const +{ + return minimumSize(); +} + +QSize FlowLayout::minimumSize() const +{ + QSize size; + QLayoutItem *item; + foreach (item, itemList) + size = size.expandedTo(item->minimumSize()); + + size += QSize(2*margin(), 2*margin()); + return size; +} +//! [8] + +//! [9] +int FlowLayout::doLayout(const QRect &rect, bool testOnly) const +{ + int left, top, right, bottom; + getContentsMargins(&left, &top, &right, &bottom); + QRect effectiveRect = rect.adjusted(+left, +top, -right, -bottom); + int x = effectiveRect.x(); + int y = effectiveRect.y(); + int lineHeight = 0; +//! [9] + +//! [10] + QLayoutItem *item; + foreach (item, itemList) { + QWidget *wid = item->widget(); + int spaceX = horizontalSpacing(); + if (spaceX == -1) + spaceX = wid->style()->layoutSpacing( + QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Horizontal); + int spaceY = verticalSpacing(); + if (spaceY == -1) + spaceY = wid->style()->layoutSpacing( + QSizePolicy::PushButton, QSizePolicy::PushButton, Qt::Vertical); +//! [10] +//! [11] + int nextX = x + item->sizeHint().width() + spaceX; + if (nextX - spaceX > effectiveRect.right() && lineHeight > 0) { + x = effectiveRect.x(); + y = y + lineHeight + spaceY; + nextX = x + item->sizeHint().width() + spaceX; + lineHeight = 0; + } + + if (!testOnly) + item->setGeometry(QRect(QPoint(x, y), item->sizeHint())); + + x = nextX; + lineHeight = qMax(lineHeight, item->sizeHint().height()); + } + return y + lineHeight - rect.y() + bottom; +} +//! [11] +//! [12] +int FlowLayout::smartSpacing(QStyle::PixelMetric pm) const +{ + QObject *parent = this->parent(); + if (!parent) { + return -1; + } else if (parent->isWidgetType()) { + QWidget *pw = static_cast(parent); + return pw->style()->pixelMetric(pm, 0, pw); + } else { + return static_cast(parent)->spacing(); + } +} +//! [12] diff --git a/src/qt/flowlayout.h b/src/qt/flowlayout.h new file mode 100644 index 0000000..0643287 --- /dev/null +++ b/src/qt/flowlayout.h @@ -0,0 +1,78 @@ +/**************************************************************************** +** +** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** This file is part of the examples of the Qt Toolkit. +** +** $QT_BEGIN_LICENSE:BSD$ +** You may use this file under the terms of the BSD license as follows: +** +** "Redistribution and use in source and binary forms, with or without +** modification, are permitted provided that the following conditions are +** met: +** * Redistributions of source code must retain the above copyright +** notice, this list of conditions and the following disclaimer. +** * 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. +** * Neither the name of Digia Plc and its Subsidiary(-ies) 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 +** OWNER 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." +** +** $QT_END_LICENSE$ +** +****************************************************************************/ + +#ifndef FLOWLAYOUT_H +#define FLOWLAYOUT_H + +#include +#include +#include +//! [0] +class FlowLayout : public QLayout +{ +public: + FlowLayout(QWidget *parent, int margin = -1, int hSpacing = -1, int vSpacing = -1); + FlowLayout(int margin = -1, int hSpacing = -1, int vSpacing = -1); + ~FlowLayout(); + + void addItem(QLayoutItem *item); + int horizontalSpacing() const; + int verticalSpacing() const; + Qt::Orientations expandingDirections() const; + bool hasHeightForWidth() const; + int heightForWidth(int) const; + int count() const; + QLayoutItem *itemAt(int index) const; + QSize minimumSize() const; + void setGeometry(const QRect &rect); + QSize sizeHint() const; + QLayoutItem *takeAt(int index); + +private: + int doLayout(const QRect &rect, bool testOnly) const; + int smartSpacing(QStyle::PixelMetric pm) const; + + QList itemList; + int m_hSpace; + int m_vSpace; +}; +//! [0] + +#endif diff --git a/src/qt/forms/addeditadrenalinenode.ui b/src/qt/forms/addeditadrenalinenode.ui new file mode 100644 index 0000000..67a683a --- /dev/null +++ b/src/qt/forms/addeditadrenalinenode.ui @@ -0,0 +1,157 @@ + + + AddEditAdrenalineNode + + + + 0 + 0 + 540 + 241 + + + + Add/Edit MasterNode Node + + + true + + + + + + 0 + + + 0 + + + + + + 0 + 0 + + + + <html><head/><body><p>Enter an Alias (friendly name) for your Masternode and its address (either clearnet IP and port or Tor onion address and port). The address should be in the format 123.456.789.123:9999 or akjdsafxjkhasdf.onion:9999. A masternode private key and a collateral address will both be automatically generated for you. You must send exactly 5000000 GENIUS to the collateral address.</p></body></html> + + + true + + + + + + + 0 + + + + + Alias + + + + + + + + + + + + 0 + + + + + Address + + + + + + + + + + + + 0 + + + + + + + + + + + Qt::Horizontal + + + + 40 + 48 + + + + + + + + + 75 + true + + + + + + + Qt::PlainText + + + true + + + + + + + Qt::Horizontal + + + + 40 + 48 + + + + + + + + &OK + + + + + + + &Cancel + + + false + + + + + + + + + + diff --git a/src/qt/forms/adrenalinenodeconfigdialog.ui b/src/qt/forms/adrenalinenodeconfigdialog.ui new file mode 100644 index 0000000..dcfcac7 --- /dev/null +++ b/src/qt/forms/adrenalinenodeconfigdialog.ui @@ -0,0 +1,74 @@ + + + AdrenalineNodeConfigDialog + + + + 0 + 0 + 620 + 250 + + + + MasterNode Node Configuration Template + + + + + + <html><head/><body><p>This pane shows an example genius.conf template with the necessary masternode settings.</p></body></html> + + + true + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Close + + + + + + + + + buttonBox + accepted() + AdrenalineNodeConfigDialog + accept() + + + 248 + 254 + + + 157 + 274 + + + + + buttonBox + rejected() + AdrenalineNodeConfigDialog + reject() + + + 316 + 260 + + + 286 + 274 + + + + + diff --git a/src/qt/forms/darksendconfig.ui b/src/qt/forms/darksendconfig.ui new file mode 100644 index 0000000..3c6aa7b --- /dev/null +++ b/src/qt/forms/darksendconfig.ui @@ -0,0 +1,188 @@ + + + DarksendConfig + + + + 0 + 0 + 630 + 307 + + + + Configure Darksend + + + + + 20 + 70 + 151 + 27 + + + + Basic Privacy + + + + + + 20 + 140 + 151 + 27 + + + + High Privacy + + + + + + 20 + 210 + 151 + 27 + + + + Maximum Privacy + + + + + + 30 + 20 + 571 + 31 + + + + Please select a privacy level. + + + + + + 190 + 70 + 421 + 21 + + + + Use 2 separate masternodes to mix funds up to 1000 GENIUS + + + + + + 190 + 140 + 411 + 21 + + + + Use 8 separate masternodes to mix funds up to 1000 GENIUS + + + + + + 190 + 210 + 421 + 21 + + + + Use 16 separate masternodes + + + + + + 40 + 100 + 561 + 21 + + + + This option is the quickest and will cost about ~0.025 GENIUS to anonymize 1000 GENIUS + + + + + + 40 + 170 + 561 + 21 + + + + This option is moderately fast and will cost about 0.05 GENIUS to anonymize 1000 GENIUS + + + + + + 40 + 240 + 561 + 21 + + + + This is the slowest and most secure option. Using maximum anonymity will cost + + + + + + 40 + 260 + 561 + 21 + + + + 0.1 GENIUS per 1000 GENIUS you anonymize. + + + + + + 10 + 120 + 601 + 16 + + + + Qt::Horizontal + + + + + + 10 + 190 + 601 + 16 + + + + Qt::Horizontal + + + + + + diff --git a/src/qt/forms/editaddressdialog.ui b/src/qt/forms/editaddressdialog.ui index b4a4c1b..677ad18 100644 --- a/src/qt/forms/editaddressdialog.ui +++ b/src/qt/forms/editaddressdialog.ui @@ -53,6 +53,13 @@ + + + + &Stealth Address + + + diff --git a/src/qt/forms/masternodemanager.ui b/src/qt/forms/masternodemanager.ui new file mode 100644 index 0000000..a313774 --- /dev/null +++ b/src/qt/forms/masternodemanager.ui @@ -0,0 +1,339 @@ + + + MasternodeManager + + + + 0 + 0 + 723 + 457 + + + + Form + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 0 + + + + + 1 + + + + MasterNode Network + + + + + + QAbstractItemView::NoEditTriggers + + + true + + + QAbstractItemView::SelectRows + + + true + + + + Address + + + + + Rank + + + + + Active + + + + + Active (secs) + + + + + Last Seen + + + + + Pubkey + + + + + + + + 0 + + + + + Masternode Count: + + + + + + + 0 + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + My Masternodes + + + + + + 0 + + + + + + + &Create... + + + + + + + Create &Local + + + + + + + Copy &Address + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + QAbstractItemView::NoEditTriggers + + + true + + + QAbstractItemView::SingleSelection + + + QAbstractItemView::SelectRows + + + true + + + + Alias + + + + + IP/Onion + + + + + Status + + + + + Local + + + + + Collateral Address + + + + + + + + 0 + + + + + &Edit + + + + + + + &Get Config + + + + + + + &Remove + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + 0 + + + + + &Start + + + + + + + Sto&p + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + 0 + + + + + S&tart All + + + + + + + St&op All + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + + + + + + + diff --git a/src/qt/forms/messagepage.ui b/src/qt/forms/messagepage.ui new file mode 100644 index 0000000..8fe9c65 --- /dev/null +++ b/src/qt/forms/messagepage.ui @@ -0,0 +1,246 @@ + + + MessagePage + + + + 0 + 0 + 793 + 419 + + + + Address Book + + + + + + These are your sent and received encrypted messages. Click on an item to read it. + + + Qt::PlainText + + + true + + + + + + + Qt::CustomContextMenu + + + Click on a message to view it + + + false + + + true + + + QAbstractItemView::SingleSelection + + + QAbstractItemView::SelectRows + + + true + + + false + + + + + + + + + + + + + 2 + + + 0 + + + 6 + + + 0 + + + 0 + + + + + + + &Back + + + + :/icons/quit:/icons/quit + + + + + + + Contact: + + + + + + + + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + #listConversation { color: #000000; } + + + + + + + + + + + + + + 0 + 100 + + + + + + + + + + &New Conversation + + + + :/icons/add:/icons/add + + + + + + + Sign a message to prove you own a Genius address + + + &Send + + + + :/icons/send:/icons/send + + + + + + + Copy the currently selected address to the system clipboard + + + &Copy From Address + + + + :/icons/editcopy:/icons/editcopy + + + + + + + Copy the currently selected address to the system clipboard + + + Copy To &Address + + + + :/icons/editcopy:/icons/editcopy + + + + + + + Delete the currently selected address from the list + + + &Delete + + + + :/icons/remove:/icons/remove + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + + + + + MRichTextEdit + QWidget +
mrichtextedit.h
+ 1 +
+
+ + + + +
diff --git a/src/qt/forms/overviewpage.ui b/src/qt/forms/overviewpage.ui index 8db9c2c..35d30b2 100644 --- a/src/qt/forms/overviewpage.ui +++ b/src/qt/forms/overviewpage.ui @@ -14,6 +14,18 @@ Form + + 0 + + + 0 + + + 0 + + + 0 + @@ -32,8 +44,26 @@ - + + + background-color: transparent; + + + true + + + + + 0 + 0 + 350 + 500 + + + + + @@ -279,8 +309,257 @@ - - + + + + + + + + 0 + 0 + + + + + 300 + 261 + + + + background:transparent; + + + QFrame::StyledPanel + + + QFrame::Raised + + + + + 0 + 0 + 331 + 261 + + + + + + + QFormLayout::AllNonFixedFieldsGrow + + + 30 + + + 12 + + + + + Status: + + + + + + + color: rgb(0, 0, 0); + + + Enabled/Disabled + + + + + + + color: rgb(0, 0, 0); + + + Completion: + + + + + + + + 154 + 16777215 + + + + background:transparent; + + + 0 + + + + + + + color: rgb(0, 0, 0); + + + Darksend Balance: + + + + + + + + 75 + true + + + + color: rgb(0, 0, 0); + + + 0 GENIUS + + + + + + + color: rgb(0, 0, 0); + + + Amount and Rounds: + + + + + + + color: rgb(0, 0, 0); + + + 0 GENIUS / 0 Rounds + + + + + + + color: rgb(0, 0, 0); + + + Submitted Denom: + + + + + + + The denominations you submitted to the Adrenaline Node. To mix, other users must submit the exact same denominations. + + + color: rgb(0, 0, 0); + + + n/a + + + + + + + + + + 288 + 43 + + + + color: rgb(0, 0, 0); + + + (Last Message) + + + Qt::AlignLeading|Qt::AlignLeft|Qt::AlignTop + + + true + + + + + + + + + + 0 + 0 + + + + color: rgb(217, 0, 7); + + + Start/Stop + + + + + + + + 0 + 0 + + + + Reset the current status of Darksend (can interrupt Darksend if it's in the process of Mixing, which can cost you money!) + + + false + + + color: rgb(217, 0, 7); + + + Reset + + + + + + + + 0 + 0 + + + + Try to manually submit a Darksend request. + + + color: rgb(217, 0, 7); + + + Try Mix + + + + + + + + + + + + @@ -355,11 +634,23 @@ - - + + +
+ + + + + + FlowLayout + QLayout +
flowlayout.h
+ 1 +
+
diff --git a/src/qt/forms/sendcoinsentry.ui b/src/qt/forms/sendcoinsentry.ui index 5d35bba..8e83e1f 100644 --- a/src/qt/forms/sendcoinsentry.ui +++ b/src/qt/forms/sendcoinsentry.ui @@ -76,7 +76,7 @@ The address to send the payment to (e.g. C8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i) - 34 + 80 diff --git a/src/qt/forms/sendmessagesdialog.ui b/src/qt/forms/sendmessagesdialog.ui new file mode 100644 index 0000000..3f508a5 --- /dev/null +++ b/src/qt/forms/sendmessagesdialog.ui @@ -0,0 +1,262 @@ + + + SendMessagesDialog + + + + 0 + 0 + 850 + 400 + + + + Send Messages + + + #SendMessagesDialog { background-color: #383838; } + + + + 8 + + + + + + 0 + 0 + + + + + 16777215 + 16777215 + + + + QFrame::StyledPanel + + + QFrame::Sunken + + + + + + color: #ffffff; + + + Address &From: + + + addressFrom + + + + + + + 1 + + + + + + + + Choose address from address book + + + + + + + :/icons/address-book:/icons/address-book + + + Alt+A + + + + + + + Paste address from clipboard + + + + + + + :/icons/editpaste:/icons/editpaste + + + Alt+P + + + + + + + + + + + + true + + + + + 0 + 0 + 830 + 298 + + + + + 0 + + + 0 + + + 0 + + + 0 + + + + + 6 + + + + + + + Qt::Vertical + + + + 20 + 40 + + + + + + + + + + + + + + Send to multiple recipients at once + + + Add &Recipient + + + + :/icons/add:/icons/add + + + false + + + + + + + + 0 + 0 + + + + Remove all transaction fields + + + Clear &All + + + + :/icons/remove:/icons/remove + + + 300 + + + false + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + + + + 150 + 0 + + + + Confirm the send action + + + S&end + + + + :/icons/send:/icons/send + + + true + + + + + + + &Close + + + + :/icons/quit:/icons/quit + + + + + + + + + + QValidatedLineEdit + QLineEdit +
qvalidatedlineedit.h
+
+
+ + + + +
diff --git a/src/qt/forms/sendmessagesentry.ui b/src/qt/forms/sendmessagesentry.ui new file mode 100644 index 0000000..e7cb0bf --- /dev/null +++ b/src/qt/forms/sendmessagesentry.ui @@ -0,0 +1,184 @@ + + + SendMessagesEntry + + + + 0 + 0 + 729 + 236 + + + + Form + + + QFrame::StyledPanel + + + QFrame::Sunken + + + + 12 + + + + + 0 + + + + + The address to send the payment to (e.g. 2XfvvXkSpTAJNP8CjtUgo9YV2M7pDxinKc) + + + 34 + + + + + + + Choose address from address book + + + + + + + :/icons/address-book:/icons/address-book + + + Alt+A + + + + + + + Paste address from clipboard + + + + + + + :/icons/editpaste:/icons/editpaste + + + Alt+P + + + + + + + Remove this recipient + + + + + + + :/icons/remove:/icons/remove + + + + + + + + + &Message: + + + Qt::AlignRight|Qt::AlignTop|Qt::AlignTrailing + + + messageText + + + + + + + Send &To: + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + sendTo + + + + + + + true + + + Qt::WheelFocus + + + false + + + + + + + true + + + Enter a label for this address to add it to your address book + + + + + + + &Label: + + + Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter + + + addAsLabel + + + + + + + &Public Key: + + + publicKey + + + + + + + + + + + QValidatedLineEdit + QLineEdit +
qvalidatedlineedit.h
+
+ + QValidatedTextEdit + QPlainTextEdit +
qvalidatedtextedit.h
+
+
+ + + + +
diff --git a/src/qt/locale/bitcoin_af_ZA.qm b/src/qt/locale/bitcoin_af_ZA.qm deleted file mode 100644 index 2f6318b..0000000 Binary files a/src/qt/locale/bitcoin_af_ZA.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_ar.qm b/src/qt/locale/bitcoin_ar.qm deleted file mode 100644 index f75da17..0000000 Binary files a/src/qt/locale/bitcoin_ar.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_be_BY.qm b/src/qt/locale/bitcoin_be_BY.qm deleted file mode 100644 index d319d0a..0000000 Binary files a/src/qt/locale/bitcoin_be_BY.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_bg.qm b/src/qt/locale/bitcoin_bg.qm deleted file mode 100644 index e5adc84..0000000 Binary files a/src/qt/locale/bitcoin_bg.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_bs.qm b/src/qt/locale/bitcoin_bs.qm deleted file mode 100644 index 89a73a4..0000000 Binary files a/src/qt/locale/bitcoin_bs.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_ca.qm b/src/qt/locale/bitcoin_ca.qm deleted file mode 100644 index c99b30c..0000000 Binary files a/src/qt/locale/bitcoin_ca.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_ca@valencia.qm b/src/qt/locale/bitcoin_ca@valencia.qm deleted file mode 100644 index dece326..0000000 Binary files a/src/qt/locale/bitcoin_ca@valencia.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_ca_ES.qm b/src/qt/locale/bitcoin_ca_ES.qm deleted file mode 100644 index 17623bb..0000000 Binary files a/src/qt/locale/bitcoin_ca_ES.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_cs.qm b/src/qt/locale/bitcoin_cs.qm deleted file mode 100644 index 60c5820..0000000 Binary files a/src/qt/locale/bitcoin_cs.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_cy.qm b/src/qt/locale/bitcoin_cy.qm deleted file mode 100644 index 92bce78..0000000 Binary files a/src/qt/locale/bitcoin_cy.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_da.qm b/src/qt/locale/bitcoin_da.qm deleted file mode 100644 index 2d3f251..0000000 Binary files a/src/qt/locale/bitcoin_da.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_de.qm b/src/qt/locale/bitcoin_de.qm deleted file mode 100644 index 02fbba3..0000000 Binary files a/src/qt/locale/bitcoin_de.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_el_GR.qm b/src/qt/locale/bitcoin_el_GR.qm deleted file mode 100644 index 25e997e..0000000 Binary files a/src/qt/locale/bitcoin_el_GR.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_en.qm b/src/qt/locale/bitcoin_en.qm deleted file mode 100644 index d491192..0000000 Binary files a/src/qt/locale/bitcoin_en.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_eo.qm b/src/qt/locale/bitcoin_eo.qm deleted file mode 100644 index 446c8fb..0000000 Binary files a/src/qt/locale/bitcoin_eo.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_es.qm b/src/qt/locale/bitcoin_es.qm deleted file mode 100644 index 125e1a5..0000000 Binary files a/src/qt/locale/bitcoin_es.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_es_CL.qm b/src/qt/locale/bitcoin_es_CL.qm deleted file mode 100644 index 4231bda..0000000 Binary files a/src/qt/locale/bitcoin_es_CL.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_es_DO.qm b/src/qt/locale/bitcoin_es_DO.qm deleted file mode 100644 index 13f9f84..0000000 Binary files a/src/qt/locale/bitcoin_es_DO.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_es_MX.qm b/src/qt/locale/bitcoin_es_MX.qm deleted file mode 100644 index 59b66e9..0000000 Binary files a/src/qt/locale/bitcoin_es_MX.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_es_UY.qm b/src/qt/locale/bitcoin_es_UY.qm deleted file mode 100644 index af4b173..0000000 Binary files a/src/qt/locale/bitcoin_es_UY.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_et.qm b/src/qt/locale/bitcoin_et.qm deleted file mode 100644 index 28913e4..0000000 Binary files a/src/qt/locale/bitcoin_et.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_eu_ES.qm b/src/qt/locale/bitcoin_eu_ES.qm deleted file mode 100644 index 4d663f3..0000000 Binary files a/src/qt/locale/bitcoin_eu_ES.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_fa.qm b/src/qt/locale/bitcoin_fa.qm deleted file mode 100644 index f8e97f7..0000000 Binary files a/src/qt/locale/bitcoin_fa.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_fa_IR.qm b/src/qt/locale/bitcoin_fa_IR.qm deleted file mode 100644 index 13b6778..0000000 Binary files a/src/qt/locale/bitcoin_fa_IR.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_fi.qm b/src/qt/locale/bitcoin_fi.qm deleted file mode 100644 index 4760f66..0000000 Binary files a/src/qt/locale/bitcoin_fi.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_fr.qm b/src/qt/locale/bitcoin_fr.qm deleted file mode 100644 index 423adea..0000000 Binary files a/src/qt/locale/bitcoin_fr.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_fr_CA.qm b/src/qt/locale/bitcoin_fr_CA.qm deleted file mode 100644 index aaccee6..0000000 Binary files a/src/qt/locale/bitcoin_fr_CA.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_gl.qm b/src/qt/locale/bitcoin_gl.qm deleted file mode 100644 index c5ba837..0000000 Binary files a/src/qt/locale/bitcoin_gl.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_he.qm b/src/qt/locale/bitcoin_he.qm deleted file mode 100644 index 6d9cb47..0000000 Binary files a/src/qt/locale/bitcoin_he.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_hi_IN.qm b/src/qt/locale/bitcoin_hi_IN.qm deleted file mode 100644 index 8cd6b64..0000000 Binary files a/src/qt/locale/bitcoin_hi_IN.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_hr.qm b/src/qt/locale/bitcoin_hr.qm deleted file mode 100644 index db22028..0000000 Binary files a/src/qt/locale/bitcoin_hr.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_hu.qm b/src/qt/locale/bitcoin_hu.qm deleted file mode 100644 index dc4e54f..0000000 Binary files a/src/qt/locale/bitcoin_hu.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_id_ID.qm b/src/qt/locale/bitcoin_id_ID.qm deleted file mode 100644 index 9f2d8b5..0000000 Binary files a/src/qt/locale/bitcoin_id_ID.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_it.qm b/src/qt/locale/bitcoin_it.qm deleted file mode 100644 index f47750c..0000000 Binary files a/src/qt/locale/bitcoin_it.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_ja.qm b/src/qt/locale/bitcoin_ja.qm deleted file mode 100644 index a664f7c..0000000 Binary files a/src/qt/locale/bitcoin_ja.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_ka.qm b/src/qt/locale/bitcoin_ka.qm deleted file mode 100644 index dba785a..0000000 Binary files a/src/qt/locale/bitcoin_ka.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_kk_KZ.qm b/src/qt/locale/bitcoin_kk_KZ.qm deleted file mode 100644 index 5106908..0000000 Binary files a/src/qt/locale/bitcoin_kk_KZ.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_ko_KR.qm b/src/qt/locale/bitcoin_ko_KR.qm deleted file mode 100644 index f2a2f22..0000000 Binary files a/src/qt/locale/bitcoin_ko_KR.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_ky.qm b/src/qt/locale/bitcoin_ky.qm deleted file mode 100644 index df83eb2..0000000 Binary files a/src/qt/locale/bitcoin_ky.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_la.qm b/src/qt/locale/bitcoin_la.qm deleted file mode 100644 index 012606f..0000000 Binary files a/src/qt/locale/bitcoin_la.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_lt.qm b/src/qt/locale/bitcoin_lt.qm deleted file mode 100644 index 56def70..0000000 Binary files a/src/qt/locale/bitcoin_lt.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_lv_LV.qm b/src/qt/locale/bitcoin_lv_LV.qm deleted file mode 100644 index 022d6c3..0000000 Binary files a/src/qt/locale/bitcoin_lv_LV.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_ms_MY.qm b/src/qt/locale/bitcoin_ms_MY.qm deleted file mode 100644 index 22d0346..0000000 Binary files a/src/qt/locale/bitcoin_ms_MY.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_nb.qm b/src/qt/locale/bitcoin_nb.qm deleted file mode 100644 index d362fb8..0000000 Binary files a/src/qt/locale/bitcoin_nb.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_nl.qm b/src/qt/locale/bitcoin_nl.qm deleted file mode 100644 index bb2c9fd..0000000 Binary files a/src/qt/locale/bitcoin_nl.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_pam.qm b/src/qt/locale/bitcoin_pam.qm deleted file mode 100644 index f215164..0000000 Binary files a/src/qt/locale/bitcoin_pam.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_pl.qm b/src/qt/locale/bitcoin_pl.qm deleted file mode 100644 index a6feba1..0000000 Binary files a/src/qt/locale/bitcoin_pl.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_pt_BR.qm b/src/qt/locale/bitcoin_pt_BR.qm deleted file mode 100644 index 4f704a2..0000000 Binary files a/src/qt/locale/bitcoin_pt_BR.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_pt_PT.qm b/src/qt/locale/bitcoin_pt_PT.qm deleted file mode 100644 index 4a7331d..0000000 Binary files a/src/qt/locale/bitcoin_pt_PT.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_ro_RO.qm b/src/qt/locale/bitcoin_ro_RO.qm deleted file mode 100644 index 56cd83d..0000000 Binary files a/src/qt/locale/bitcoin_ro_RO.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_ru.qm b/src/qt/locale/bitcoin_ru.qm deleted file mode 100644 index c5af4f9..0000000 Binary files a/src/qt/locale/bitcoin_ru.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_sah.qm b/src/qt/locale/bitcoin_sah.qm deleted file mode 100644 index 38ca3b6..0000000 Binary files a/src/qt/locale/bitcoin_sah.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_sk.qm b/src/qt/locale/bitcoin_sk.qm deleted file mode 100644 index b5a36a2..0000000 Binary files a/src/qt/locale/bitcoin_sk.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_sl_SI.qm b/src/qt/locale/bitcoin_sl_SI.qm deleted file mode 100644 index 3f7fca4..0000000 Binary files a/src/qt/locale/bitcoin_sl_SI.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_sq.qm b/src/qt/locale/bitcoin_sq.qm deleted file mode 100644 index 460daab..0000000 Binary files a/src/qt/locale/bitcoin_sq.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_sr.qm b/src/qt/locale/bitcoin_sr.qm deleted file mode 100644 index 602d286..0000000 Binary files a/src/qt/locale/bitcoin_sr.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_sv.qm b/src/qt/locale/bitcoin_sv.qm deleted file mode 100644 index a9b5443..0000000 Binary files a/src/qt/locale/bitcoin_sv.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_th_TH.qm b/src/qt/locale/bitcoin_th_TH.qm deleted file mode 100644 index cd3e597..0000000 Binary files a/src/qt/locale/bitcoin_th_TH.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_tr.qm b/src/qt/locale/bitcoin_tr.qm deleted file mode 100644 index 8cca9d0..0000000 Binary files a/src/qt/locale/bitcoin_tr.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_uk.qm b/src/qt/locale/bitcoin_uk.qm deleted file mode 100644 index 39175ad..0000000 Binary files a/src/qt/locale/bitcoin_uk.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_ur_PK.qm b/src/qt/locale/bitcoin_ur_PK.qm deleted file mode 100644 index 31cf0a9..0000000 Binary files a/src/qt/locale/bitcoin_ur_PK.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_vi.qm b/src/qt/locale/bitcoin_vi.qm deleted file mode 100644 index 8cb33c4..0000000 Binary files a/src/qt/locale/bitcoin_vi.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_vi_VN.qm b/src/qt/locale/bitcoin_vi_VN.qm deleted file mode 100644 index 07335c3..0000000 Binary files a/src/qt/locale/bitcoin_vi_VN.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_zh_CN.qm b/src/qt/locale/bitcoin_zh_CN.qm deleted file mode 100644 index 976364e..0000000 Binary files a/src/qt/locale/bitcoin_zh_CN.qm and /dev/null differ diff --git a/src/qt/locale/bitcoin_zh_TW.qm b/src/qt/locale/bitcoin_zh_TW.qm deleted file mode 100644 index 8fa6443..0000000 Binary files a/src/qt/locale/bitcoin_zh_TW.qm and /dev/null differ diff --git a/src/qt/masternodemanager.cpp b/src/qt/masternodemanager.cpp new file mode 100644 index 0000000..45b817f --- /dev/null +++ b/src/qt/masternodemanager.cpp @@ -0,0 +1,537 @@ +#include "masternodemanager.h" +#include "ui_masternodemanager.h" +#include "addeditadrenalinenode.h" +#include "adrenalinenodeconfigdialog.h" + +#include "sync.h" +#include "clientmodel.h" +#include "walletmodel.h" +#include "activemasternode.h" +#include "masternodeconfig.h" +#include "masternode.h" +#include "walletdb.h" +#include "wallet.h" +#include "init.h" +#include "net.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +MasternodeManager::MasternodeManager(QWidget *parent) : + QWidget(parent), + ui(new Ui::MasternodeManager), + clientModel(0), + walletModel(0) +{ + ui->setupUi(this); + + ui->editButton->setEnabled(false); + ui->getConfigButton->setEnabled(false); + ui->startButton->setEnabled(false); + ui->stopButton->setEnabled(false); + ui->copyAddressButton->setEnabled(false); + + ui->tableWidget->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + ui->tableWidget_2->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeToContents); + + subscribeToCoreSignals(); + + timer = new QTimer(this); + connect(timer, SIGNAL(timeout()), this, SLOT(updateNodeList())); + if(!GetBoolArg("-reindexaddr", false)) + timer->start(30000); + + + + updateNodeList(); +} + +MasternodeManager::~MasternodeManager() +{ + delete ui; +} + +static void NotifyAdrenalineNodeUpdated(MasternodeManager *page, CAdrenalineNodeConfig nodeConfig) +{ + // alias, address, privkey, collateral address + QString alias = QString::fromStdString(nodeConfig.sAlias); + QString addr = QString::fromStdString(nodeConfig.sAddress); + QString privkey = QString::fromStdString(nodeConfig.sMasternodePrivKey); + QString collateral = QString::fromStdString(nodeConfig.sCollateralAddress); + QString local = "No"; + if(nodeConfig.isLocal) + local = "Yes"; + QMetaObject::invokeMethod(page, "updateAdrenalineNode", Qt::QueuedConnection, + Q_ARG(QString, alias), + Q_ARG(QString, addr), + Q_ARG(QString, privkey), + Q_ARG(QString, collateral), + Q_ARG(QString, local) + ); +} + +void MasternodeManager::subscribeToCoreSignals() +{ + // Connect signals to core + uiInterface.NotifyAdrenalineNodeChanged.connect(boost::bind(&NotifyAdrenalineNodeUpdated, this, _1)); +} + +void MasternodeManager::unsubscribeFromCoreSignals() +{ + // Disconnect signals from core + uiInterface.NotifyAdrenalineNodeChanged.disconnect(boost::bind(&NotifyAdrenalineNodeUpdated, this, _1)); +} + +void MasternodeManager::on_tableWidget_2_itemSelectionChanged() +{ + if(ui->tableWidget_2->selectedItems().count() > 0) + { + ui->editButton->setEnabled(true); + ui->getConfigButton->setEnabled(true); + ui->startButton->setEnabled(true); + ui->stopButton->setEnabled(true); + ui->copyAddressButton->setEnabled(true); + } +} + +void MasternodeManager::updateAdrenalineNode(QString alias, QString addr, QString privkey, QString collateral, QString local) +{ + LOCK(cs_adrenaline); + bool bFound = false; + int nodeRow = 0; + for(int i=0; i < ui->tableWidget_2->rowCount(); i++) + { + if(ui->tableWidget_2->item(i, 0)->text() == alias) + { + bFound = true; + nodeRow = i; + break; + } + } + + if(nodeRow == 0 && !bFound) + ui->tableWidget_2->insertRow(0); + + QTableWidgetItem *aliasItem = new QTableWidgetItem(alias); + QTableWidgetItem *addrItem = new QTableWidgetItem(addr); + QTableWidgetItem *statusItem = new QTableWidgetItem(""); + QTableWidgetItem *collateralItem = new QTableWidgetItem(collateral); + QTableWidgetItem *localItem = new QTableWidgetItem(local); + + ui->tableWidget_2->setItem(nodeRow, 0, aliasItem); + ui->tableWidget_2->setItem(nodeRow, 1, addrItem); + ui->tableWidget_2->setItem(nodeRow, 2, statusItem); + ui->tableWidget_2->setItem(nodeRow, 3, localItem); + ui->tableWidget_2->setItem(nodeRow, 4, collateralItem); +} + +static QString seconds_to_DHMS(quint32 duration) +{ + QString res; + int seconds = (int) (duration % 60); + duration /= 60; + int minutes = (int) (duration % 60); + duration /= 60; + int hours = (int) (duration % 24); + int days = (int) (duration / 24); + if((hours == 0)&&(days == 0)) + return res.sprintf("%02dm:%02ds", minutes, seconds); + if (days == 0) + return res.sprintf("%02dh:%02dm:%02ds", hours, minutes, seconds); + return res.sprintf("%dd %02dh:%02dm:%02ds", days, hours, minutes, seconds); +} + +void MasternodeManager::updateNodeList() +{ + TRY_LOCK(cs_masternodes, lockMasternodes); + if(!lockMasternodes) + return; + + ui->countLabel->setText("Updating..."); + ui->tableWidget->clearContents(); + ui->tableWidget->setRowCount(0); + BOOST_FOREACH(CMasterNode mn, vecMasternodes) + { + int mnRow = 0; + ui->tableWidget->insertRow(0); + + // populate list + // Address, Rank, Active, Active Seconds, Last Seen, Pub Key + QTableWidgetItem *activeItem = new QTableWidgetItem(QString::number(mn.IsEnabled())); + QTableWidgetItem *addressItem = new QTableWidgetItem(QString::fromStdString(mn.addr.ToString())); + QTableWidgetItem *rankItem = new QTableWidgetItem(QString::number(GetMasternodeRank(mn.vin, pindexBest->nHeight))); + QTableWidgetItem *activeSecondsItem = new QTableWidgetItem(seconds_to_DHMS((qint64)(mn.lastTimeSeen - mn.now))); + QTableWidgetItem *lastSeenItem = new QTableWidgetItem(QString::fromStdString(DateTimeStrFormat(mn.lastTimeSeen))); + + CScript pubkey; + pubkey =GetScriptForDestination(mn.pubkey.GetID()); + CTxDestination address1; + ExtractDestination(pubkey, address1); + CBitcoinAddress address2(address1); + QTableWidgetItem *pubkeyItem = new QTableWidgetItem(QString::fromStdString(address2.ToString())); + + ui->tableWidget->setItem(mnRow, 0, addressItem); + ui->tableWidget->setItem(mnRow, 1, rankItem); + ui->tableWidget->setItem(mnRow, 2, activeItem); + ui->tableWidget->setItem(mnRow, 3, activeSecondsItem); + ui->tableWidget->setItem(mnRow, 4, lastSeenItem); + ui->tableWidget->setItem(mnRow, 5, pubkeyItem); + } + + ui->countLabel->setText(QString::number(ui->tableWidget->rowCount())); + + if(pwalletMain) + { + LOCK(cs_adrenaline); + BOOST_FOREACH(PAIRTYPE(std::string, CAdrenalineNodeConfig) adrenaline, pwalletMain->mapMyAdrenalineNodes) + { + QString local = "No"; + if(adrenaline.second.isLocal) + local = "Yes"; + updateAdrenalineNode(QString::fromStdString(adrenaline.second.sAlias), QString::fromStdString(adrenaline.second.sAddress), QString::fromStdString(adrenaline.second.sMasternodePrivKey), QString::fromStdString(adrenaline.second.sCollateralAddress), local); + } + } +} + + +void MasternodeManager::setClientModel(ClientModel *model) +{ + this->clientModel = model; + if(model) + { + } +} + +void MasternodeManager::setWalletModel(WalletModel *model) +{ + this->walletModel = model; + if(model && model->getOptionsModel()) + { + } + +} + +void MasternodeManager::on_createButton_clicked() +{ + AddEditAdrenalineNode* aenode = new AddEditAdrenalineNode(); + aenode->exec(); +} + +void MasternodeManager::on_copyAddressButton_clicked() +{ + QItemSelectionModel* selectionModel = ui->tableWidget_2->selectionModel(); + QModelIndexList selected = selectionModel->selectedRows(); + if(selected.count() == 0) + return; + + QModelIndex index = selected.at(0); + int r = index.row(); + std::string sCollateralAddress = ui->tableWidget_2->item(r, 3)->text().toStdString(); + + QApplication::clipboard()->setText(QString::fromStdString(sCollateralAddress)); +} + +void MasternodeManager::on_editButton_clicked() +{ + QItemSelectionModel* selectionModel = ui->tableWidget_2->selectionModel(); + QModelIndexList selected = selectionModel->selectedRows(); + if(selected.count() == 0) + return; + + QModelIndex index = selected.at(0); + int r = index.row(); + std::string sAddress = ui->tableWidget_2->item(r, 1)->text().toStdString(); + + // get existing config entry + +} + +void MasternodeManager::on_getConfigButton_clicked() +{ + QItemSelectionModel* selectionModel = ui->tableWidget_2->selectionModel(); + QModelIndexList selected = selectionModel->selectedRows(); + if(selected.count() == 0) + return; + + QModelIndex index = selected.at(0); + int r = index.row(); + std::string sAddress = ui->tableWidget_2->item(r, 1)->text().toStdString(); + CAdrenalineNodeConfig c = pwalletMain->mapMyAdrenalineNodes[sAddress]; + std::string sPrivKey = c.sMasternodePrivKey; + AdrenalineNodeConfigDialog* d = new AdrenalineNodeConfigDialog(this, QString::fromStdString(sAddress), QString::fromStdString(sPrivKey)); + d->exec(); +} + +void MasternodeManager::on_removeButton_clicked() +{ + QItemSelectionModel* selectionModel = ui->tableWidget_2->selectionModel(); + QModelIndexList selected = selectionModel->selectedRows(); + if(selected.count() == 0) + return; + + QMessageBox::StandardButton confirm; + confirm = QMessageBox::question(this, "Delete Adrenaline Node?", "Are you sure you want to delete this adrenaline node configuration?", QMessageBox::Yes|QMessageBox::No); + + if(confirm == QMessageBox::Yes) + { + QModelIndex index = selected.at(0); + int r = index.row(); + std::string sAddress = ui->tableWidget_2->item(r, 1)->text().toStdString(); + CAdrenalineNodeConfig c = pwalletMain->mapMyAdrenalineNodes[sAddress]; + CWalletDB walletdb(pwalletMain->strWalletFile); + pwalletMain->mapMyAdrenalineNodes.erase(sAddress); + walletdb.EraseAdrenalineNodeConfig(c.sAddress); + ui->tableWidget_2->clearContents(); + ui->tableWidget_2->setRowCount(0); + BOOST_FOREACH(PAIRTYPE(std::string, CAdrenalineNodeConfig) adrenaline, pwalletMain->mapMyAdrenalineNodes) + { + QString local = "No"; + if(adrenaline.second.isLocal) + local = "Yes"; + updateAdrenalineNode(QString::fromStdString(adrenaline.second.sAlias), QString::fromStdString(adrenaline.second.sAddress), QString::fromStdString(adrenaline.second.sMasternodePrivKey), QString::fromStdString(adrenaline.second.sCollateralAddress), local); + } + } +} + +void MasternodeManager::on_localButton_clicked() +{ + bool bAlreadyHaveLocalTree = false; + // Check if a local masternode already exists + BOOST_FOREACH(PAIRTYPE(std::string, CAdrenalineNodeConfig) adrenaline, pwalletMain->mapMyAdrenalineNodes) + { + if(adrenaline.second.isLocal) + { + bAlreadyHaveLocalTree = true; + break; + } + } + if(bAlreadyHaveLocalTree) + { + QMessageBox msg; + msg.setText("A local masternode already exists."); + msg.exec(); + return; + } + + // Only create once the external IP is known + if(GetLocalAddress(NULL).ToStringIP() == "0.0.0.0") + { + QMessageBox msg; + msg.setText("The local external IP is not yet detected. Please try again in a few minutes."); + msg.exec(); + return; + } + + if(pwalletMain->GetBalance() < 5000005*COIN) + { + QMessageBox msg; + msg.setText("You must have at least 5000005 GENIUS to cover the 5000000 GENIUS collateral for a Masternode and the tx fee."); + msg.exec(); + return; + } + + if (pwalletMain->IsLocked()) + { + QMessageBox msg; + msg.setText("Your wallet must be unlocked so that the 5000000 GENIUS collateral can be sent."); + msg.exec(); + return; + } + + // Automatically create an entry for the local address + CAdrenalineNodeConfig c; + c.sAlias = "Local Masternode"; + c.sAddress = GetLocalAddress(NULL).ToStringIPPort(); + CKey secret; + secret.MakeNewKey(false); + c.sMasternodePrivKey = CBitcoinSecret(secret).ToString(); + + CWalletDB walletdb(pwalletMain->strWalletFile); + CAccount account; + walletdb.ReadAccount(c.sAlias, account); + bool bKeyUsed = false; + bool bForceNew = false; + + // Check if the current key has been used + if (account.vchPubKey.IsValid()) + { + CScript scriptPubKey; + scriptPubKey.SetDestination(account.vchPubKey.GetID()); + for (map::iterator it = pwalletMain->mapWallet.begin(); + it != pwalletMain->mapWallet.end() && account.vchPubKey.IsValid(); + ++it) + { + const CWalletTx& wtx = (*it).second; + BOOST_FOREACH(const CTxOut& txout, wtx.vout) + if (txout.scriptPubKey == scriptPubKey) + bKeyUsed = true; + } + } + + // Generate a new key + if (!account.vchPubKey.IsValid() || bForceNew || bKeyUsed) + { + if (!pwalletMain->GetKeyFromPool(account.vchPubKey)) + { + QMessageBox msg; + msg.setText("Keypool ran out, please call keypoolrefill first."); + msg.exec(); + return; + } + pwalletMain->SetAddressBookName(account.vchPubKey.GetID(), c.sAlias); + walletdb.WriteAccount(c.sAlias, account); + } + + c.sCollateralAddress = CBitcoinAddress(account.vchPubKey.GetID()).ToString(); + + c.isLocal = true; + + pwalletMain->mapMyAdrenalineNodes.insert(make_pair(c.sAddress, c)); + walletdb.WriteAdrenalineNodeConfig(c.sAddress, c); + uiInterface.NotifyAdrenalineNodeChanged(c); + + strMasterNodeAddr = c.sAddress; + strMasterNodePrivKey = c.sMasternodePrivKey; + + CKey keyds; + CPubKey pubkeyds; + std::string errorMessage; + if(!darkSendSigner.SetKey(strMasterNodePrivKey, errorMessage, keyds, pubkeyds)) + { + QMessageBox msg; + msg.setText("Invalid masternodeprivkey. Please see documenation."); + msg.exec(); + return; + } + + activeMasternode.pubKeyMasternode = pubkeyds; + fMasterNode = true; + + CWalletTx wtx; + std::string sNarr; + + string strError = pwalletMain->SendMoneyToDestination(CBitcoinAddress(account.vchPubKey.GetID()).Get(), 5000*COIN, sNarr, wtx); + if (strError != "") + { + QMessageBox msg; + msg.setText(QString::fromStdString(strError)); + msg.exec(); + return; + } + else + { + QMessageBox msg; + std::string sMsg = "Local Masternode created and 5000000 GENIUS sent to the collateral address. Transaction hash:\n"; + sMsg += wtx.GetHash().GetHex(); + msg.setText(QString::fromStdString(sMsg)); + msg.exec(); + return; + } +} + +void MasternodeManager::on_startButton_clicked() +{ + // start the node + QItemSelectionModel* selectionModel = ui->tableWidget_2->selectionModel(); + QModelIndexList selected = selectionModel->selectedRows(); + if(selected.count() == 0) + return; + + QModelIndex index = selected.at(0); + int r = index.row(); + std::string sAddress = ui->tableWidget_2->item(r, 1)->text().toStdString(); + CAdrenalineNodeConfig c = pwalletMain->mapMyAdrenalineNodes[sAddress]; + + std::string errorMessage; + bool result = activeMasternode.RegisterByPubKey(c.sAddress, c.sMasternodePrivKey, c.sCollateralAddress, errorMessage); + + QMessageBox msg; + if(result) + msg.setText("Adrenaline Node at " + QString::fromStdString(c.sAddress) + " started."); + else + msg.setText("Error: " + QString::fromStdString(errorMessage)); + + msg.exec(); +} + +void MasternodeManager::on_stopButton_clicked() +{ + // start the node + QItemSelectionModel* selectionModel = ui->tableWidget_2->selectionModel(); + QModelIndexList selected = selectionModel->selectedRows(); + if(selected.count() == 0) + return; + + QModelIndex index = selected.at(0); + int r = index.row(); + std::string sAddress = ui->tableWidget_2->item(r, 1)->text().toStdString(); + CAdrenalineNodeConfig c = pwalletMain->mapMyAdrenalineNodes[sAddress]; + + std::string errorMessage; + bool result = activeMasternode.StopMasterNode(c.sAddress, c.sMasternodePrivKey, errorMessage); + QMessageBox msg; + if(result) + { + msg.setText("Adrenaline Node at " + QString::fromStdString(c.sAddress) + " stopped."); + } + else + { + msg.setText("Error: " + QString::fromStdString(errorMessage)); + } + msg.exec(); +} + +void MasternodeManager::on_startAllButton_clicked() +{ + std::string results; + BOOST_FOREACH(PAIRTYPE(std::string, CAdrenalineNodeConfig) adrenaline, pwalletMain->mapMyAdrenalineNodes) + { + CAdrenalineNodeConfig c = adrenaline.second; + std::string errorMessage; + bool result = activeMasternode.RegisterByPubKey(c.sAddress, c.sMasternodePrivKey, c.sCollateralAddress, errorMessage); + if(result) + { + results += c.sAddress + ": STARTED\n"; + } + else + { + results += c.sAddress + ": ERROR: " + errorMessage + "\n"; + } + } + + QMessageBox msg; + msg.setText(QString::fromStdString(results)); + msg.exec(); +} + +void MasternodeManager::on_stopAllButton_clicked() +{ + std::string results; + BOOST_FOREACH(PAIRTYPE(std::string, CAdrenalineNodeConfig) adrenaline, pwalletMain->mapMyAdrenalineNodes) + { + CAdrenalineNodeConfig c = adrenaline.second; + std::string errorMessage; + bool result = activeMasternode.StopMasterNode(c.sAddress, c.sMasternodePrivKey, errorMessage); + if(result) + { + results += c.sAddress + ": STOPPED\n"; + } + else + { + results += c.sAddress + ": ERROR: " + errorMessage + "\n"; + } + } + + QMessageBox msg; + msg.setText(QString::fromStdString(results)); + msg.exec(); +} diff --git a/src/qt/masternodemanager.h b/src/qt/masternodemanager.h new file mode 100644 index 0000000..33a0439 --- /dev/null +++ b/src/qt/masternodemanager.h @@ -0,0 +1,62 @@ +#ifndef MASTERNODEMANAGER_H +#define MASTERNODEMANAGER_H + +#include "util.h" +#include "sync.h" + +#include +#include + +namespace Ui { + class MasternodeManager; +} +class ClientModel; +class WalletModel; + +QT_BEGIN_NAMESPACE +class QModelIndex; +QT_END_NAMESPACE + +/** Masternode Manager page widget */ +class MasternodeManager : public QWidget +{ + Q_OBJECT + +public: + explicit MasternodeManager(QWidget *parent = 0); + ~MasternodeManager(); + + void setClientModel(ClientModel *clientModel); + void setWalletModel(WalletModel *walletModel); + + +public slots: + void updateNodeList(); + void updateAdrenalineNode(QString alias, QString addr, QString privkey, QString collateral, QString local); + +signals: + +private: + QTimer *timer; + Ui::MasternodeManager *ui; + ClientModel *clientModel; + WalletModel *walletModel; + CCriticalSection cs_adrenaline; + void subscribeToCoreSignals(); + void unsubscribeFromCoreSignals(); + +private slots: + void on_copyAddressButton_clicked(); + void on_createButton_clicked(); + void on_editButton_clicked(); + void on_getConfigButton_clicked(); + void on_localButton_clicked(); + void on_startButton_clicked(); + void on_stopButton_clicked(); + void on_startAllButton_clicked(); + void on_stopAllButton_clicked(); + void on_removeButton_clicked(); + void on_tableWidget_2_itemSelectionChanged(); +}; + +#endif // MASTERNODEMANAGER_H diff --git a/src/qt/messagemodel.cpp b/src/qt/messagemodel.cpp new file mode 100644 index 0000000..ad81329 --- /dev/null +++ b/src/qt/messagemodel.cpp @@ -0,0 +1,619 @@ +#include "guiutil.h" +#include "guiconstants.h" +#include "bitcoinunits.h" +#include "optionsmodel.h" +#include "walletmodel.h" +#include "messagemodel.h" +#include "addresstablemodel.h" + +#include "ui_interface.h" +#include "base58.h" +#include "json_spirit.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +Q_DECLARE_METATYPE(std::vector); + +QList ambiguous; /**< Specifies Ambiguous addresses */ + +const QString MessageModel::Sent = "Sent"; +const QString MessageModel::Received = "Received"; + +struct MessageTableEntryLessThan +{ + bool operator()(const MessageTableEntry &a, const MessageTableEntry &b) const {return a.received_datetime < b.received_datetime;}; + bool operator()(const MessageTableEntry &a, const QDateTime &b) const {return a.received_datetime < b;} + bool operator()(const QDateTime &a, const MessageTableEntry &b) const {return a < b.received_datetime;} +}; + +// Private implementation +class MessageTablePriv +{ +public: + QList cachedMessageTable; + MessageModel *parent; + + MessageTablePriv(MessageModel *parent): + parent(parent) {} + + void refreshMessageTable() + { + cachedMessageTable.clear(); + + if (parent->getWalletModel()->getEncryptionStatus() == WalletModel::Locked) + { + // -- messages are stored encrypted, can't load them without the private keys + return; + }; + + { + LOCK(cs_smsgDB); + + SecMsgDB dbSmsg; + + if (!dbSmsg.Open("cr+")) + //throw runtime_error("Could not open DB."); + return; + + unsigned char chKey[18]; + std::vector vchKey; + vchKey.resize(18); + + SecMsgStored smsgStored; + MessageData msg; + QString label; + QDateTime sent_datetime; + QDateTime received_datetime; + + std::string sPrefix("im"); + leveldb::Iterator* it = dbSmsg.pdb->NewIterator(leveldb::ReadOptions()); + while (dbSmsg.NextSmesg(it, sPrefix, chKey, smsgStored)) + { + uint32_t nPayload = smsgStored.vchMessage.size() - SMSG_HDR_LEN; + if (SecureMsgDecrypt(false, smsgStored.sAddrTo, &smsgStored.vchMessage[0], &smsgStored.vchMessage[SMSG_HDR_LEN], nPayload, msg) == 0) + { + label = parent->getWalletModel()->getAddressTableModel()->labelForAddress(QString::fromStdString(msg.sFromAddress)); + + sent_datetime .setTime_t(msg.timestamp); + received_datetime.setTime_t(smsgStored.timeReceived); + + memcpy(&vchKey[0], chKey, 18); + + addMessageEntry(MessageTableEntry(vchKey, + MessageTableEntry::Received, + label, + QString::fromStdString(smsgStored.sAddrTo), + QString::fromStdString(msg.sFromAddress), + sent_datetime, + received_datetime, + (char*)&msg.vchMessage[0]), + true); + } + }; + + delete it; + + sPrefix = "sm"; + it = dbSmsg.pdb->NewIterator(leveldb::ReadOptions()); + while (dbSmsg.NextSmesg(it, sPrefix, chKey, smsgStored)) + { + uint32_t nPayload = smsgStored.vchMessage.size() - SMSG_HDR_LEN; + if (SecureMsgDecrypt(false, smsgStored.sAddrOutbox, &smsgStored.vchMessage[0], &smsgStored.vchMessage[SMSG_HDR_LEN], nPayload, msg) == 0) + { + label = parent->getWalletModel()->getAddressTableModel()->labelForAddress(QString::fromStdString(smsgStored.sAddrTo)); + + sent_datetime .setTime_t(msg.timestamp); + received_datetime.setTime_t(smsgStored.timeReceived); + + memcpy(&vchKey[0], chKey, 18); + + addMessageEntry(MessageTableEntry(vchKey, + MessageTableEntry::Sent, + label, + QString::fromStdString(smsgStored.sAddrTo), + QString::fromStdString(msg.sFromAddress), + sent_datetime, + received_datetime, + (char*)&msg.vchMessage[0]), + true); + } + }; + + delete it; + } + } + + void newMessage(const SecMsgStored& inboxHdr) + { + // we have to copy it, because it doesn't like constants going into Decrypt + SecMsgStored smsgStored = inboxHdr; + MessageData msg; + QString label; + QDateTime sent_datetime; + QDateTime received_datetime; + + uint32_t nPayload = smsgStored.vchMessage.size() - SMSG_HDR_LEN; + if (SecureMsgDecrypt(false, smsgStored.sAddrTo, &smsgStored.vchMessage[0], &smsgStored.vchMessage[SMSG_HDR_LEN], nPayload, msg) == 0) + { + label = parent->getWalletModel()->getAddressTableModel()->labelForAddress(QString::fromStdString(msg.sFromAddress)); + + sent_datetime .setTime_t(msg.timestamp); + received_datetime.setTime_t(smsgStored.timeReceived); + + std::string sPrefix("im"); + SecureMessage* psmsg = (SecureMessage*) &smsgStored.vchMessage[0]; + + std::vector vchKey; + vchKey.resize(18); + memcpy(&vchKey[0], sPrefix.data(), 2); + memcpy(&vchKey[2], &psmsg->timestamp, 8); + memcpy(&vchKey[10], &smsgStored.vchMessage[SMSG_HDR_LEN], 8); // sample + + addMessageEntry(MessageTableEntry(vchKey, + MessageTableEntry::Received, + label, + QString::fromStdString(smsgStored.sAddrTo), + QString::fromStdString(msg.sFromAddress), + sent_datetime, + received_datetime, + (char*)&msg.vchMessage[0]), + false); + } + } + + void newOutboxMessage(const SecMsgStored& outboxHdr) + { + + SecMsgStored smsgStored = outboxHdr; + MessageData msg; + QString label; + QDateTime sent_datetime; + QDateTime received_datetime; + + uint32_t nPayload = smsgStored.vchMessage.size() - SMSG_HDR_LEN; + if (SecureMsgDecrypt(false, smsgStored.sAddrOutbox, &smsgStored.vchMessage[0], &smsgStored.vchMessage[SMSG_HDR_LEN], nPayload, msg) == 0) + { + label = parent->getWalletModel()->getAddressTableModel()->labelForAddress(QString::fromStdString(smsgStored.sAddrTo)); + + sent_datetime .setTime_t(msg.timestamp); + received_datetime.setTime_t(smsgStored.timeReceived); + + std::string sPrefix("sm"); + SecureMessage* psmsg = (SecureMessage*) &smsgStored.vchMessage[0]; + std::vector vchKey; + vchKey.resize(18); + memcpy(&vchKey[0], sPrefix.data(), 2); + memcpy(&vchKey[2], &psmsg->timestamp, 8); + memcpy(&vchKey[10], &smsgStored.vchMessage[SMSG_HDR_LEN], 8); // sample + + addMessageEntry(MessageTableEntry(vchKey, + MessageTableEntry::Sent, + label, + QString::fromStdString(smsgStored.sAddrTo), + QString::fromStdString(msg.sFromAddress), + sent_datetime, + received_datetime, + (char*)&msg.vchMessage[0]), + false); + } + } + + void walletUnlocked() + { + // -- wallet is unlocked, can get at the private keys now + refreshMessageTable(); + + parent->reset(); // reload table view + + if (parent->proxyModel) + { + parent->proxyModel->setFilterRole(false); + parent->proxyModel->setFilterFixedString(""); + parent->resetFilter(); + parent->proxyModel->setFilterRole(MessageModel::Ambiguous); + parent->proxyModel->setFilterFixedString("true"); + } + + //invalidateFilter() + } + + void setEncryptionStatus(int status) + { + if (status == WalletModel::Locked) + { + // -- Wallet is locked, clear secure message display. + cachedMessageTable.clear(); + + parent->reset(); // reload table view + }; + }; + + MessageTableEntry *index(int idx) + { + if(idx >= 0 && idx < cachedMessageTable.size()) + return &cachedMessageTable[idx]; + else + return 0; + } + +private: + // Get the json value + const json_spirit::mValue & find_value(json_spirit::mObject & obj, const char * key) + { + std::string newKey = key; + + json_spirit::mObject::const_iterator i = obj.find(newKey); + + if(i != obj.end() && i->first == newKey) + return i->second; + else + return json_spirit::mValue::null; + } + + const std::string get_value(json_spirit::mObject & obj, const char * key) + { + json_spirit::mValue val = find_value(obj, key); + + if(val.is_null()) + return ""; + else + return val.get_str(); + } + + // Determine if it is a special message, i.e.: Invoice, Receipt, etc... + void handleMessageEntry(const MessageTableEntry & message, const bool append) + { + addMessageEntry(message, append); + json_spirit::mValue mVal; + json_spirit::read(message.message.toStdString(), mVal); + + if(mVal.is_null()) + { + addMessageEntry(message, append); + return; + } + + json_spirit::mObject mObj(mVal.get_obj()); + json_spirit::mValue mvType = find_value(mObj, "type"); + + } + + void addMessageEntry(const MessageTableEntry & message, const bool & append) + { + if(append) + { + cachedMessageTable.append(message); + } else + { + int index = qLowerBound(cachedMessageTable.begin(), cachedMessageTable.end(), message.received_datetime, MessageTableEntryLessThan()) - cachedMessageTable.begin(); + parent->beginInsertRows(QModelIndex(), index, index); + cachedMessageTable.insert( + index, + message); + parent->endInsertRows(); + } + } + +}; + +MessageModel::MessageModel(CWallet *wallet, WalletModel *walletModel, QObject *parent) : + QAbstractTableModel(parent), wallet(wallet), walletModel(walletModel), optionsModel(0), priv(0) +{ + columns << tr("Type") << tr("Sent Date Time") << tr("Received Date Time") << tr("Label") << tr("To Address") << tr("From Address") << tr("Message"); + + proxyModel = NULL; + + optionsModel = walletModel->getOptionsModel(); + + priv = new MessageTablePriv(this); + priv->refreshMessageTable(); + + subscribeToCoreSignals(); +} + +MessageModel::~MessageModel() +{ + if (proxyModel) + delete proxyModel; + + delete priv; + unsubscribeFromCoreSignals(); +} + +bool MessageModel::getAddressOrPubkey(QString &address, QString &pubkey) const +{ + CBitcoinAddress addressParsed(address.toStdString()); + + if(addressParsed.IsValid()) { + CKeyID destinationAddress; + CPubKey destinationKey; + + addressParsed.GetKeyID(destinationAddress); + + if (SecureMsgGetStoredKey(destinationAddress, destinationKey) != 0 + && SecureMsgGetLocalKey(destinationAddress, destinationKey) != 0) // test if it's a local key + return false; + + address = destinationAddress.ToString().c_str(); + pubkey = EncodeBase58(destinationKey.Raw()).c_str(); + + return true; + } + + return false; +} + +WalletModel *MessageModel::getWalletModel() +{ + return walletModel; +} + +OptionsModel *MessageModel::getOptionsModel() +{ + return optionsModel; +} + +MessageModel::StatusCode MessageModel::sendMessages(const QList &recipients, const QString &addressFrom) +{ + + QSet setAddress; + + if(recipients.empty()) + return OK; + + // Pre-check input data for validity + foreach(const SendMessagesRecipient &rcp, recipients) + { + if(!walletModel->validateAddress(rcp.address)) + return InvalidAddress; + + if(rcp.message == "") + return MessageCreationFailed; + + std::string sendTo = rcp.address.toStdString(); + std::string pubkey = rcp.pubkey.toStdString(); + std::string message = rcp.message.toStdString(); + std::string addFrom = addressFrom.toStdString(); + + SecureMsgAddAddress(sendTo, pubkey); + setAddress.insert(rcp.address); + + std::string sError; + if (SecureMsgSend(addFrom, sendTo, message, sError) != 0) + { + QMessageBox::warning(NULL, tr("Send Secure Message"), + tr("Send failed: %1.").arg(sError.c_str()), + QMessageBox::Ok, QMessageBox::Ok); + + return FailedErrorShown; + }; + + // Add addresses / update labels that we've sent to to the address book + std::string strAddress = rcp.address.toStdString(); + CTxDestination dest = CBitcoinAddress(strAddress).Get(); + std::string strLabel = rcp.label.toStdString(); + { + LOCK(wallet->cs_wallet); + + std::map::iterator mi = wallet->mapAddressBook.find(dest); + + // Check if we have a new address or an updated label + if (mi == wallet->mapAddressBook.end() || mi->second != strLabel) + { + wallet->SetAddressBookName(dest, strLabel); + } + } + } + + if(recipients.size() > setAddress.size()) + return DuplicateAddress; + + return OK; +} + +MessageModel::StatusCode MessageModel::sendMessages(const QList &recipients) +{ + return sendMessages(recipients, "anon"); +} + +int MessageModel::rowCount(const QModelIndex &parent) const +{ + Q_UNUSED(parent); + return priv->cachedMessageTable.size(); +} + +int MessageModel::columnCount(const QModelIndex &parent) const +{ + Q_UNUSED(parent); + return columns.length(); +} + +QVariant MessageModel::data(const QModelIndex &index, int role) const +{ + if(!index.isValid()) + return QVariant(); + + MessageTableEntry *rec = static_cast(index.internalPointer()); + + switch(role) + { + /* + case Qt::DecorationRole: + switch(index.column()) + { + return txStatusDecoration(rec); + case ToAddress: + return txAddressDecoration(rec); + } + break;*/ + case Qt::DisplayRole: + switch(index.column()) + { + case Label: return (rec->label.isEmpty() ? tr("(no label)") : rec->label); + case ToAddress: return rec->to_address; + case FromAddress: return rec->from_address; + case SentDateTime: return rec->sent_datetime; + case ReceivedDateTime: return rec->received_datetime; + case Message: return rec->message; + case TypeInt: return rec->type; + case HTML: return rec->received_datetime.toString() + "
" + (rec->label.isEmpty() ? rec->from_address : rec->label) + "
" + rec->message; + case Type: + switch(rec->type) + { + case MessageTableEntry::Sent: return Sent; + case MessageTableEntry::Received: return Received; + default: break; + } + case Key: return QVariant::fromValue(rec->chKey); + } + break; + + case KeyRole: return QVariant::fromValue(rec->chKey); + case TypeRole: return rec->type; + case SentDateRole: return rec->sent_datetime; + case ReceivedDateRole: return rec->received_datetime; + case FromAddressRole: return rec->from_address; + case ToAddressRole: return rec->to_address; + case FilterAddressRole: return (rec->type == MessageTableEntry::Sent ? rec->to_address + rec->from_address : rec->from_address + rec->to_address); + case LabelRole: return rec->label; + case MessageRole: return rec->message; + case ShortMessageRole: return rec->message; // TODO: Short message + case HTMLRole: return rec->received_datetime.toString() + "
" + (rec->label.isEmpty() ? rec->from_address : rec->label) + "
" + rec->message; + case Ambiguous: + int it; + + for (it = 0; ittype == MessageTableEntry::Sent ? rec->to_address + rec->from_address : rec->from_address + rec->to_address)) + return false; + } + QString address = (rec->type == MessageTableEntry::Sent ? rec->to_address + rec->from_address : rec->from_address + rec->to_address); + ambiguous.append(address); + + return "true"; + break; + } + + return QVariant(); +} + +QVariant MessageModel::headerData(int section, Qt::Orientation orientation, int role) const +{ + return (orientation == Qt::Horizontal && role == Qt::DisplayRole ? columns[section] : QVariant()); +} + +Qt::ItemFlags MessageModel::flags(const QModelIndex & index) const +{ + if(index.isValid()) + return Qt::ItemIsSelectable | Qt::ItemIsEnabled; + + return 0; +} + +QModelIndex MessageModel::index(int row, int column, const QModelIndex & parent) const +{ + Q_UNUSED(parent); + MessageTableEntry *data = priv->index(row); + return (data ? createIndex(row, column, priv->index(row)) : QModelIndex()); +} + +bool MessageModel::removeRows(int row, int count, const QModelIndex & parent) +{ + MessageTableEntry *rec = priv->index(row); + if(count != 1 || !rec) + // Can only remove one row at a time, and cannot remove rows not in model. + // Also refuse to remove receiving addresses. + return false; + + { + LOCK(cs_smsgDB); + SecMsgDB dbSmsg; + + if (!dbSmsg.Open("cr+")) + //throw runtime_error("Could not open DB."); + return false; + + dbSmsg.EraseSmesg(&rec->chKey[0]); + } + + beginRemoveRows(parent, row, row); + priv->cachedMessageTable.removeAt(row); + endRemoveRows(); + + return true; +} + +void MessageModel::resetFilter() +{ + ambiguous.clear(); +} + +void MessageModel::newMessage(const SecMsgStored &smsg) +{ + priv->newMessage(smsg); +} + + +void MessageModel::newOutboxMessage(const SecMsgStored &smsgOutbox) +{ + priv->newOutboxMessage(smsgOutbox); +} + + +void MessageModel::walletUnlocked() +{ + priv->walletUnlocked(); +} + +void MessageModel::setEncryptionStatus(int status) +{ + priv->setEncryptionStatus(status); +} + + +static void NotifySecMsgInbox(MessageModel *messageModel, SecMsgStored inboxHdr) +{ + // Too noisy: OutputDebugStringF("NotifySecMsgInboxChanged %s\n", message); + QMetaObject::invokeMethod(messageModel, "newMessage", Qt::QueuedConnection, + Q_ARG(SecMsgStored, inboxHdr)); +} + +static void NotifySecMsgOutbox(MessageModel *messageModel, SecMsgStored outboxHdr) +{ + QMetaObject::invokeMethod(messageModel, "newOutboxMessage", Qt::QueuedConnection, + Q_ARG(SecMsgStored, outboxHdr)); +} + +static void NotifySecMsgWallet(MessageModel *messageModel) +{ + QMetaObject::invokeMethod(messageModel, "walletUnlocked", Qt::QueuedConnection); +} + +void MessageModel::subscribeToCoreSignals() +{ + qRegisterMetaType("SecMsgStored"); + + // Connect signals + NotifySecMsgInboxChanged.connect(boost::bind(NotifySecMsgInbox, this, _1)); + NotifySecMsgOutboxChanged.connect(boost::bind(NotifySecMsgOutbox, this, _1)); + NotifySecMsgWalletUnlocked.connect(boost::bind(NotifySecMsgWallet, this)); + + connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int))); +} + +void MessageModel::unsubscribeFromCoreSignals() +{ + // Disconnect signals + NotifySecMsgInboxChanged.disconnect(boost::bind(NotifySecMsgInbox, this, _1)); + NotifySecMsgOutboxChanged.disconnect(boost::bind(NotifySecMsgOutbox, this, _1)); + NotifySecMsgWalletUnlocked.disconnect(boost::bind(NotifySecMsgWallet, this)); + + disconnect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int))); +} diff --git a/src/qt/messagemodel.h b/src/qt/messagemodel.h new file mode 100644 index 0000000..2106162 --- /dev/null +++ b/src/qt/messagemodel.h @@ -0,0 +1,195 @@ +#ifndef MESSAGEMODEL_H +#define MESSAGEMODEL_H + +#include "uint256.h" + +#include +#include "allocators.h" /* for SecureString */ +#include "smessage.h" +#include +#include +#include +#include +#include + + +class MessageTablePriv; +class InvoiceTableModel; +class InvoiceItemTableModel; +class ReceiptTableModel; +class CWallet; +class WalletModel; +class OptionsModel; + +class SendMessagesRecipient +{ +public: + QString address; + QString label; + QString pubkey; + QString message; +}; + +struct MessageTableEntry +{ + enum Type { + Sent, + Received + }; + + std::vector chKey; + Type type; + QString label; + QString to_address; + QString from_address; + QDateTime sent_datetime; + QDateTime received_datetime; + QString message; + + MessageTableEntry() {} + MessageTableEntry(std::vector &chKey, + Type type, + const QString &label, + const QString &to_address, + const QString &from_address, + const QDateTime &sent_datetime, + const QDateTime &received_datetime, + const QString &message): + chKey(chKey), + type(type), + label(label), + to_address(to_address), + from_address(from_address), + sent_datetime(sent_datetime), + received_datetime(received_datetime), + message(message) + { + } +}; + +/** Interface to Genius Secure Messaging from Qt view code. */ +class MessageModel : public QAbstractTableModel +{ + Q_OBJECT + +public: + explicit MessageModel(CWallet *wallet, WalletModel *walletModel, QObject *parent = 0); + ~MessageModel(); + + enum StatusCode // Returned by sendMessages + { + OK, + InvalidAddress, + InvalidMessage, + DuplicateAddress, + MessageCreationFailed, // Error returned when DB is still locked + MessageCommitFailed, + Aborted, + FailedErrorShown + }; + + enum ColumnIndex { + Type = 0, /**< Sent/Received */ + SentDateTime = 1, /**< Time Sent */ + ReceivedDateTime = 2, /**< Time Received */ + Label = 3, /**< User specified label */ + ToAddress = 4, /**< To Bitcoin address */ + FromAddress = 5, /**< From Bitcoin address */ + Message = 6, /**< Plaintext */ + TypeInt = 7, /**< Plaintext */ + Key = 8, /**< chKey */ + HTML = 9, /**< HTML Formatted Data */ + }; + + /** Roles to get specific information from a message row. + These are independent of column. + */ + enum RoleIndex { + /** Type of message */ + TypeRole = Qt::UserRole, + /** Date and time this message was sent */ + /** message key */ + KeyRole, + SentDateRole, + /** Date and time this message was received */ + ReceivedDateRole, + /** From Address of message */ + FromAddressRole, + /** To Address of message */ + ToAddressRole, + /** Filter address related to message */ + FilterAddressRole, + /** Label of address related to message */ + LabelRole, + /** Full Message */ + MessageRole, + /** Short Message */ + ShortMessageRole, + /** HTML Formatted */ + HTMLRole, + /** Ambiguous bool */ + Ambiguous + }; + + static const QString Sent; /**< Specifies sent message */ + static const QString Received; /**< Specifies sent message */ + + //QList ambiguous; /**< Specifies Ambiguous addresses */ + + /** @name Methods overridden from QAbstractTableModel + @{*/ + int rowCount(const QModelIndex &parent) const; + int columnCount(const QModelIndex &parent) const; + QVariant data(const QModelIndex &index, int role) const; + QVariant headerData(int section, Qt::Orientation orientation, int role) const; + QModelIndex index(int row, int column, const QModelIndex & parent) const; + bool removeRows(int row, int count, const QModelIndex & parent = QModelIndex()); + Qt::ItemFlags flags(const QModelIndex & index) const; + /*@}*/ + + /* Look up row index of a message in the model. + Return -1 if not found. + */ + int lookupMessage(const QString &message) const; + + WalletModel *getWalletModel(); + OptionsModel *getOptionsModel(); + + void resetFilter(); + + bool getAddressOrPubkey( QString &Address, QString &Pubkey) const; + + // Send messages to a list of recipients + StatusCode sendMessages(const QList &recipients); + StatusCode sendMessages(const QList &recipients, const QString &addressFrom); + + QSortFilterProxyModel *proxyModel; + +private: + CWallet *wallet; + WalletModel *walletModel; + OptionsModel *optionsModel; + MessageTablePriv *priv; + QStringList columns; + + void subscribeToCoreSignals(); + void unsubscribeFromCoreSignals(); + +public slots: + + /* Check for new messages */ + void newMessage(const SecMsgStored& smsg); + void newOutboxMessage(const SecMsgStored& smsg); + + void walletUnlocked(); + + void setEncryptionStatus(int status); + + friend class MessageTablePriv; + +signals: + // Asynchronous error notification + void error(const QString &title, const QString &message, bool modal); +}; + +#endif // MESSAGEMODEL_H diff --git a/src/qt/messagepage.cpp b/src/qt/messagepage.cpp new file mode 100644 index 0000000..261c75b --- /dev/null +++ b/src/qt/messagepage.cpp @@ -0,0 +1,429 @@ +#include "messagepage.h" +#include "ui_messagepage.h" + +#include "sendmessagesdialog.h" +#include "mrichtextedit.h" +#include "messagemodel.h" +#include "bitcoingui.h" +#include "csvmodelwriter.h" +#include "guiutil.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#define DECORATION_SIZE 64 +#define NUM_ITEMS 3 + +class MessageViewDelegate : public QStyledItemDelegate +{ +protected: + void paint ( QPainter * painter, const QStyleOptionViewItem & option, const QModelIndex & index ) const; + QSize sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const; +}; + +void MessageViewDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const +{ + QStyleOptionViewItemV4 optionV4 = option; + initStyleOption(&optionV4, index); + + QStyle *style = optionV4.widget? optionV4.widget->style() : QApplication::style(); + + QTextDocument doc; + QString align(index.data(MessageModel::TypeRole) == 1 ? "left" : "right"); + QString html = "

" + index.data(MessageModel::HTMLRole).toString() + "

"; + doc.setHtml(html); + + /// Painting item without text + optionV4.text = QString(); + style->drawControl(QStyle::CE_ItemViewItem, &optionV4, painter); + + QAbstractTextDocumentLayout::PaintContext ctx; + + // Highlighting text if item is selected + if (optionV4.state & QStyle::State_Selected) + ctx.palette.setColor(QPalette::Text, optionV4.palette.color(QPalette::Active, QPalette::HighlightedText)); + + QRect textRect = style->subElementRect(QStyle::SE_ItemViewItemText, &optionV4); + doc.setTextWidth( textRect.width() ); + painter->save(); + painter->translate(textRect.topLeft()); + painter->setClipRect(textRect.translated(-textRect.topLeft())); + doc.documentLayout()->draw(painter, ctx); + painter->restore(); +} + +QSize MessageViewDelegate::sizeHint ( const QStyleOptionViewItem & option, const QModelIndex & index ) const +{ + QStyleOptionViewItemV4 options = option; + initStyleOption(&options, index); + + QTextDocument doc; + doc.setHtml(index.data(MessageModel::HTMLRole).toString()); + doc.setTextWidth(options.rect.width()); + return QSize(doc.idealWidth(), doc.size().height() + 20); +} + + +MessagePage::MessagePage(QWidget *parent) : + QWidget(parent), + ui(new Ui::MessagePage), + model(0), + msgdelegate(new MessageViewDelegate()), + messageTextEdit(new MRichTextEdit()) +{ + ui->setupUi(this); + + +#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac + ui->deleteButton->setIcon(QIcon()); +#endif + // Context menu actions + replyAction = new QAction(ui->sendButton->text(), this); + copyFromAddressAction = new QAction(ui->copyFromAddressButton->text(), this); + copyToAddressAction = new QAction(ui->copyToAddressButton->text(), this); + deleteAction = new QAction(ui->deleteButton->text(), this); + + // Build context menu + contextMenu = new QMenu(); + + contextMenu->addAction(replyAction); + contextMenu->addAction(copyFromAddressAction); + contextMenu->addAction(copyToAddressAction); + contextMenu->addAction(deleteAction); + + connect(replyAction, SIGNAL(triggered()), this, SLOT(on_sendButton_clicked())); + connect(copyFromAddressAction, SIGNAL(triggered()), this, SLOT(on_copyFromAddressButton_clicked())); + connect(copyToAddressAction, SIGNAL(triggered()), this, SLOT(on_copyToAddressButton_clicked())); + connect(deleteAction, SIGNAL(triggered()), this, SLOT(on_deleteButton_clicked())); + + connect(ui->tableView, SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(contextualMenu(QPoint))); + + // Show Messages + ui->listConversation->setItemDelegate(msgdelegate); + ui->listConversation->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); + ui->listConversation->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); + ui->listConversation->setAttribute(Qt::WA_MacShowFocusRect, false); +} + +MessagePage::~MessagePage() +{ + delete ui; +} + +void MessagePage::setModel(MessageModel *model) +{ + this->model = model; + if(!model) + return; + + //if (model->proxyModel) + // delete model->proxyModel; + model->proxyModel = new QSortFilterProxyModel(this); + model->proxyModel->setSourceModel(model); + model->proxyModel->setDynamicSortFilter(true); + model->proxyModel->setSortCaseSensitivity(Qt::CaseInsensitive); + model->proxyModel->setFilterCaseSensitivity(Qt::CaseInsensitive); + model->proxyModel->sort(MessageModel::ReceivedDateTime); + model->proxyModel->setFilterRole(MessageModel::Ambiguous); + model->proxyModel->setFilterFixedString("true"); + + ui->tableView->setModel(model->proxyModel); + ui->tableView->sortByColumn(MessageModel::ReceivedDateTime, Qt::DescendingOrder); + + ui->listConversation->setModel(model->proxyModel); + ui->listConversation->setModelColumn(MessageModel::HTML); + + // Set column widths + ui->tableView->horizontalHeader()->resizeSection(MessageModel::Type, 100); + ui->tableView->horizontalHeader()->resizeSection(MessageModel::Label, 100); + ui->tableView->horizontalHeader()->setResizeMode(MessageModel::Label, QHeaderView::Stretch); + ui->tableView->horizontalHeader()->resizeSection(MessageModel::FromAddress, 320); + ui->tableView->horizontalHeader()->resizeSection(MessageModel::ToAddress, 320); + ui->tableView->horizontalHeader()->resizeSection(MessageModel::SentDateTime, 170); + ui->tableView->horizontalHeader()->resizeSection(MessageModel::ReceivedDateTime, 170); + + //ui->messageEdit->setMinimumHeight(100); + + // Hidden columns + ui->tableView->setColumnHidden(MessageModel::Message, true); + + connect(ui->tableView->selectionModel(), SIGNAL(selectionChanged(QItemSelection, QItemSelection)), this, SLOT(selectionChanged())); + connect(ui->tableView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(selectionChanged())); + connect(ui->listConversation->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(itemSelectionChanged())); + connect(ui->listConversation, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(itemSelectionChanged())); + //connect(ui->messageEdit, SIGNAL(textChanged()), this, SLOT(messageTextChanged())); + + // Scroll to bottom + connect(model, SIGNAL(rowsInserted(QModelIndex,int,int)), this, SLOT(incomingMessage())); + + selectionChanged(); +} + +void MessagePage::on_sendButton_clicked() +{ + if(!model) + return; + + std::string sError; + std::string sendTo = replyToAddress.toStdString(); + std::string message = ui->messageEdit->toHtml().toStdString(); + std::string addFrom = replyFromAddress.toStdString(); + + if (SecureMsgSend(addFrom, sendTo, message, sError) != 0) + { + QMessageBox::warning(NULL, tr("Send Secure Message"), + tr("Send failed: %1.").arg(sError.c_str()), + QMessageBox::Ok, QMessageBox::Ok); + + return; + }; + + //ui->messageEdit->setMaximumHeight(30); + ui->messageEdit->clear(); + ui->listConversation->scrollToBottom(); +} + +void MessagePage::on_newButton_clicked() +{ + if(!model) + return; + + SendMessagesDialog dlg(SendMessagesDialog::Encrypted, SendMessagesDialog::Dialog, this); + + dlg.setModel(model); + dlg.exec(); +} + +void MessagePage::on_copyFromAddressButton_clicked() +{ + GUIUtil::copyEntryData(ui->tableView, MessageModel::FromAddress, Qt::DisplayRole); +} + +void MessagePage::on_copyToAddressButton_clicked() +{ + GUIUtil::copyEntryData(ui->tableView, MessageModel::ToAddress, Qt::DisplayRole); +} + +void MessagePage::on_deleteButton_clicked() +{ + QListView *list = ui->listConversation; + + if(!list->selectionModel()) + return; + + QModelIndexList indexes = list->selectionModel()->selectedIndexes(); + + if(!indexes.isEmpty()) + { + list->model()->removeRow(indexes.at(0).row()); + indexes = list->selectionModel()->selectedIndexes(); + + if(indexes.isEmpty()) + on_backButton_clicked(); + } +} + +void MessagePage::on_backButton_clicked() +{ + model->proxyModel->setFilterRole(false); + model->proxyModel->setFilterFixedString(""); + model->resetFilter(); + model->proxyModel->setFilterRole(MessageModel::Ambiguous); + model->proxyModel->setFilterFixedString("true"); + + ui->tableView->clearSelection(); + ui->listConversation->clearSelection(); + itemSelectionChanged(); + selectionChanged(); + + ui->messageDetails->hide(); + ui->tableView->show(); + ui->newButton->setEnabled(true); + ui->newButton->setVisible(true); + ui->sendButton->setEnabled(false); + ui->sendButton->setVisible(false); + ui->messageEdit->setVisible(false); +} + +void MessagePage::selectionChanged() +{ + // Set button states based on selected tab and selection + QTableView *table = ui->tableView; + if(!table->selectionModel()) + return; + + if(table->selectionModel()->hasSelection()) + { + replyAction->setEnabled(true); + copyFromAddressAction->setEnabled(true); + copyToAddressAction->setEnabled(true); + deleteAction->setEnabled(true); + + ui->copyFromAddressButton->setEnabled(true); + ui->copyToAddressButton->setEnabled(true); + ui->deleteButton->setEnabled(true); + + ui->newButton->setEnabled(false); + ui->newButton->setVisible(false); + ui->sendButton->setEnabled(true); + ui->sendButton->setVisible(true); + ui->messageEdit->setVisible(true); + + ui->tableView->hide(); + + // Figure out which message was selected + QModelIndexList labelColumn = table->selectionModel()->selectedRows(MessageModel::Label); + QModelIndexList addressFromColumn = table->selectionModel()->selectedRows(MessageModel::FromAddress); + QModelIndexList addressToColumn = table->selectionModel()->selectedRows(MessageModel::ToAddress); + QModelIndexList typeColumn = table->selectionModel()->selectedRows(MessageModel::Type); + + int type; + + foreach (QModelIndex index, typeColumn) + type = (table->model()->data(index).toString() == MessageModel::Sent ? MessageTableEntry::Sent : MessageTableEntry::Received); + + foreach (QModelIndex index, labelColumn) + ui->contactLabel->setText(table->model()->data(index).toString()); + + foreach (QModelIndex index, addressFromColumn) + if(type == MessageTableEntry::Sent) + replyFromAddress = table->model()->data(index).toString(); + else + replyToAddress = table->model()->data(index).toString(); + + foreach (QModelIndex index, addressToColumn) + if(type == MessageTableEntry::Sent) + replyToAddress = table->model()->data(index).toString(); + else + replyFromAddress = table->model()->data(index).toString(); + + QString filter = (type == MessageTableEntry::Sent ? replyToAddress + replyFromAddress : replyToAddress + replyFromAddress); + + model->proxyModel->setFilterRole(false); + model->proxyModel->setFilterFixedString(""); + model->proxyModel->sort(MessageModel::ReceivedDateTime); + model->proxyModel->setFilterRole(MessageModel::FilterAddressRole); + model->proxyModel->setFilterFixedString(filter); + ui->messageDetails->show(); + ui->listConversation->setCurrentIndex(model->proxyModel->index(0, 0, QModelIndex())); + } + else + { + ui->newButton->setEnabled(true); + ui->newButton->setVisible(true); + ui->sendButton->setEnabled(false); + ui->sendButton->setVisible(false); + ui->copyFromAddressButton->setEnabled(false); + ui->copyToAddressButton->setEnabled(false); + ui->deleteButton->setEnabled(false); + ui->messageEdit->hide(); + ui->messageDetails->hide(); + ui->messageEdit->clear(); + } +} + +void MessagePage::itemSelectionChanged() +{ + // Set button states based on selected tab and selection + QListView *list = ui->listConversation; + if(!list->selectionModel()) + return; + + if(list->selectionModel()->hasSelection()) + { + replyAction->setEnabled(true); + copyFromAddressAction->setEnabled(true); + copyToAddressAction->setEnabled(true); + deleteAction->setEnabled(true); + + ui->copyFromAddressButton->setEnabled(true); + ui->copyToAddressButton->setEnabled(true); + ui->deleteButton->setEnabled(true); + + ui->newButton->setEnabled(false); + ui->newButton->setVisible(false); + ui->sendButton->setEnabled(true); + ui->sendButton->setVisible(true); + ui->messageEdit->setVisible(true); + + ui->tableView->hide(); + + } + else + { + ui->newButton->setEnabled(true); + ui->newButton->setVisible(true); + ui->sendButton->setEnabled(false); + ui->sendButton->setVisible(false); + ui->copyFromAddressButton->setEnabled(false); + ui->copyToAddressButton->setEnabled(false); + ui->deleteButton->setEnabled(false); + ui->messageEdit->hide(); + ui->messageDetails->hide(); + ui->messageEdit->clear(); + } +} + +void MessagePage::incomingMessage() +{ + ui->listConversation->scrollToBottom(); +} + +void MessagePage::messageTextChanged() +{ + /* + if(ui->messageEdit->toPlainText().endsWith("\n")) + { + ui->messageEdit->setMaximumHeight(80); + ui->messageEdit->resize(256, ui->messageEdit->document()->size().height() + 10); + }*/ + +} + +void MessagePage::exportClicked() +{ + // CSV is currently the only supported format + QString filename = GUIUtil::getSaveFileName( + this, + tr("Export Messages"), QString(), + tr("Comma separated file (*.csv)")); + + if (filename.isNull()) return; + + CSVModelWriter writer(filename); + + // name, column, role + writer.setModel(model->proxyModel); + writer.addColumn("Type", MessageModel::Type, Qt::DisplayRole); + writer.addColumn("Label", MessageModel::Label, Qt::DisplayRole); + writer.addColumn("FromAddress", MessageModel::FromAddress, Qt::DisplayRole); + writer.addColumn("ToAddress", MessageModel::ToAddress, Qt::DisplayRole); + writer.addColumn("SentDateTime", MessageModel::SentDateTime, Qt::DisplayRole); + writer.addColumn("ReceivedDateTime", MessageModel::ReceivedDateTime, Qt::DisplayRole); + writer.addColumn("Message", MessageModel::Message, Qt::DisplayRole); + + if(!writer.write()) + { + QMessageBox::critical(this, tr("Error exporting"), tr("Could not write to file %1.").arg(filename), + QMessageBox::Abort, QMessageBox::Abort); + } +} + + +void MessagePage::contextualMenu(const QPoint &point) +{ + QModelIndex index = ui->tableView->indexAt(point); + if(index.isValid()) + { + contextMenu->exec(QCursor::pos()); + } +} + diff --git a/src/qt/messagepage.h b/src/qt/messagepage.h new file mode 100644 index 0000000..f58c1dd --- /dev/null +++ b/src/qt/messagepage.h @@ -0,0 +1,73 @@ +#ifndef MESSAGEPAGE_H +#define MESSAGEPAGE_H + +#include + +namespace Ui { + class MessagePage; +} +class MessageModel; +//class OptionsModel; + +QT_BEGIN_NAMESPACE +class QTableView; +class QItemSelection; +class QSortFilterProxyModel; +class QMenu; +class QModelIndex; +class MessageViewDelegate; +class MRichTextEdit; +QT_END_NAMESPACE + + +/** Widget that shows a list of sending or receiving addresses. + */ +class MessagePage : public QWidget +{ + Q_OBJECT + +public: + + explicit MessagePage(QWidget *parent = 0); + ~MessagePage(); + + void setModel(MessageModel *model); + +private: + void setupTextActions(); + +public slots: + void exportClicked(); + +private: + Ui::MessagePage *ui; + MessageModel *model; + + QMenu *contextMenu; + QAction *replyAction; + QAction *copyFromAddressAction; + QAction *copyToAddressAction; + QAction *deleteAction; + QString replyFromAddress; + QString replyToAddress; + MessageViewDelegate *msgdelegate; + MRichTextEdit *messageTextEdit; + +private slots: + void on_sendButton_clicked(); + void on_newButton_clicked(); + void on_copyFromAddressButton_clicked(); + void on_copyToAddressButton_clicked(); + void on_deleteButton_clicked(); + void on_backButton_clicked(); + void messageTextChanged(); + void selectionChanged(); + void itemSelectionChanged(); + void incomingMessage(); + /** Spawn contextual menu (right mouse menu) for address book entry */ + void contextualMenu(const QPoint &point); + +signals: +}; + +#endif // MESSAGEPAGE_H diff --git a/src/qt/optionsmodel.cpp b/src/qt/optionsmodel.cpp index 561d00a..a2be4c2 100644 --- a/src/qt/optionsmodel.cpp +++ b/src/qt/optionsmodel.cpp @@ -48,6 +48,15 @@ void OptionsModel::Init() language = settings.value("language", "").toString(); fUseBlackTheme = settings.value("fUseBlackTheme", false).toBool(); + if (!settings.contains("nDarksendRounds")) + settings.setValue("nDarksendRounds", 2); + + if (!settings.contains("nAnonymizeGeniusAmount")) + settings.setValue("nAnonymizeGeniusAmount", 1000); + + nDarksendRounds = settings.value("nDarksendRounds").toLongLong(); + nAnonymizeGeniusAmount = settings.value("nAnonymizeGeniusAmount").toLongLong(); + // These are shared with core Bitcoin; we want // command-line options to override the GUI settings: if (settings.contains("fUseUPnP")) @@ -58,6 +67,11 @@ void OptionsModel::Init() SoftSetBoolArg("-minimizecoinage", settings.value("fMinimizeCoinAge").toBool()); if (!language.isEmpty()) SoftSetArg("-lang", language.toStdString()); + + if (settings.contains("nDarksendRounds")) + SoftSetArg("-darksendrounds", settings.value("nDarksendRounds").toString().toStdString()); + if (settings.contains("nAnonymizeGeniusAmount")) + SoftSetArg("-anonymizegeniusamount", settings.value("nAnonymizeGeniusAmount").toString().toStdString()); } int OptionsModel::rowCount(const QModelIndex & parent) const @@ -197,6 +211,16 @@ bool OptionsModel::setData(const QModelIndex & index, const QVariant & value, in fUseBlackTheme = value.toBool(); settings.setValue("fUseBlackTheme", fUseBlackTheme); break; + case DarksendRounds: + nDarksendRounds = value.toInt(); + settings.setValue("nDarksendRounds", nDarksendRounds); + emit darksendRoundsChanged(nDarksendRounds); + break; + case anonymizeGeniusAmount: + nAnonymizeGeniusAmount = value.toInt(); + settings.setValue("nAnonymizeGeniusAmount", nAnonymizeGeniusAmount); + emit anonymizeGeniusAmountChanged(nAnonymizeGeniusAmount); + break; default: break; } diff --git a/src/qt/optionsmodel.h b/src/qt/optionsmodel.h index f9db785..cb3c1bf 100644 --- a/src/qt/optionsmodel.h +++ b/src/qt/optionsmodel.h @@ -33,6 +33,8 @@ class OptionsModel : public QAbstractListModel CoinControlFeatures, // bool MinimizeCoinAge, // bool UseBlackTheme, // bool + DarksendRounds, // int + anonymizeGeniusAmount, //int OptionIDRowCount, }; @@ -63,6 +65,8 @@ class OptionsModel : public QAbstractListModel void transactionFeeChanged(qint64); void reserveBalanceChanged(qint64); void coinControlFeaturesChanged(bool); + void darksendRoundsChanged(int); + void anonymizeGeniusAmountChanged(int); }; #endif // OPTIONSMODEL_H diff --git a/src/qt/overviewpage.cpp b/src/qt/overviewpage.cpp index b44821b..a490c92 100644 --- a/src/qt/overviewpage.cpp +++ b/src/qt/overviewpage.cpp @@ -2,6 +2,8 @@ #include "ui_overviewpage.h" #include "clientmodel.h" +#include "darksend.h" +#include "darksendconfig.h" #include "walletmodel.h" #include "bitcoinunits.h" #include "optionsmodel.h" @@ -12,6 +14,10 @@ #include #include +#include +#include +#include +#include #define DECORATION_SIZE 64 #define NUM_ITEMS 6 @@ -104,11 +110,22 @@ OverviewPage::OverviewPage(QWidget *parent) : { ui->setupUi(this); + ui->frameDarksend->setVisible(false); // Hide darksend features + + QScroller::grabGesture(ui->scrollArea, QScroller::LeftMouseButtonGesture); + ui->scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + ui->scrollArea->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + + ui->columnTwoWidget->setContentsMargins(0,0,0,0); + ui->columnTwoWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); + ui->columnTwoWidget->setMinimumWidth(300); + // Recent transactions ui->listTransactions->setItemDelegate(txdelegate); ui->listTransactions->setIconSize(QSize(DECORATION_SIZE, DECORATION_SIZE)); ui->listTransactions->setMinimumHeight(NUM_ITEMS * (DECORATION_SIZE + 2)); ui->listTransactions->setAttribute(Qt::WA_MacShowFocusRect, false); + ui->listTransactions->setMinimumWidth(350); connect(ui->listTransactions, SIGNAL(clicked(QModelIndex)), this, SLOT(handleTransactionClicked(QModelIndex))); @@ -116,6 +133,29 @@ OverviewPage::OverviewPage(QWidget *parent) : ui->labelWalletStatus->setText("(" + tr("out of sync") + ")"); ui->labelTransactionsStatus->setText("(" + tr("out of sync") + ")"); + showingDarkSendMessage = 0; + darksendActionCheck = 0; + lastNewBlock = 0; + + if(fLiteMode){ + ui->frameDarksend->setVisible(false); + } else { + qDebug() << "Dark Send Status Timer"; + timer = new QTimer(this); + connect(timer, SIGNAL(timeout()), this, SLOT(darkSendStatus())); + if(!GetBoolArg("-reindexaddr", false)) + timer->start(60000); + } + + if(fMasterNode || fLiteMode){ + ui->toggleDarksend->setText("(" + tr("Disabled") + ")"); + ui->toggleDarksend->setEnabled(false); + }else if(!fEnableDarksend){ + ui->toggleDarksend->setText(tr("Start Darksend")); + } else { + ui->toggleDarksend->setText(tr("Stop Darksend")); + } + // start with displaying the "out of sync" warnings showOutOfSyncWarning(true); @@ -141,24 +181,31 @@ OverviewPage::~OverviewPage() delete ui; } -void OverviewPage::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) +void OverviewPage::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance, qint64 anonymizedBalance) { int unit = walletModel->getOptionsModel()->getDisplayUnit(); currentBalance = balance; currentStake = stake; currentUnconfirmedBalance = unconfirmedBalance; currentImmatureBalance = immatureBalance; + currentAnonymizedBalance = anonymizedBalance; ui->labelBalance->setText(BitcoinUnits::formatWithUnit(unit, balance)); ui->labelStake->setText(BitcoinUnits::formatWithUnit(unit, stake)); ui->labelUnconfirmed->setText(BitcoinUnits::formatWithUnit(unit, unconfirmedBalance)); ui->labelImmature->setText(BitcoinUnits::formatWithUnit(unit, immatureBalance)); ui->labelTotal->setText(BitcoinUnits::formatWithUnit(unit, balance + stake + unconfirmedBalance + immatureBalance)); + ui->labelAnonymized->setText(BitcoinUnits::formatWithUnit(unit, anonymizedBalance)); // only show immature (newly mined) balance if it's non-zero, so as not to complicate things // for the non-mining users bool showImmature = immatureBalance != 0; ui->labelImmature->setVisible(showImmature); ui->labelImmatureText->setVisible(showImmature); + + if(cachedTxLocks != nCompleteTXLocks){ + cachedTxLocks = nCompleteTXLocks; + ui->listTransactions->update(); + } } void OverviewPage::setClientModel(ClientModel *model) @@ -190,10 +237,14 @@ void OverviewPage::setWalletModel(WalletModel *model) ui->listTransactions->setModelColumn(TransactionTableModel::ToAddress); // Keep up to date with wallet - setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); - connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64))); + setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getAnonymizedBalance()); + connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); + + connect(ui->darksendAuto, SIGNAL(clicked()), this, SLOT(darksendAuto())); + connect(ui->darksendReset, SIGNAL(clicked()), this, SLOT(darksendReset())); + connect(ui->toggleDarksend, SIGNAL(clicked()), this, SLOT(toggleDarksend())); } // update the display unit, to not use the default ("BTC") @@ -205,7 +256,7 @@ void OverviewPage::updateDisplayUnit() if(walletModel && walletModel->getOptionsModel()) { if(currentBalance != -1) - setBalance(currentBalance, walletModel->getStake(), currentUnconfirmedBalance, currentImmatureBalance); + setBalance(currentBalance, walletModel->getStake(), currentUnconfirmedBalance, currentImmatureBalance, currentAnonymizedBalance); // Update txdelegate->unit with the current unit txdelegate->unit = walletModel->getOptionsModel()->getDisplayUnit(); @@ -225,3 +276,254 @@ void OverviewPage::showOutOfSyncWarning(bool fShow) ui->labelWalletStatus->setVisible(fShow); ui->labelTransactionsStatus->setVisible(fShow); } + + + +void OverviewPage::updateDarksendProgress() +{ + qDebug() << "updateDarksendProgress()"; + if(IsInitialBlockDownload()) return; + + qDebug() << "updateDarksendProgress() getbalance"; + int64_t nBalance = pwalletMain->GetBalance(); + if(nBalance == 0) + { + ui->darksendProgress->setValue(0); + QString s(tr("No inputs detected")); + ui->darksendProgress->setToolTip(s); + return; + } + + //get denominated unconfirmed inputs + if(pwalletMain->GetDenominatedBalance(true, true) > 0) + { + QString s(tr("Found unconfirmed denominated outputs, will wait till they confirm to recalculate.")); + ui->darksendProgress->setToolTip(s); + return; + } + + //Get the anon threshold + int64_t nMaxToAnonymize = nAnonymizeGeniusAmount*COIN; + + // If it's more than the wallet amount, limit to that. + if(nMaxToAnonymize > nBalance) nMaxToAnonymize = nBalance; + + if(nMaxToAnonymize == 0) return; + + // calculate parts of the progress, each of them shouldn't be higher than 1: + // mixing progress of denominated balance + int64_t denominatedBalance = pwalletMain->GetDenominatedBalance(); + float denomPart = 0; + if(denominatedBalance > 0) + { + denomPart = (float)pwalletMain->GetNormalizedAnonymizedBalance() / pwalletMain->GetDenominatedBalance(); + denomPart = denomPart > 1 ? 1 : denomPart; + } + + // % of fully anonymized balance + float anonPart = 0; + if(nMaxToAnonymize > 0) + { + anonPart = (float)pwalletMain->GetAnonymizedBalance() / nMaxToAnonymize; + // if anonPart is > 1 then we are done, make denomPart equal 1 too + anonPart = anonPart > 1 ? (denomPart = 1, 1) : anonPart; + } + + // apply some weights to them (sum should be <=100) and calculate the whole progress + int progress = 80 * denomPart + 20 * anonPart; + if(progress > 100) progress = 100; + + ui->darksendProgress->setValue(progress); + + std::ostringstream convert; + convert << "Progress: " << progress << "%, inputs have an average of " << pwalletMain->GetAverageAnonymizedRounds() << " of " << nDarksendRounds << " rounds"; + QString s(convert.str().c_str()); + ui->darksendProgress->setToolTip(s); +} + + +void OverviewPage::darkSendStatus() +{ + int nBestHeight = pindexBest->nHeight; + + if(nBestHeight != darkSendPool.cachedNumBlocks) + { + //we we're processing lots of blocks, we'll just leave + if(GetTime() - lastNewBlock < 10) return; + lastNewBlock = GetTime(); + + updateDarksendProgress(); + + QString strSettings(" " + tr("Rounds")); + strSettings.prepend(QString::number(nDarksendRounds)).prepend(" / "); + strSettings.prepend(BitcoinUnits::formatWithUnit( + walletModel->getOptionsModel()->getDisplayUnit(), + nAnonymizeGeniusAmount * COIN) + ); + + ui->labelAmountRounds->setText(strSettings); + } + + if(!fEnableDarksend) { + if(nBestHeight != darkSendPool.cachedNumBlocks) + { + darkSendPool.cachedNumBlocks = nBestHeight; + + ui->darksendEnabled->setText(tr("Disabled")); + ui->darksendStatus->setText(""); + ui->toggleDarksend->setText(tr("Start Darksend")); + } + + return; + } + + // check darksend status and unlock if needed + if(nBestHeight != darkSendPool.cachedNumBlocks) + { + // Balance and number of transactions might have changed + darkSendPool.cachedNumBlocks = nBestHeight; + + /* *******************************************************/ + + ui->darksendEnabled->setText(tr("Enabled")); + } + + int state = darkSendPool.GetState(); + int entries = darkSendPool.GetEntriesCount(); + int accepted = darkSendPool.GetLastEntryAccepted(); + + /* ** @TODO this string creation really needs some clean ups ---vertoe ** */ + std::ostringstream convert; + + if(state == POOL_STATUS_ACCEPTING_ENTRIES) { + if(entries == 0) { + if(darkSendPool.strAutoDenomResult.size() == 0){ + convert << tr("Darksend is idle.").toStdString(); + } else { + convert << darkSendPool.strAutoDenomResult; + } + showingDarkSendMessage = 0; + } else if (accepted == 1) { + convert << tr("Darksend request complete: Your transaction was accepted into the pool!").toStdString(); + if(showingDarkSendMessage % 10 > 8) { + darkSendPool.lastEntryAccepted = 0; + showingDarkSendMessage = 0; + } + } else { + if(showingDarkSendMessage % 70 <= 40) convert << tr("Submitted following entries to masternode:").toStdString() << " " << entries << "/" << darkSendPool.GetMaxPoolTransactions(); + else if(showingDarkSendMessage % 70 <= 50) convert << tr("Submitted to masternode, Waiting for more entries").toStdString() << " (" << entries << "/" << darkSendPool.GetMaxPoolTransactions() << " ) ."; + else if(showingDarkSendMessage % 70 <= 60) convert << tr("Submitted to masternode, Waiting for more entries").toStdString() << " (" << entries << "/" << darkSendPool.GetMaxPoolTransactions() << " ) .."; + else if(showingDarkSendMessage % 70 <= 70) convert << tr("Submitted to masternode, Waiting for more entries").toStdString() << " (" << entries << "/" << darkSendPool.GetMaxPoolTransactions() << " ) ..."; + } + } else if(state == POOL_STATUS_SIGNING) { + if(showingDarkSendMessage % 70 <= 10) convert << tr("Found enough users, signing ...").toStdString(); + else if(showingDarkSendMessage % 70 <= 20) convert << tr("Found enough users, signing ( waiting. )").toStdString(); + else if(showingDarkSendMessage % 70 <= 30) convert << tr("Found enough users, signing ( waiting.. )").toStdString(); + else if(showingDarkSendMessage % 70 <= 40) convert << tr("Found enough users, signing ( waiting... )").toStdString(); + } else if(state == POOL_STATUS_TRANSMISSION) { + convert << tr("Transmitting final transaction.").toStdString(); + } else if (state == POOL_STATUS_IDLE) { + convert << tr("Darksend is idle.").toStdString(); + } else if (state == POOL_STATUS_FINALIZE_TRANSACTION) { + convert << tr("Finalizing transaction.").toStdString(); + } else if(state == POOL_STATUS_ERROR) { + convert << tr("Darksend request incomplete:").toStdString() << " " << darkSendPool.lastMessage << ". " << tr("Will retry...").toStdString(); + } else if(state == POOL_STATUS_SUCCESS) { + convert << tr("Darksend request complete:").toStdString() << " " << darkSendPool.lastMessage; + } else if(state == POOL_STATUS_QUEUE) { + if(showingDarkSendMessage % 70 <= 50) convert << tr("Submitted to masternode, waiting in queue .").toStdString(); + else if(showingDarkSendMessage % 70 <= 60) convert << tr("Submitted to masternode, waiting in queue ..").toStdString(); + else if(showingDarkSendMessage % 70 <= 70) convert << tr("Submitted to masternode, waiting in queue ...").toStdString(); + } else { + convert << tr("Unknown state:").toStdString() << " id = " << state; + } + + if(state == POOL_STATUS_ERROR || state == POOL_STATUS_SUCCESS) darkSendPool.Check(); + + QString s(convert.str().c_str()); + s = tr("Last Darksend message:\n") + s; + + if(s != ui->darksendStatus->text()) + LogPrintf("Last Darksend message: %s\n", convert.str().c_str()); + + ui->darksendStatus->setText(s); + + if(darkSendPool.sessionDenom == 0){ + ui->labelSubmittedDenom->setText(tr("N/A")); + } else { + std::string out; + darkSendPool.GetDenominationsToString(darkSendPool.sessionDenom, out); + QString s2(out.c_str()); + ui->labelSubmittedDenom->setText(s2); + } + + showingDarkSendMessage++; + darksendActionCheck++; + + // Get DarkSend Denomination Status +} + +void OverviewPage::darksendAuto(){ + darkSendPool.DoAutomaticDenominating(); +} + +void OverviewPage::darksendReset(){ + darkSendPool.Reset(); + + QMessageBox::warning(this, tr("Darksend"), + tr("Darksend was successfully reset."), + QMessageBox::Ok, QMessageBox::Ok); +} + +void OverviewPage::toggleDarksend(){ + if(!fEnableDarksend){ + int64_t balance = pwalletMain->GetBalance(); + float minAmount = 1.49 * COIN; + if(balance < minAmount){ + QString strMinAmount( + BitcoinUnits::formatWithUnit( + walletModel->getOptionsModel()->getDisplayUnit(), + minAmount)); + QMessageBox::warning(this, tr("Darksend"), + tr("Darksend requires at least %1 to use.").arg(strMinAmount), + QMessageBox::Ok, QMessageBox::Ok); + return; + } + + // if wallet is locked, ask for a passphrase + if (walletModel->getEncryptionStatus() == WalletModel::Locked) + { + WalletModel::UnlockContext ctx(walletModel->requestUnlock()); + if(!ctx.isValid()) + { + //unlock was cancelled + darkSendPool.cachedNumBlocks = 0; + QMessageBox::warning(this, tr("Darksend"), + tr("Wallet is locked and user declined to unlock. Disabling Darksend."), + QMessageBox::Ok, QMessageBox::Ok); + if (fDebug) LogPrintf("Wallet is locked and user declined to unlock. Disabling Darksend.\n"); + return; + } + } + + } + + darkSendPool.cachedNumBlocks = 0; + fEnableDarksend = !fEnableDarksend; + + if(!fEnableDarksend){ + ui->toggleDarksend->setText(tr("Start Darksend")); + } else { + ui->toggleDarksend->setText(tr("Stop Darksend")); + + /* show darksend configuration if client has defaults set */ + + if(nAnonymizeGeniusAmount == 0){ + DarksendConfig dlg(this); + dlg.setModel(walletModel); + dlg.exec(); + } + + darkSendPool.DoAutomaticDenominating(); + } +} diff --git a/src/qt/overviewpage.h b/src/qt/overviewpage.h index 7249684..44c4602 100644 --- a/src/qt/overviewpage.h +++ b/src/qt/overviewpage.h @@ -2,6 +2,7 @@ #define OVERVIEWPAGE_H #include +#include namespace Ui { class OverviewPage; @@ -27,14 +28,17 @@ class OverviewPage : public QWidget void setClientModel(ClientModel *clientModel); void setWalletModel(WalletModel *walletModel); void showOutOfSyncWarning(bool fShow); + void updateDarksendProgress(); public slots: - void setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance); + void darkSendStatus(); + void setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance, qint64 anonymizedBalance); signals: void transactionClicked(const QModelIndex &index); private: + QTimer *timer; Ui::OverviewPage *ui; ClientModel *clientModel; WalletModel *walletModel; @@ -42,11 +46,20 @@ public slots: qint64 currentStake; qint64 currentUnconfirmedBalance; qint64 currentImmatureBalance; + qint64 currentAnonymizedBalance; + qint64 cachedTxLocks; + qint64 lastNewBlock; + int showingDarkSendMessage; + int darksendActionCheck; + int cachedNumBlocks; TxViewDelegate *txdelegate; TransactionFilterProxy *filter; private slots: + void toggleDarksend(); + void darksendAuto(); + void darksendReset(); void updateDisplayUnit(); void handleTransactionClicked(const QModelIndex &index); void updateAlerts(const QString &warnings); diff --git a/src/qt/plugins/mrichtexteditor/LGPL_EXCEPTION.txt b/src/qt/plugins/mrichtexteditor/LGPL_EXCEPTION.txt new file mode 100644 index 0000000..e4e581a --- /dev/null +++ b/src/qt/plugins/mrichtexteditor/LGPL_EXCEPTION.txt @@ -0,0 +1,23 @@ +Digia Qt LGPL Exception version 1.1 + +As an additional permission to the GNU Lesser General Public License version +2.1, the object code form of a "work that uses the Library" may incorporate +material from a header file that is part of the Library. You may distribute +such object code under terms of your choice, provided that: + (i) the header files of the Library have not been modified; and + (ii) the incorporated material is limited to numerical parameters, data + structure layouts, accessors, macros, inline functions and + templates; and + (iii) you comply with the terms of Section 6 of the GNU Lesser General + Public License version 2.1. + +Moreover, you may apply this exception to a modified version of the Library, +provided that such modification does not involve copying material from the +Library into the modified Library's header files unless such material is +limited to (i) numerical parameters; (ii) data structure layouts; +(iii) accessors; and (iv) small macros, templates and inline functions of +five lines or less in length. + +Furthermore, you are not required to apply this additional permission to a +modified version of the Library. + diff --git a/src/qt/plugins/mrichtexteditor/LICENSE.LGPL b/src/qt/plugins/mrichtexteditor/LICENSE.LGPL new file mode 100644 index 0000000..3e12d08 --- /dev/null +++ b/src/qt/plugins/mrichtexteditor/LICENSE.LGPL @@ -0,0 +1,505 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 2.1, February 1999 + + Copyright (C) 1991, 1999 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + +[This is the first released version of the Lesser GPL. It also counts + as the successor of the GNU Library Public License, version 2, hence + the version number 2.1.] + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +Licenses are intended to guarantee your freedom to share and change +free software--to make sure the software is free for all its users. + + This license, the Lesser General Public License, applies to some +specially designated software packages--typically libraries--of the +Free Software Foundation and other authors who decide to use it. You +can use it too, but we suggest you first think carefully about whether +this license or the ordinary General Public License is the better +strategy to use in any particular case, based on the explanations below. + + When we speak of free software, we are referring to freedom of use, +not price. Our General Public Licenses are designed to make sure that +you have the freedom to distribute copies of free software (and charge +for this service if you wish); that you receive source code or can get +it if you want it; that you can change the software and use pieces of +it in new free programs; and that you are informed that you can do +these things. + + To protect your rights, we need to make restrictions that forbid +distributors to deny you these rights or to ask you to surrender these +rights. These restrictions translate to certain responsibilities for +you if you distribute copies of the library or if you modify it. + + For example, if you distribute copies of the library, whether gratis +or for a fee, you must give the recipients all the rights that we gave +you. You must make sure that they, too, receive or can get the source +code. If you link other code with the library, you must provide +complete object files to the recipients, so that they can relink them +with the library after making changes to the library and recompiling +it. And you must show them these terms so they know their rights. + + We protect your rights with a two-step method: (1) we copyright the +library, and (2) we offer you this license, which gives you legal +permission to copy, distribute and/or modify the library. + + To protect each distributor, we want to make it very clear that +there is no warranty for the free library. Also, if the library is +modified by someone else and passed on, the recipients should know +that what they have is not the original version, so that the original +author's reputation will not be affected by problems that might be +introduced by others. + + Finally, software patents pose a constant threat to the existence of +any free program. We wish to make sure that a company cannot +effectively restrict the users of a free program by obtaining a +restrictive license from a patent holder. Therefore, we insist that +any patent license obtained for a version of the library must be +consistent with the full freedom of use specified in this license. + + Most GNU software, including some libraries, is covered by the +ordinary GNU General Public License. This license, the GNU Lesser +General Public License, applies to certain designated libraries, and +is quite different from the ordinary General Public License. We use +this license for certain libraries in order to permit linking those +libraries into non-free programs. + + When a program is linked with a library, whether statically or using +a shared library, the combination of the two is legally speaking a +combined work, a derivative of the original library. The ordinary +General Public License therefore permits such linking only if the +entire combination fits its criteria of freedom. The Lesser General +Public License permits more lax criteria for linking other code with +the library. + + We call this license the "Lesser" General Public License because it +does Less to protect the user's freedom than the ordinary General +Public License. It also provides other free software developers Less +of an advantage over competing non-free programs. These disadvantages +are the reason we use the ordinary General Public License for many +libraries. However, the Lesser license provides advantages in certain +special circumstances. + + For example, on rare occasions, there may be a special need to +encourage the widest possible use of a certain library, so that it becomes +a de-facto standard. To achieve this, non-free programs must be +allowed to use the library. A more frequent case is that a free +library does the same job as widely used non-free libraries. In this +case, there is little to gain by limiting the free library to free +software only, so we use the Lesser General Public License. + + In other cases, permission to use a particular library in non-free +programs enables a greater number of people to use a large body of +free software. For example, permission to use the GNU C Library in +non-free programs enables many more people to use the whole GNU +operating system, as well as its variant, the GNU/Linux operating +system. + + Although the Lesser General Public License is Less protective of the +users' freedom, it does ensure that the user of a program that is +linked with the Library has the freedom and the wherewithal to run +that program using a modified version of the Library. + + The precise terms and conditions for copying, distribution and +modification follow. Pay close attention to the difference between a +"work based on the library" and a "work that uses the library". The +former contains code derived from the library, whereas the latter must +be combined with the library in order to run. + + GNU LESSER GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License Agreement applies to any software library or other +program which contains a notice placed by the copyright holder or +other authorized party saying it may be distributed under the terms of +this Lesser General Public License (also called "this License"). +Each licensee is addressed as "you". + + A "library" means a collection of software functions and/or data +prepared so as to be conveniently linked with application programs +(which use some of those functions and data) to form executables. + + The "Library", below, refers to any such software library or work +which has been distributed under these terms. A "work based on the +Library" means either the Library or any derivative work under +copyright law: that is to say, a work containing the Library or a +portion of it, either verbatim or with modifications and/or translated +straightforwardly into another language. (Hereinafter, translation is +included without limitation in the term "modification".) + + "Source code" for a work means the preferred form of the work for +making modifications to it. For a library, complete source code means +all the source code for all modules it contains, plus any associated +interface definition files, plus the scripts used to control compilation +and installation of the library. + + Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running a program using the Library is not restricted, and output from +such a program is covered only if its contents constitute a work based +on the Library (independent of the use of the Library in a tool for +writing it). Whether that is true depends on what the Library does +and what the program that uses the Library does. + + 1. You may copy and distribute verbatim copies of the Library's +complete source code as you receive it, in any medium, provided that +you conspicuously and appropriately publish on each copy an +appropriate copyright notice and disclaimer of warranty; keep intact +all the notices that refer to this License and to the absence of any +warranty; and distribute a copy of this License along with the +Library. + + You may charge a fee for the physical act of transferring a copy, +and you may at your option offer warranty protection in exchange for a +fee. + + 2. You may modify your copy or copies of the Library or any portion +of it, thus forming a work based on the Library, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) The modified work must itself be a software library. + + b) You must cause the files modified to carry prominent notices + stating that you changed the files and the date of any change. + + c) You must cause the whole of the work to be licensed at no + charge to all third parties under the terms of this License. + + d) If a facility in the modified Library refers to a function or a + table of data to be supplied by an application program that uses + the facility, other than as an argument passed when the facility + is invoked, then you must make a good faith effort to ensure that, + in the event an application does not supply such function or + table, the facility still operates, and performs whatever part of + its purpose remains meaningful. + + (For example, a function in a library to compute square roots has + a purpose that is entirely well-defined independent of the + application. Therefore, Subsection 2d requires that any + application-supplied function or table used by this function must + be optional: if the application does not supply it, the square + root function must still compute square roots.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Library, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Library, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote +it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Library. + +In addition, mere aggregation of another work not based on the Library +with the Library (or with a work based on the Library) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may opt to apply the terms of the ordinary GNU General Public +License instead of this License to a given copy of the Library. To do +this, you must alter all the notices that refer to this License, so +that they refer to the ordinary GNU General Public License, version 2, +instead of to this License. (If a newer version than version 2 of the +ordinary GNU General Public License has appeared, then you can specify +that version instead if you wish.) Do not make any other change in +these notices. + + Once this change is made in a given copy, it is irreversible for +that copy, so the ordinary GNU General Public License applies to all +subsequent copies and derivative works made from that copy. + + This option is useful when you wish to copy part of the code of +the Library into a program that is not a library. + + 4. You may copy and distribute the Library (or a portion or +derivative of it, under Section 2) in object code or executable form +under the terms of Sections 1 and 2 above provided that you accompany +it with the complete corresponding machine-readable source code, which +must be distributed under the terms of Sections 1 and 2 above on a +medium customarily used for software interchange. + + If distribution of object code is made by offering access to copy +from a designated place, then offering equivalent access to copy the +source code from the same place satisfies the requirement to +distribute the source code, even though third parties are not +compelled to copy the source along with the object code. + + 5. A program that contains no derivative of any portion of the +Library, but is designed to work with the Library by being compiled or +linked with it, is called a "work that uses the Library". Such a +work, in isolation, is not a derivative work of the Library, and +therefore falls outside the scope of this License. + + However, linking a "work that uses the Library" with the Library +creates an executable that is a derivative of the Library (because it +contains portions of the Library), rather than a "work that uses the +library". The executable is therefore covered by this License. +Section 6 states terms for distribution of such executables. + + When a "work that uses the Library" uses material from a header file +that is part of the Library, the object code for the work may be a +derivative work of the Library even though the source code is not. +Whether this is true is especially significant if the work can be +linked without the Library, or if the work is itself a library. The +threshold for this to be true is not precisely defined by law. + + If such an object file uses only numerical parameters, data +structure layouts and accessors, and small macros and small inline +functions (ten lines or less in length), then the use of the object +file is unrestricted, regardless of whether it is legally a derivative +work. (Executables containing this object code plus portions of the +Library will still fall under Section 6.) + + Otherwise, if the work is a derivative of the Library, you may +distribute the object code for the work under the terms of Section 6. +Any executables containing that work also fall under Section 6, +whether or not they are linked directly with the Library itself. + + 6. As an exception to the Sections above, you may also combine or +link a "work that uses the Library" with the Library to produce a +work containing portions of the Library, and distribute that work +under terms of your choice, provided that the terms permit +modification of the work for the customer's own use and reverse +engineering for debugging such modifications. + + You must give prominent notice with each copy of the work that the +Library is used in it and that the Library and its use are covered by +this License. You must supply a copy of this License. If the work +during execution displays copyright notices, you must include the +copyright notice for the Library among them, as well as a reference +directing the user to the copy of this License. Also, you must do one +of these things: + + a) Accompany the work with the complete corresponding + machine-readable source code for the Library including whatever + changes were used in the work (which must be distributed under + Sections 1 and 2 above); and, if the work is an executable linked + with the Library, with the complete machine-readable "work that + uses the Library", as object code and/or source code, so that the + user can modify the Library and then relink to produce a modified + executable containing the modified Library. (It is understood + that the user who changes the contents of definitions files in the + Library will not necessarily be able to recompile the application + to use the modified definitions.) + + b) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (1) uses at run time a + copy of the library already present on the user's computer system, + rather than copying library functions into the executable, and (2) + will operate properly with a modified version of the library, if + the user installs one, as long as the modified version is + interface-compatible with the version that the work was made with. + + c) Accompany the work with a written offer, valid for at + least three years, to give the same user the materials + specified in Subsection 6a, above, for a charge no more + than the cost of performing this distribution. + + d) If distribution of the work is made by offering access to copy + from a designated place, offer equivalent access to copy the above + specified materials from the same place. + + e) Verify that the user has already received a copy of these + materials or that you have already sent this user a copy. + + For an executable, the required form of the "work that uses the +Library" must include any data and utility programs needed for +reproducing the executable from it. However, as a special exception, +the materials to be distributed need not include anything that is +normally distributed (in either source or binary form) with the major +components (compiler, kernel, and so on) of the operating system on +which the executable runs, unless that component itself accompanies +the executable. + + It may happen that this requirement contradicts the license +restrictions of other proprietary libraries that do not normally +accompany the operating system. Such a contradiction means you cannot +use both them and the Library together in an executable that you +distribute. + + 7. 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 not covered by this License, and distribute such a combined +library, provided that the separate distribution of the work based on +the Library and of the other library facilities is otherwise +permitted, and provided that you do these two things: + + a) Accompany the combined library with a copy of the same work + based on the Library, uncombined with any other library + facilities. This must be distributed under the terms of the + Sections above. + + b) Give prominent notice with the combined library of the fact + that part of it is a work based on the Library, and explaining + where to find the accompanying uncombined form of the same work. + + 8. You may not copy, modify, sublicense, link with, or distribute +the Library except as expressly provided under this License. Any +attempt otherwise to copy, modify, sublicense, link with, or +distribute the Library is void, and will automatically terminate your +rights under this License. However, parties who have received copies, +or rights, from you under this License will not have their licenses +terminated so long as such parties remain in full compliance. + + 9. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Library or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Library (or any work based on the +Library), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Library or works based on it. + + 10. Each time you redistribute the Library (or any work based on the +Library), the recipient automatically receives a license from the +original licensor to copy, distribute, link with or modify the Library +subject to these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties with +this License. + + 11. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Library at all. For example, if a patent +license would not permit royalty-free redistribution of the Library by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Library. + +If any portion of this section is held invalid or unenforceable under any +particular circumstance, the balance of the section is intended to apply, +and the section as a whole is intended to apply in other circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 12. If the distribution and/or use of the Library is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Library under this License may add +an explicit geographical distribution limitation excluding those countries, +so that distribution is permitted only in or among countries not thus +excluded. In such case, this License incorporates the limitation as if +written in the body of this License. + + 13. The Free Software Foundation may publish revised and/or new +versions of the 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 +specifies a version number of this License which applies to it and +"any later version", you have the option of following the terms and +conditions either of that version or of any later version published by +the Free Software Foundation. If the Library does not specify a +license version number, you may choose any version ever published by +the Free Software Foundation. + + 14. If you wish to incorporate parts of the Library into other free +programs whose distribution conditions are incompatible with these, +write to the author to ask for permission. For software which is +copyrighted by the Free Software Foundation, write to the Free +Software Foundation; we sometimes make exceptions for this. Our +decision will be guided by the two goals of preserving the free status +of all derivatives of our free software and of promoting the sharing +and reuse of software generally. + + NO WARRANTY + + 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO +WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. +EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR +OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY +KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE +LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME +THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN +WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY +AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU +FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR +CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE +LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING +RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A +FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF +SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH +DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Libraries + + If you develop a new library, and you want it to be of the greatest +possible use to the public, we recommend making it free software that +everyone can redistribute and change. You can do so by permitting +redistribution under these terms (or, alternatively, under the terms of the +ordinary General Public License). + + To apply these terms, attach the following notices to the library. It is +safest to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least the +"copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + This library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with this library; if not, write to the Free Software + Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + +Also add information on how to contact you by electronic and paper mail. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the library, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the + library `Frob' (a library for tweaking knobs) written by James Random Hacker. + + , 1 April 1990 + Ty Coon, President of Vice + +That's all there is to it! + + + diff --git a/src/qt/plugins/mrichtexteditor/README.md b/src/qt/plugins/mrichtexteditor/README.md new file mode 100644 index 0000000..f76d7e3 --- /dev/null +++ b/src/qt/plugins/mrichtexteditor/README.md @@ -0,0 +1,11 @@ +# MRichTextEdit + +A simple Qt rich-text editor widget, easy to use in any Qt project. + +![Screenshot](https://github.com/Anchakor/MRichTextEditor/raw/master/example.png) + +The icons used are standard icons from theme as defined by [freedesktop.org Icon Naming Specification](http://standards.freedesktop.org/icon-naming-spec/icon-naming-spec-latest.html) (which lacks button/ordered list icons). + +The editor automatically converts plain text http(s) links and emails to html links in toHtml(). + +Courtesy of [Hobrasoft](http://www.hobrasoft.cz/). diff --git a/src/qt/plugins/mrichtexteditor/example.png b/src/qt/plugins/mrichtexteditor/example.png new file mode 100644 index 0000000..2bc545a Binary files /dev/null and b/src/qt/plugins/mrichtexteditor/example.png differ diff --git a/src/qt/plugins/mrichtexteditor/mrichtextedit.cpp b/src/qt/plugins/mrichtexteditor/mrichtextedit.cpp new file mode 100644 index 0000000..939b942 --- /dev/null +++ b/src/qt/plugins/mrichtexteditor/mrichtextedit.cpp @@ -0,0 +1,468 @@ +/* +** Copyright (C) 2013 Jiří Procházka (Hobrasoft) +** Contact: http://www.hobrasoft.cz/ +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file is under the terms of the GNU Lesser General Public License +** version 2.1 as published by the Free Software Foundation and appearing +** in the file LICENSE.LGPL included in the packaging of this file. +** Please review the following information to ensure the +** GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** $QT_END_LICENSE$ +*/ + +#include "mrichtextedit.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +MRichTextEdit::MRichTextEdit(QWidget *parent) : QWidget(parent) { + setupUi(this); + m_lastBlockList = 0; + f_textedit->setTabStopWidth(40); + + connect(f_textedit, SIGNAL(currentCharFormatChanged(QTextCharFormat)), + this, SLOT(slotCurrentCharFormatChanged(QTextCharFormat))); + connect(f_textedit, SIGNAL(cursorPositionChanged()), + this, SLOT(slotCursorPositionChanged())); + + m_fontsize_h1 = 18; + m_fontsize_h2 = 16; + m_fontsize_h3 = 14; + m_fontsize_h4 = 12; + + fontChanged(f_textedit->font()); + bgColorChanged(f_textedit->textColor()); + + // paragraph formatting + + m_paragraphItems << tr("Standard") + << tr("Heading 1") + << tr("Heading 2") + << tr("Heading 3") + << tr("Heading 4") + << tr("Monospace"); + f_paragraph->addItems(m_paragraphItems); + + connect(f_paragraph, SIGNAL(activated(int)), + this, SLOT(textStyle(int))); + + // undo & redo + + f_undo->setShortcut(QKeySequence::Undo); + f_redo->setShortcut(QKeySequence::Redo); + + connect(f_textedit->document(), SIGNAL(undoAvailable(bool)), + f_undo, SLOT(setEnabled(bool))); + connect(f_textedit->document(), SIGNAL(redoAvailable(bool)), + f_redo, SLOT(setEnabled(bool))); + + f_undo->setEnabled(f_textedit->document()->isUndoAvailable()); + f_redo->setEnabled(f_textedit->document()->isRedoAvailable()); + + connect(f_undo, SIGNAL(clicked()), f_textedit, SLOT(undo())); + connect(f_redo, SIGNAL(clicked()), f_textedit, SLOT(redo())); + + // cut, copy & paste + + f_cut->setShortcut(QKeySequence::Cut); + f_copy->setShortcut(QKeySequence::Copy); + f_paste->setShortcut(QKeySequence::Paste); + + f_cut->setEnabled(false); + f_copy->setEnabled(false); + + connect(f_cut, SIGNAL(clicked()), f_textedit, SLOT(cut())); + connect(f_copy, SIGNAL(clicked()), f_textedit, SLOT(copy())); + connect(f_paste, SIGNAL(clicked()), f_textedit, SLOT(paste())); + + connect(f_textedit, SIGNAL(copyAvailable(bool)), f_cut, SLOT(setEnabled(bool))); + connect(f_textedit, SIGNAL(copyAvailable(bool)), f_copy, SLOT(setEnabled(bool))); + +#ifndef QT_NO_CLIPBOARD + connect(QApplication::clipboard(), SIGNAL(dataChanged()), this, SLOT(slotClipboardDataChanged())); +#endif + + // link + + f_link->setShortcut(Qt::CTRL + Qt::Key_L); + + connect(f_link, SIGNAL(clicked(bool)), this, SLOT(textLink(bool))); + + // bold, italic & underline + + f_bold->setShortcut(Qt::CTRL + Qt::Key_B); + f_italic->setShortcut(Qt::CTRL + Qt::Key_I); + f_underline->setShortcut(Qt::CTRL + Qt::Key_U); + + connect(f_bold, SIGNAL(clicked()), this, SLOT(textBold())); + connect(f_italic, SIGNAL(clicked()), this, SLOT(textItalic())); + connect(f_underline, SIGNAL(clicked()), this, SLOT(textUnderline())); + connect(f_strikeout, SIGNAL(clicked()), this, SLOT(textStrikeout())); + + // lists + + f_list_bullet->setShortcut(Qt::CTRL + Qt::Key_Minus); + f_list_ordered->setShortcut(Qt::CTRL + Qt::Key_Equal); + + connect(f_list_bullet, SIGNAL(clicked(bool)), this, SLOT(listBullet(bool))); + connect(f_list_ordered, SIGNAL(clicked(bool)), this, SLOT(listOrdered(bool))); + + // indentation + + f_indent_dec->setShortcut(Qt::CTRL + Qt::Key_Comma); + f_indent_inc->setShortcut(Qt::CTRL + Qt::Key_Period); + + connect(f_indent_inc, SIGNAL(clicked()), this, SLOT(increaseIndentation())); + connect(f_indent_dec, SIGNAL(clicked()), this, SLOT(decreaseIndentation())); + + // font size + + QFontDatabase db; + foreach(int size, db.standardSizes()) + f_fontsize->addItem(QString::number(size)); + + connect(f_fontsize, SIGNAL(activated(QString)), + this, SLOT(textSize(QString))); + f_fontsize->setCurrentIndex(f_fontsize->findText(QString::number(QApplication::font() + .pointSize()))); + + // text background color + + QPixmap pix(16, 16); + pix.fill(QApplication::palette().background().color()); + f_bgcolor->setIcon(pix); + + connect(f_bgcolor, SIGNAL(clicked()), this, SLOT(textBgColor())); + + // images + //connect(f_image, SIGNAL(clicked()), this, SLOT(insertImage())); +} + +void MRichTextEdit::textBold() { + QTextCharFormat fmt; + fmt.setFontWeight(f_bold->isChecked() ? QFont::Bold : QFont::Normal); + mergeFormatOnWordOrSelection(fmt); +} + + +void MRichTextEdit::focusInEvent(QFocusEvent *) { + f_textedit->setFocus(Qt::TabFocusReason); +} + + +void MRichTextEdit::textUnderline() { + QTextCharFormat fmt; + fmt.setFontUnderline(f_underline->isChecked()); + mergeFormatOnWordOrSelection(fmt); +} + +void MRichTextEdit::textItalic() { + QTextCharFormat fmt; + fmt.setFontItalic(f_italic->isChecked()); + mergeFormatOnWordOrSelection(fmt); +} + +void MRichTextEdit::textStrikeout() { + QTextCharFormat fmt; + fmt.setFontStrikeOut(f_strikeout->isChecked()); + mergeFormatOnWordOrSelection(fmt); +} + +void MRichTextEdit::textSize(const QString &p) { + qreal pointSize = p.toFloat(); + if (p.toFloat() > 0) { + QTextCharFormat fmt; + fmt.setFontPointSize(pointSize); + mergeFormatOnWordOrSelection(fmt); + } +} + +void MRichTextEdit::textLink(bool checked) { + bool unlink = false; + QTextCharFormat fmt; + if (checked) { + QString url = f_textedit->currentCharFormat().anchorHref(); + bool ok; + QString newUrl = QInputDialog::getText(this, tr("Create a link"), + tr("Link URL:"), QLineEdit::Normal, + url, + &ok); + if (ok) { + fmt.setAnchor(true); + fmt.setAnchorHref(newUrl); + fmt.setForeground(QApplication::palette().color(QPalette::Link)); + fmt.setFontUnderline(true); + } else { + unlink = true; + } + } else { + unlink = true; + } + if (unlink) { + fmt.setAnchor(false); + fmt.setForeground(QApplication::palette().color(QPalette::Text)); + fmt.setFontUnderline(false); + } + mergeFormatOnWordOrSelection(fmt); +} + +void MRichTextEdit::textStyle(int index) { + QTextCursor cursor = f_textedit->textCursor(); + cursor.beginEditBlock(); + + // standard + if (!cursor.hasSelection()) { + cursor.select(QTextCursor::BlockUnderCursor); + } + QTextCharFormat fmt; + cursor.setCharFormat(fmt); + f_textedit->setCurrentCharFormat(fmt); + + if (index == ParagraphHeading1 + || index == ParagraphHeading2 + || index == ParagraphHeading3 + || index == ParagraphHeading4 ) { + if (index == ParagraphHeading1) { + fmt.setFontPointSize(m_fontsize_h1); + } + if (index == ParagraphHeading2) { + fmt.setFontPointSize(m_fontsize_h2); + } + if (index == ParagraphHeading3) { + fmt.setFontPointSize(m_fontsize_h3); + } + if (index == ParagraphHeading4) { + fmt.setFontPointSize(m_fontsize_h4); + } + if (index == ParagraphHeading2 || index == ParagraphHeading4) { + fmt.setFontItalic(true); + } + + fmt.setFontWeight(QFont::Bold); + } + if (index == ParagraphMonospace) { + fmt = cursor.charFormat(); + fmt.setFontFamily("Monospace"); + fmt.setFontStyleHint(QFont::Monospace); + fmt.setFontFixedPitch(true); + } + cursor.setCharFormat(fmt); + f_textedit->setCurrentCharFormat(fmt); + + cursor.endEditBlock(); +} + +void MRichTextEdit::textBgColor() { + QColor col = QColorDialog::getColor(f_textedit->textBackgroundColor(), this); + QTextCursor cursor = f_textedit->textCursor(); + if (!cursor.hasSelection()) { + cursor.select(QTextCursor::WordUnderCursor); + } + QTextCharFormat fmt = cursor.charFormat(); + if (col.isValid()) { + fmt.setBackground(col); + } else { + fmt.clearBackground(); + } + cursor.setCharFormat(fmt); + f_textedit->setCurrentCharFormat(fmt); + bgColorChanged(col); +} + +void MRichTextEdit::listBullet(bool checked) { + if (checked) { + f_list_ordered->setChecked(false); + } + list(checked, QTextListFormat::ListDisc); +} + +void MRichTextEdit::listOrdered(bool checked) { + if (checked) { + f_list_bullet->setChecked(false); + } + list(checked, QTextListFormat::ListDecimal); +} + +void MRichTextEdit::list(bool checked, QTextListFormat::Style style) { + QTextCursor cursor = f_textedit->textCursor(); + cursor.beginEditBlock(); + if (!checked) { + QTextBlockFormat obfmt = cursor.blockFormat(); + QTextBlockFormat bfmt; + bfmt.setIndent(obfmt.indent()); + cursor.setBlockFormat(bfmt); + } else { + QTextListFormat listFmt; + if (cursor.currentList()) { + listFmt = cursor.currentList()->format(); + } + listFmt.setStyle(style); + cursor.createList(listFmt); + } + cursor.endEditBlock(); +} + +void MRichTextEdit::mergeFormatOnWordOrSelection(const QTextCharFormat &format) { + QTextCursor cursor = f_textedit->textCursor(); + if (!cursor.hasSelection()) { + cursor.select(QTextCursor::WordUnderCursor); + } + cursor.mergeCharFormat(format); + f_textedit->mergeCurrentCharFormat(format); +} + +void MRichTextEdit::slotCursorPositionChanged() { + QTextList *l = f_textedit->textCursor().currentList(); + if (m_lastBlockList && (l == m_lastBlockList || (l != 0 && m_lastBlockList != 0 + && l->format().style() == m_lastBlockList->format().style()))) { + return; + } + m_lastBlockList = l; + if (l) { + QTextListFormat lfmt = l->format(); + if (lfmt.style() == QTextListFormat::ListDisc) { + f_list_bullet->setChecked(true); + f_list_ordered->setChecked(false); + } else if (lfmt.style() == QTextListFormat::ListDecimal) { + f_list_bullet->setChecked(false); + f_list_ordered->setChecked(true); + } else { + f_list_bullet->setChecked(false); + f_list_ordered->setChecked(false); + } + } else { + f_list_bullet->setChecked(false); + f_list_ordered->setChecked(false); + } +} + +void MRichTextEdit::fontChanged(const QFont &f) { + f_fontsize->setCurrentIndex(f_fontsize->findText(QString::number(f.pointSize()))); + f_bold->setChecked(f.bold()); + f_italic->setChecked(f.italic()); + f_underline->setChecked(f.underline()); + f_strikeout->setChecked(f.strikeOut()); + if (f.pointSize() == m_fontsize_h1) { + f_paragraph->setCurrentIndex(ParagraphHeading1); + } else if (f.pointSize() == m_fontsize_h2) { + f_paragraph->setCurrentIndex(ParagraphHeading2); + } else if (f.pointSize() == m_fontsize_h3) { + f_paragraph->setCurrentIndex(ParagraphHeading3); + } else if (f.pointSize() == m_fontsize_h4) { + f_paragraph->setCurrentIndex(ParagraphHeading4); + } else { + if (f.fixedPitch() && f.family() == "Monospace") { + f_paragraph->setCurrentIndex(ParagraphMonospace); + } else { + f_paragraph->setCurrentIndex(ParagraphStandard); + } + } + if (f_textedit->textCursor().currentList()) { + QTextListFormat lfmt = f_textedit->textCursor().currentList()->format(); + if (lfmt.style() == QTextListFormat::ListDisc) { + f_list_bullet->setChecked(true); + f_list_ordered->setChecked(false); + } else if (lfmt.style() == QTextListFormat::ListDecimal) { + f_list_bullet->setChecked(false); + f_list_ordered->setChecked(true); + } else { + f_list_bullet->setChecked(false); + f_list_ordered->setChecked(false); + } + } else { + f_list_bullet->setChecked(false); + f_list_ordered->setChecked(false); + } +} + +void MRichTextEdit::bgColorChanged(const QColor &c) { + QPixmap pix(16, 16); + if (c.isValid()) { + pix.fill(c); + } else { + pix.fill(QApplication::palette().background().color()); + } + f_bgcolor->setIcon(pix); +} + +void MRichTextEdit::slotCurrentCharFormatChanged(const QTextCharFormat &format) { + fontChanged(format.font()); + bgColorChanged((format.background().isOpaque()) ? format.background().color() : QColor()); + f_link->setChecked(format.isAnchor()); +} + +void MRichTextEdit::slotClipboardDataChanged() { +#ifndef QT_NO_CLIPBOARD + if (const QMimeData *md = QApplication::clipboard()->mimeData()) + f_paste->setEnabled(md->hasText()); +#endif +} + +QString MRichTextEdit::toHtml() const { + QString s = f_textedit->toHtml(); + // convert emails to links + s = s.replace(QRegExp("(<[^a][^>]+>(?:]+>)?|\\s)([a-zA-Z\\d]+@[a-zA-Z\\d]+\\.[a-zA-Z]+)"), "\\1\\2"); + // convert links + s = s.replace(QRegExp("(<[^a][^>]+>(?:]+>)?|\\s)((?:https?|ftp|file)://[^\\s'\"<>]+)"), "\\1\\2"); + // see also: Utils::linkify() + return s; +} + +void MRichTextEdit::increaseIndentation() { + indent(+1); +} + +void MRichTextEdit::decreaseIndentation() { + indent(-1); +} + +void MRichTextEdit::indent(int delta) { + QTextCursor cursor = f_textedit->textCursor(); + cursor.beginEditBlock(); + QTextBlockFormat bfmt = cursor.blockFormat(); + int ind = bfmt.indent(); + if (ind + delta >= 0) { + bfmt.setIndent(ind + delta); + } + cursor.setBlockFormat(bfmt); + cursor.endEditBlock(); +} + +void MRichTextEdit::setText(const QString& text) { + if (text.isEmpty()) { + setPlainText(text); + return; + } + if (text[0] == '<') { + setHtml(text); + } else { + setPlainText(text); + } +} + +void MRichTextEdit::clear() { + f_textedit->clear(); +} + + diff --git a/src/qt/plugins/mrichtexteditor/mrichtextedit.h b/src/qt/plugins/mrichtexteditor/mrichtextedit.h new file mode 100644 index 0000000..24e3fbb --- /dev/null +++ b/src/qt/plugins/mrichtexteditor/mrichtextedit.h @@ -0,0 +1,92 @@ +/* +** Copyright (C) 2013 Jiří Procházka (Hobrasoft) +** Contact: http://www.hobrasoft.cz/ +** +** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies). +** Contact: http://www.qt-project.org/legal +** +** $QT_BEGIN_LICENSE:LGPL$ +** GNU Lesser General Public License Usage +** This file is under the terms of the GNU Lesser General Public License +** version 2.1 as published by the Free Software Foundation and appearing +** in the file LICENSE.LGPL included in the packaging of this file. +** Please review the following information to ensure the +** GNU Lesser General Public License version 2.1 requirements +** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. +** +** In addition, as a special exception, Digia gives you certain additional +** rights. These rights are described in the Digia Qt LGPL Exception +** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. +** +** $QT_END_LICENSE$ +*/ + +#ifndef _MRICHTEXTEDIT_H_ +#define _MRICHTEXTEDIT_H_ + +#include +#include "ui_mrichtextedit.h" + +/** + * @Brief A simple rich-text editor + */ +class MRichTextEdit : public QWidget, protected Ui::MRichTextEdit { + Q_OBJECT + public: + MRichTextEdit(QWidget *parent = 0); + + QString toPlainText() const { return f_textedit->toPlainText(); } + QString toHtml() const; + QTextDocument *document() { return f_textedit->document(); } + QTextCursor textCursor() const { return f_textedit->textCursor(); } + void setTextCursor(const QTextCursor& cursor) { f_textedit->setTextCursor(cursor); } + + + public slots: + void setText(const QString &text); + void clear(); + + protected slots: + void setPlainText(const QString &text) { f_textedit->setPlainText(text); } + void setHtml(const QString &text) { f_textedit->setHtml(text); } + void textBold(); + void textUnderline(); + void textStrikeout(); + void textItalic(); + void textSize(const QString &p); + void textLink(bool checked); + void textStyle(int index); + void textBgColor(); + void listBullet(bool checked); + void listOrdered(bool checked); + void slotCurrentCharFormatChanged(const QTextCharFormat &format); + void slotCursorPositionChanged(); + void slotClipboardDataChanged(); + void increaseIndentation(); + void decreaseIndentation(); + + protected: + void mergeFormatOnWordOrSelection(const QTextCharFormat &format); + void fontChanged(const QFont &f); + void bgColorChanged(const QColor &c); + void list(bool checked, QTextListFormat::Style style); + void indent(int delta); + void focusInEvent(QFocusEvent *event); + + QStringList m_paragraphItems; + int m_fontsize_h1; + int m_fontsize_h2; + int m_fontsize_h3; + int m_fontsize_h4; + + enum ParagraphItems { ParagraphStandard = 0, + ParagraphHeading1, + ParagraphHeading2, + ParagraphHeading3, + ParagraphHeading4, + ParagraphMonospace }; + + QPointer m_lastBlockList; +}; + +#endif diff --git a/src/qt/plugins/mrichtexteditor/mrichtextedit.ui b/src/qt/plugins/mrichtexteditor/mrichtextedit.ui new file mode 100644 index 0000000..50c5c42 --- /dev/null +++ b/src/qt/plugins/mrichtexteditor/mrichtextedit.ui @@ -0,0 +1,538 @@ + + + MRichTextEdit + + + + 0 + 0 + 819 + 312 + + + + + + + + 1 + + + 1 + + + 1 + + + 1 + + + 1 + + + + + + 2 + + + 0 + + + 0 + + + 0 + + + 0 + + + + + Qt::ClickFocus + + + Paragraph formatting + + + true + + + + + + + Qt::Vertical + + + + + + + false + + + Qt::ClickFocus + + + Undo (CTRL+Z) + + + Undo + + + + + + + + + 16 + 16 + + + + + + + + false + + + Qt::ClickFocus + + + Redo + + + Redo + + + + + + + + + 16 + 16 + + + + + + + + Qt::ClickFocus + + + Cut (CTRL+X) + + + Cut + + + + + + + + + 16 + 16 + + + + + + + + Qt::ClickFocus + + + Copy (CTRL+C) + + + Copy + + + + + + + + + 16 + 16 + + + + + + + + Qt::ClickFocus + + + Paste (CTRL+V) + + + Paste + + + + + + + + + 16 + 16 + + + + + + + + Qt::Vertical + + + + + + + Qt::ClickFocus + + + Link (CTRL+L) + + + Link + + + + + + + + + 16 + 16 + + + + true + + + + + + + Qt::Vertical + + + + + + + Qt::ClickFocus + + + Bold (CTRL+B) + + + Bold + + + + + + + + + 16 + 16 + + + + true + + + + + + + Qt::ClickFocus + + + Italic (CTRL+I) + + + Italic + + + + + + + + + 16 + 16 + + + + true + + + + + + + Qt::ClickFocus + + + Underline (CTRL+U) + + + Underline + + + + + + + + + 16 + 16 + + + + true + + + + + + + Strike Out + + + true + + + + + + + Qt::Vertical + + + + + + + Qt::ClickFocus + + + Bullet list (CTRL+-) + + + Bullet list + + + + 16 + 16 + + + + true + + + + + + + Qt::ClickFocus + + + Ordered list (CTRL+=) + + + Ordered list + + + + 16 + 16 + + + + true + + + + + + + Qt::ClickFocus + + + Decrease indentation (CTRL+,) + + + Decrease indentation + + + + + + + + + 16 + 16 + + + + + + + + Qt::ClickFocus + + + Increase indentation (CTRL+.) + + + Increase indentation + + + + + + + + + 16 + 16 + + + + + + + + Qt::Vertical + + + + + + + + 16 + 16 + + + + + 16 + 16 + + + + Qt::ClickFocus + + + Text background color + + + . + + + + 16 + 16 + + + + + + + + Qt::ClickFocus + + + Font size + + + true + + + + + + + Qt::Vertical + + + + + + + Qt::Horizontal + + + + 40 + 20 + + + + + + f_paragraph + line_4 + f_undo + f_redo + f_cut + f_copy + f_paste + line + f_link + line_3 + f_italic + f_underline + line_2 + f_fontsize + line_5 + f_list_bullet + f_list_ordered + f_indent_dec + f_indent_inc + f_bold + f_bgcolor + f_strikeout + line_6 + + + + + + QTextEdit::AutoNone + + + true + + + + + + + + diff --git a/src/qt/qcustomplot.cpp b/src/qt/qcustomplot.cpp new file mode 100644 index 0000000..6e3cef9 --- /dev/null +++ b/src/qt/qcustomplot.cpp @@ -0,0 +1,23710 @@ +/*************************************************************************** +** ** +** QCustomPlot, an easy to use, modern plotting widget for Qt ** +** Copyright (C) 2011, 2012, 2013, 2014 Emanuel Eichhammer ** +** ** +** This program is free software: you can redistribute it and/or modify ** +** it under the terms of the GNU General Public License as published by ** +** the Free Software Foundation, either version 3 of the License, or ** +** (at your option) any later version. ** +** ** +** This program is distributed in the hope that it will be useful, ** +** but WITHOUT ANY WARRANTY; without even the implied warranty of ** +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** +** GNU General Public License for more details. ** +** ** +** You should have received a copy of the GNU General Public License ** +** along with this program. If not, see http://www.gnu.org/licenses/. ** +** ** +**************************************************************************** +** Author: Emanuel Eichhammer ** +** Website/Contact: http://www.qcustomplot.com/ ** +** Date: 11.10.14 ** +** Version: 1.3.0-beta ** +****************************************************************************/ + +#include "qcustomplot.h" + + + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPPainter +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPPainter + \brief QPainter subclass used internally + + This QPainter subclass is used to provide some extended functionality e.g. for tweaking position + consistency between antialiased and non-antialiased painting. Further it provides workarounds + for QPainter quirks. + + \warning This class intentionally hides non-virtual functions of QPainter, e.g. setPen, save and + restore. So while it is possible to pass a QCPPainter instance to a function that expects a + QPainter pointer, some of the workarounds and tweaks will be unavailable to the function (because + it will call the base class implementations of the functions actually hidden by QCPPainter). +*/ + +/*! + Creates a new QCPPainter instance and sets default values +*/ +QCPPainter::QCPPainter() : + QPainter(), + mModes(pmDefault), + mIsAntialiasing(false) +{ + // don't setRenderHint(QPainter::NonCosmeticDefautPen) here, because painter isn't active yet and + // a call to begin() will follow +} + +/*! + Creates a new QCPPainter instance on the specified paint \a device and sets default values. Just + like the analogous QPainter constructor, begins painting on \a device immediately. + + Like \ref begin, this method sets QPainter::NonCosmeticDefaultPen in Qt versions before Qt5. +*/ +QCPPainter::QCPPainter(QPaintDevice *device) : + QPainter(device), + mModes(pmDefault), + mIsAntialiasing(false) +{ +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. + if (isActive()) + setRenderHint(QPainter::NonCosmeticDefaultPen); +#endif +} + +QCPPainter::~QCPPainter() +{ +} + +/*! + Sets the pen of the painter and applies certain fixes to it, depending on the mode of this + QCPPainter. + + \note this function hides the non-virtual base class implementation. +*/ +void QCPPainter::setPen(const QPen &pen) +{ + QPainter::setPen(pen); + if (mModes.testFlag(pmNonCosmetic)) + makeNonCosmetic(); +} + +/*! \overload + + Sets the pen (by color) of the painter and applies certain fixes to it, depending on the mode of + this QCPPainter. + + \note this function hides the non-virtual base class implementation. +*/ +void QCPPainter::setPen(const QColor &color) +{ + QPainter::setPen(color); + if (mModes.testFlag(pmNonCosmetic)) + makeNonCosmetic(); +} + +/*! \overload + + Sets the pen (by style) of the painter and applies certain fixes to it, depending on the mode of + this QCPPainter. + + \note this function hides the non-virtual base class implementation. +*/ +void QCPPainter::setPen(Qt::PenStyle penStyle) +{ + QPainter::setPen(penStyle); + if (mModes.testFlag(pmNonCosmetic)) + makeNonCosmetic(); +} + +/*! \overload + + Works around a Qt bug introduced with Qt 4.8 which makes drawing QLineF unpredictable when + antialiasing is disabled. Thus when antialiasing is disabled, it rounds the \a line to + integer coordinates and then passes it to the original drawLine. + + \note this function hides the non-virtual base class implementation. +*/ +void QCPPainter::drawLine(const QLineF &line) +{ + if (mIsAntialiasing || mModes.testFlag(pmVectorized)) + QPainter::drawLine(line); + else + QPainter::drawLine(line.toLine()); +} + +/*! + Sets whether painting uses antialiasing or not. Use this method instead of using setRenderHint + with QPainter::Antialiasing directly, as it allows QCPPainter to regain pixel exactness between + antialiased and non-antialiased painting (Since Qt < 5.0 uses slightly different coordinate systems for + AA/Non-AA painting). +*/ +void QCPPainter::setAntialiasing(bool enabled) +{ + setRenderHint(QPainter::Antialiasing, enabled); + if (mIsAntialiasing != enabled) + { + mIsAntialiasing = enabled; + if (!mModes.testFlag(pmVectorized)) // antialiasing half-pixel shift only needed for rasterized outputs + { + if (mIsAntialiasing) + translate(0.5, 0.5); + else + translate(-0.5, -0.5); + } + } +} + +/*! + Sets the mode of the painter. This controls whether the painter shall adjust its + fixes/workarounds optimized for certain output devices. +*/ +void QCPPainter::setModes(QCPPainter::PainterModes modes) +{ + mModes = modes; +} + +/*! + Sets the QPainter::NonCosmeticDefaultPen in Qt versions before Qt5 after beginning painting on \a + device. This is necessary to get cosmetic pen consistency across Qt versions, because since Qt5, + all pens are non-cosmetic by default, and in Qt4 this render hint must be set to get that + behaviour. + + The Constructor \ref QCPPainter(QPaintDevice *device) which directly starts painting also sets + the render hint as appropriate. + + \note this function hides the non-virtual base class implementation. +*/ +bool QCPPainter::begin(QPaintDevice *device) +{ + bool result = QPainter::begin(device); +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) // before Qt5, default pens used to be cosmetic if NonCosmeticDefaultPen flag isn't set. So we set it to get consistency across Qt versions. + if (result) + setRenderHint(QPainter::NonCosmeticDefaultPen); +#endif + return result; +} + +/*! \overload + + Sets the mode of the painter. This controls whether the painter shall adjust its + fixes/workarounds optimized for certain output devices. +*/ +void QCPPainter::setMode(QCPPainter::PainterMode mode, bool enabled) +{ + if (!enabled && mModes.testFlag(mode)) + mModes &= ~mode; + else if (enabled && !mModes.testFlag(mode)) + mModes |= mode; +} + +/*! + Saves the painter (see QPainter::save). Since QCPPainter adds some new internal state to + QPainter, the save/restore functions are reimplemented to also save/restore those members. + + \note this function hides the non-virtual base class implementation. + + \see restore +*/ +void QCPPainter::save() +{ + mAntialiasingStack.push(mIsAntialiasing); + QPainter::save(); +} + +/*! + Restores the painter (see QPainter::restore). Since QCPPainter adds some new internal state to + QPainter, the save/restore functions are reimplemented to also save/restore those members. + + \note this function hides the non-virtual base class implementation. + + \see save +*/ +void QCPPainter::restore() +{ + if (!mAntialiasingStack.isEmpty()) + mIsAntialiasing = mAntialiasingStack.pop(); + else + qDebug() << Q_FUNC_INFO << "Unbalanced save/restore"; + QPainter::restore(); +} + +/*! + Changes the pen width to 1 if it currently is 0. This function is called in the \ref setPen + overrides when the \ref pmNonCosmetic mode is set. +*/ +void QCPPainter::makeNonCosmetic() +{ + if (qFuzzyIsNull(pen().widthF())) + { + QPen p = pen(); + p.setWidth(1); + QPainter::setPen(p); + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPScatterStyle +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPScatterStyle + \brief Represents the visual appearance of scatter points + + This class holds information about shape, color and size of scatter points. In plottables like + QCPGraph it is used to store how scatter points shall be drawn. For example, \ref + QCPGraph::setScatterStyle takes a QCPScatterStyle instance. + + A scatter style consists of a shape (\ref setShape), a line color (\ref setPen) and possibly a + fill (\ref setBrush), if the shape provides a fillable area. Further, the size of the shape can + be controlled with \ref setSize. + + \section QCPScatterStyle-defining Specifying a scatter style + + You can set all these configurations either by calling the respective functions on an instance: + \code + QCPScatterStyle myScatter; + myScatter.setShape(QCPScatterStyle::ssCircle); + myScatter.setPen(Qt::blue); + myScatter.setBrush(Qt::white); + myScatter.setSize(5); + customPlot->graph(0)->setScatterStyle(myScatter); + \endcode + + Or you can use one of the various constructors that take different parameter combinations, making + it easy to specify a scatter style in a single call, like so: + \code + customPlot->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, Qt::white, 5)); + \endcode + + \section QCPScatterStyle-undefinedpen Leaving the color/pen up to the plottable + + There are two constructors which leave the pen undefined: \ref QCPScatterStyle() and \ref + QCPScatterStyle(ScatterShape shape, double size). If those constructors are used, a call to \ref + isPenDefined will return false. It leads to scatter points that inherit the pen from the + plottable that uses the scatter style. Thus, if such a scatter style is passed to QCPGraph, the line + color of the graph (\ref QCPGraph::setPen) will be used by the scatter points. This makes + it very convenient to set up typical scatter settings: + + \code + customPlot->graph(0)->setScatterStyle(QCPScatterStyle::ssPlus); + \endcode + + Notice that it wasn't even necessary to explicitly call a QCPScatterStyle constructor. This works + because QCPScatterStyle provides a constructor that can transform a \ref ScatterShape directly + into a QCPScatterStyle instance (that's the \ref QCPScatterStyle(ScatterShape shape, double size) + constructor with a default for \a size). In those cases, C++ allows directly supplying a \ref + ScatterShape, where actually a QCPScatterStyle is expected. + + \section QCPScatterStyle-custompath-and-pixmap Custom shapes and pixmaps + + QCPScatterStyle supports drawing custom shapes and arbitrary pixmaps as scatter points. + + For custom shapes, you can provide a QPainterPath with the desired shape to the \ref + setCustomPath function or call the constructor that takes a painter path. The scatter shape will + automatically be set to \ref ssCustom. + + For pixmaps, you call \ref setPixmap with the desired QPixmap. Alternatively you can use the + constructor that takes a QPixmap. The scatter shape will automatically be set to \ref ssPixmap. + Note that \ref setSize does not influence the appearance of the pixmap. +*/ + +/* start documentation of inline functions */ + +/*! \fn bool QCPScatterStyle::isNone() const + + Returns whether the scatter shape is \ref ssNone. + + \see setShape +*/ + +/*! \fn bool QCPScatterStyle::isPenDefined() const + + Returns whether a pen has been defined for this scatter style. + + The pen is undefined if a constructor is called that does not carry \a pen as parameter. Those are + \ref QCPScatterStyle() and \ref QCPScatterStyle(ScatterShape shape, double size). If the pen is + left undefined, the scatter color will be inherited from the plottable that uses this scatter + style. + + \see setPen +*/ + +/* end documentation of inline functions */ + +/*! + Creates a new QCPScatterStyle instance with size set to 6. No shape, pen or brush is defined. + + Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited + from the plottable that uses this scatter style. +*/ +QCPScatterStyle::QCPScatterStyle() : + mSize(6), + mShape(ssNone), + mPen(Qt::NoPen), + mBrush(Qt::NoBrush), + mPenDefined(false) +{ +} + +/*! + Creates a new QCPScatterStyle instance with shape set to \a shape and size to \a size. No pen or + brush is defined. + + Since the pen is undefined (\ref isPenDefined returns false), the scatter color will be inherited + from the plottable that uses this scatter style. +*/ +QCPScatterStyle::QCPScatterStyle(ScatterShape shape, double size) : + mSize(size), + mShape(shape), + mPen(Qt::NoPen), + mBrush(Qt::NoBrush), + mPenDefined(false) +{ +} + +/*! + Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color, + and size to \a size. No brush is defined, i.e. the scatter point will not be filled. +*/ +QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, double size) : + mSize(size), + mShape(shape), + mPen(QPen(color)), + mBrush(Qt::NoBrush), + mPenDefined(true) +{ +} + +/*! + Creates a new QCPScatterStyle instance with shape set to \a shape, the pen color set to \a color, + the brush color to \a fill (with a solid pattern), and size to \a size. +*/ +QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) : + mSize(size), + mShape(shape), + mPen(QPen(color)), + mBrush(QBrush(fill)), + mPenDefined(true) +{ +} + +/*! + Creates a new QCPScatterStyle instance with shape set to \a shape, the pen set to \a pen, the + brush to \a brush, and size to \a size. + + \warning In some cases it might be tempting to directly use a pen style like Qt::NoPen as \a pen + and a color like Qt::blue as \a brush. Notice however, that the corresponding call\n + QCPScatterStyle(QCPScatterShape::ssCircle, Qt::NoPen, Qt::blue, 5)\n + doesn't necessarily lead C++ to use this constructor in some cases, but might mistake + Qt::NoPen for a QColor and use the + \ref QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size) + constructor instead (which will lead to an unexpected look of the scatter points). To prevent + this, be more explicit with the parameter types. For example, use QBrush(Qt::blue) + instead of just Qt::blue, to clearly point out to the compiler that this constructor is + wanted. +*/ +QCPScatterStyle::QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size) : + mSize(size), + mShape(shape), + mPen(pen), + mBrush(brush), + mPenDefined(pen.style() != Qt::NoPen) +{ +} + +/*! + Creates a new QCPScatterStyle instance which will show the specified \a pixmap. The scatter shape + is set to \ref ssPixmap. +*/ +QCPScatterStyle::QCPScatterStyle(const QPixmap &pixmap) : + mSize(5), + mShape(ssPixmap), + mPen(Qt::NoPen), + mBrush(Qt::NoBrush), + mPixmap(pixmap), + mPenDefined(false) +{ +} + +/*! + Creates a new QCPScatterStyle instance with a custom shape that is defined via \a customPath. The + scatter shape is set to \ref ssCustom. + + The custom shape line will be drawn with \a pen and filled with \a brush. The size has a slightly + different meaning than for built-in scatter points: The custom path will be drawn scaled by a + factor of \a size/6.0. Since the default \a size is 6, the custom path will appear at a its + natural size by default. To double the size of the path for example, set \a size to 12. +*/ +QCPScatterStyle::QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush, double size) : + mSize(size), + mShape(ssCustom), + mPen(pen), + mBrush(brush), + mCustomPath(customPath), + mPenDefined(pen.style() != Qt::NoPen) +{ +} + +/*! + Sets the size (pixel diameter) of the drawn scatter points to \a size. + + \see setShape +*/ +void QCPScatterStyle::setSize(double size) +{ + mSize = size; +} + +/*! + Sets the shape to \a shape. + + Note that the calls \ref setPixmap and \ref setCustomPath automatically set the shape to \ref + ssPixmap and \ref ssCustom, respectively. + + \see setSize +*/ +void QCPScatterStyle::setShape(QCPScatterStyle::ScatterShape shape) +{ + mShape = shape; +} + +/*! + Sets the pen that will be used to draw scatter points to \a pen. + + If the pen was previously undefined (see \ref isPenDefined), the pen is considered defined after + a call to this function, even if \a pen is Qt::NoPen. + + \see setBrush +*/ +void QCPScatterStyle::setPen(const QPen &pen) +{ + mPenDefined = true; + mPen = pen; +} + +/*! + Sets the brush that will be used to fill scatter points to \a brush. Note that not all scatter + shapes have fillable areas. For example, \ref ssPlus does not while \ref ssCircle does. + + \see setPen +*/ +void QCPScatterStyle::setBrush(const QBrush &brush) +{ + mBrush = brush; +} + +/*! + Sets the pixmap that will be drawn as scatter point to \a pixmap. + + Note that \ref setSize does not influence the appearance of the pixmap. + + The scatter shape is automatically set to \ref ssPixmap. +*/ +void QCPScatterStyle::setPixmap(const QPixmap &pixmap) +{ + setShape(ssPixmap); + mPixmap = pixmap; +} + +/*! + Sets the custom shape that will be drawn as scatter point to \a customPath. + + The scatter shape is automatically set to \ref ssCustom. +*/ +void QCPScatterStyle::setCustomPath(const QPainterPath &customPath) +{ + setShape(ssCustom); + mCustomPath = customPath; +} + +/*! + Applies the pen and the brush of this scatter style to \a painter. If this scatter style has an + undefined pen (\ref isPenDefined), sets the pen of \a painter to \a defaultPen instead. + + This function is used by plottables (or any class that wants to draw scatters) just before a + number of scatters with this style shall be drawn with the \a painter. + + \see drawShape +*/ +void QCPScatterStyle::applyTo(QCPPainter *painter, const QPen &defaultPen) const +{ + painter->setPen(mPenDefined ? mPen : defaultPen); + painter->setBrush(mBrush); +} + +/*! + Draws the scatter shape with \a painter at position \a pos. + + This function does not modify the pen or the brush on the painter, as \ref applyTo is meant to be + called before scatter points are drawn with \ref drawShape. + + \see applyTo +*/ +void QCPScatterStyle::drawShape(QCPPainter *painter, QPointF pos) const +{ + drawShape(painter, pos.x(), pos.y()); +} + +/*! \overload + Draws the scatter shape with \a painter at position \a x and \a y. +*/ +void QCPScatterStyle::drawShape(QCPPainter *painter, double x, double y) const +{ + double w = mSize/2.0; + switch (mShape) + { + case ssNone: break; + case ssDot: + { + painter->drawLine(QPointF(x, y), QPointF(x+0.0001, y)); + break; + } + case ssCross: + { + painter->drawLine(QLineF(x-w, y-w, x+w, y+w)); + painter->drawLine(QLineF(x-w, y+w, x+w, y-w)); + break; + } + case ssPlus: + { + painter->drawLine(QLineF(x-w, y, x+w, y)); + painter->drawLine(QLineF( x, y+w, x, y-w)); + break; + } + case ssCircle: + { + painter->drawEllipse(QPointF(x , y), w, w); + break; + } + case ssDisc: + { + QBrush b = painter->brush(); + painter->setBrush(painter->pen().color()); + painter->drawEllipse(QPointF(x , y), w, w); + painter->setBrush(b); + break; + } + case ssSquare: + { + painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); + break; + } + case ssDiamond: + { + painter->drawLine(QLineF(x-w, y, x, y-w)); + painter->drawLine(QLineF( x, y-w, x+w, y)); + painter->drawLine(QLineF(x+w, y, x, y+w)); + painter->drawLine(QLineF( x, y+w, x-w, y)); + break; + } + case ssStar: + { + painter->drawLine(QLineF(x-w, y, x+w, y)); + painter->drawLine(QLineF( x, y+w, x, y-w)); + painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.707, y+w*0.707)); + painter->drawLine(QLineF(x-w*0.707, y+w*0.707, x+w*0.707, y-w*0.707)); + break; + } + case ssTriangle: + { + painter->drawLine(QLineF(x-w, y+0.755*w, x+w, y+0.755*w)); + painter->drawLine(QLineF(x+w, y+0.755*w, x, y-0.977*w)); + painter->drawLine(QLineF( x, y-0.977*w, x-w, y+0.755*w)); + break; + } + case ssTriangleInverted: + { + painter->drawLine(QLineF(x-w, y-0.755*w, x+w, y-0.755*w)); + painter->drawLine(QLineF(x+w, y-0.755*w, x, y+0.977*w)); + painter->drawLine(QLineF( x, y+0.977*w, x-w, y-0.755*w)); + break; + } + case ssCrossSquare: + { + painter->drawLine(QLineF(x-w, y-w, x+w*0.95, y+w*0.95)); + painter->drawLine(QLineF(x-w, y+w*0.95, x+w*0.95, y-w)); + painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); + break; + } + case ssPlusSquare: + { + painter->drawLine(QLineF(x-w, y, x+w*0.95, y)); + painter->drawLine(QLineF( x, y+w, x, y-w)); + painter->drawRect(QRectF(x-w, y-w, mSize, mSize)); + break; + } + case ssCrossCircle: + { + painter->drawLine(QLineF(x-w*0.707, y-w*0.707, x+w*0.670, y+w*0.670)); + painter->drawLine(QLineF(x-w*0.707, y+w*0.670, x+w*0.670, y-w*0.707)); + painter->drawEllipse(QPointF(x, y), w, w); + break; + } + case ssPlusCircle: + { + painter->drawLine(QLineF(x-w, y, x+w, y)); + painter->drawLine(QLineF( x, y+w, x, y-w)); + painter->drawEllipse(QPointF(x, y), w, w); + break; + } + case ssPeace: + { + painter->drawLine(QLineF(x, y-w, x, y+w)); + painter->drawLine(QLineF(x, y, x-w*0.707, y+w*0.707)); + painter->drawLine(QLineF(x, y, x+w*0.707, y+w*0.707)); + painter->drawEllipse(QPointF(x, y), w, w); + break; + } + case ssPixmap: + { + painter->drawPixmap(x-mPixmap.width()*0.5, y-mPixmap.height()*0.5, mPixmap); + break; + } + case ssCustom: + { + QTransform oldTransform = painter->transform(); + painter->translate(x, y); + painter->scale(mSize/6.0, mSize/6.0); + painter->drawPath(mCustomPath); + painter->setTransform(oldTransform); + break; + } + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPLayer +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPLayer + \brief A layer that may contain objects, to control the rendering order + + The Layering system of QCustomPlot is the mechanism to control the rendering order of the + elements inside the plot. + + It is based on the two classes QCPLayer and QCPLayerable. QCustomPlot holds an ordered list of + one or more instances of QCPLayer (see QCustomPlot::addLayer, QCustomPlot::layer, + QCustomPlot::moveLayer, etc.). When replotting, QCustomPlot goes through the list of layers + bottom to top and successively draws the layerables of the layers. + + A QCPLayer contains an ordered list of QCPLayerable instances. QCPLayerable is an abstract base + class from which almost all visible objects derive, like axes, grids, graphs, items, etc. + + Initially, QCustomPlot has five layers: "background", "grid", "main", "axes" and "legend" (in + that order). The top two layers "axes" and "legend" contain the default axes and legend, so they + will be drawn on top. In the middle, there is the "main" layer. It is initially empty and set as + the current layer (see QCustomPlot::setCurrentLayer). This means, all new plottables, items etc. + are created on this layer by default. Then comes the "grid" layer which contains the QCPGrid + instances (which belong tightly to QCPAxis, see \ref QCPAxis::grid). The Axis rect background + shall be drawn behind everything else, thus the default QCPAxisRect instance is placed on the + "background" layer. Of course, the layer affiliation of the individual objects can be changed as + required (\ref QCPLayerable::setLayer). + + Controlling the ordering of objects is easy: Create a new layer in the position you want it to + be, e.g. above "main", with QCustomPlot::addLayer. Then set the current layer with + QCustomPlot::setCurrentLayer to that new layer and finally create the objects normally. They will + be placed on the new layer automatically, due to the current layer setting. Alternatively you + could have also ignored the current layer setting and just moved the objects with + QCPLayerable::setLayer to the desired layer after creating them. + + It is also possible to move whole layers. For example, If you want the grid to be shown in front + of all plottables/items on the "main" layer, just move it above "main" with + QCustomPlot::moveLayer. + + The rendering order within one layer is simply by order of creation or insertion. The item + created last (or added last to the layer), is drawn on top of all other objects on that layer. + + When a layer is deleted, the objects on it are not deleted with it, but fall on the layer below + the deleted layer, see QCustomPlot::removeLayer. +*/ + +/* start documentation of inline functions */ + +/*! \fn QList QCPLayer::children() const + + Returns a list of all layerables on this layer. The order corresponds to the rendering order: + layerables with higher indices are drawn above layerables with lower indices. +*/ + +/*! \fn int QCPLayer::index() const + + Returns the index this layer has in the QCustomPlot. The index is the integer number by which this layer can be + accessed via \ref QCustomPlot::layer. + + Layers with higher indices will be drawn above layers with lower indices. +*/ + +/* end documentation of inline functions */ + +/*! + Creates a new QCPLayer instance. + + Normally you shouldn't directly instantiate layers, use \ref QCustomPlot::addLayer instead. + + \warning It is not checked that \a layerName is actually a unique layer name in \a parentPlot. + This check is only performed by \ref QCustomPlot::addLayer. +*/ +QCPLayer::QCPLayer(QCustomPlot *parentPlot, const QString &layerName) : + QObject(parentPlot), + mParentPlot(parentPlot), + mName(layerName), + mIndex(-1), // will be set to a proper value by the QCustomPlot layer creation function + mVisible(true) +{ + // Note: no need to make sure layerName is unique, because layer + // management is done with QCustomPlot functions. +} + +QCPLayer::~QCPLayer() +{ + // If child layerables are still on this layer, detach them, so they don't try to reach back to this + // then invalid layer once they get deleted/moved themselves. This only happens when layers are deleted + // directly, like in the QCustomPlot destructor. (The regular layer removal procedure for the user is to + // call QCustomPlot::removeLayer, which moves all layerables off this layer before deleting it.) + + while (!mChildren.isEmpty()) + mChildren.last()->setLayer(0); // removes itself from mChildren via removeChild() + + if (mParentPlot->currentLayer() == this) + qDebug() << Q_FUNC_INFO << "The parent plot's mCurrentLayer will be a dangling pointer. Should have been set to a valid layer or 0 beforehand."; +} + +/*! + Sets whether this layer is visible or not. If \a visible is set to false, all layerables on this + layer will be invisible. + + This function doesn't change the visibility property of the layerables (\ref + QCPLayerable::setVisible), but the \ref QCPLayerable::realVisibility of each layerable takes the + visibility of the parent layer into account. +*/ +void QCPLayer::setVisible(bool visible) +{ + mVisible = visible; +} + +/*! \internal + + Adds the \a layerable to the list of this layer. If \a prepend is set to true, the layerable will + be prepended to the list, i.e. be drawn beneath the other layerables already in the list. + + This function does not change the \a mLayer member of \a layerable to this layer. (Use + QCPLayerable::setLayer to change the layer of an object, not this function.) + + \see removeChild +*/ +void QCPLayer::addChild(QCPLayerable *layerable, bool prepend) +{ + if (!mChildren.contains(layerable)) + { + if (prepend) + mChildren.prepend(layerable); + else + mChildren.append(layerable); + } else + qDebug() << Q_FUNC_INFO << "layerable is already child of this layer" << reinterpret_cast(layerable); +} + +/*! \internal + + Removes the \a layerable from the list of this layer. + + This function does not change the \a mLayer member of \a layerable. (Use QCPLayerable::setLayer + to change the layer of an object, not this function.) + + \see addChild +*/ +void QCPLayer::removeChild(QCPLayerable *layerable) +{ + if (!mChildren.removeOne(layerable)) + qDebug() << Q_FUNC_INFO << "layerable is not child of this layer" << reinterpret_cast(layerable); +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPLayerable +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPLayerable + \brief Base class for all drawable objects + + This is the abstract base class most visible objects derive from, e.g. plottables, axes, grid + etc. + + Every layerable is on a layer (QCPLayer) which allows controlling the rendering order by stacking + the layers accordingly. + + For details about the layering mechanism, see the QCPLayer documentation. +*/ + +/* start documentation of inline functions */ + +/*! \fn QCPLayerable *QCPLayerable::parentLayerable() const + + Returns the parent layerable of this layerable. The parent layerable is used to provide + visibility hierarchies in conjunction with the method \ref realVisibility. This way, layerables + only get drawn if their parent layerables are visible, too. + + Note that a parent layerable is not necessarily also the QObject parent for memory management. + Further, a layerable doesn't always have a parent layerable, so this function may return 0. + + A parent layerable is set implicitly with when placed inside layout elements and doesn't need to be + set manually by the user. +*/ + +/* end documentation of inline functions */ +/* start documentation of pure virtual functions */ + +/*! \fn virtual void QCPLayerable::applyDefaultAntialiasingHint(QCPPainter *painter) const = 0 + \internal + + This function applies the default antialiasing setting to the specified \a painter, using the + function \ref applyAntialiasingHint. It is the antialiasing state the painter is put in, when + \ref draw is called on the layerable. If the layerable has multiple entities whose antialiasing + setting may be specified individually, this function should set the antialiasing state of the + most prominent entity. In this case however, the \ref draw function usually calls the specialized + versions of this function before drawing each entity, effectively overriding the setting of the + default antialiasing hint. + + First example: QCPGraph has multiple entities that have an antialiasing setting: The graph + line, fills, scatters and error bars. Those can be configured via QCPGraph::setAntialiased, + QCPGraph::setAntialiasedFill, QCPGraph::setAntialiasedScatters etc. Consequently, there isn't + only the QCPGraph::applyDefaultAntialiasingHint function (which corresponds to the graph line's + antialiasing), but specialized ones like QCPGraph::applyFillAntialiasingHint and + QCPGraph::applyScattersAntialiasingHint. So before drawing one of those entities, QCPGraph::draw + calls the respective specialized applyAntialiasingHint function. + + Second example: QCPItemLine consists only of a line so there is only one antialiasing + setting which can be controlled with QCPItemLine::setAntialiased. (This function is inherited by + all layerables. The specialized functions, as seen on QCPGraph, must be added explicitly to the + respective layerable subclass.) Consequently it only has the normal + QCPItemLine::applyDefaultAntialiasingHint. The \ref QCPItemLine::draw function doesn't need to + care about setting any antialiasing states, because the default antialiasing hint is already set + on the painter when the \ref draw function is called, and that's the state it wants to draw the + line with. +*/ + +/*! \fn virtual void QCPLayerable::draw(QCPPainter *painter) const = 0 + \internal + + This function draws the layerable with the specified \a painter. It is only called by + QCustomPlot, if the layerable is visible (\ref setVisible). + + Before this function is called, the painter's antialiasing state is set via \ref + applyDefaultAntialiasingHint, see the documentation there. Further, the clipping rectangle was + set to \ref clipRect. +*/ + +/* end documentation of pure virtual functions */ +/* start documentation of signals */ + +/*! \fn void QCPLayerable::layerChanged(QCPLayer *newLayer); + + This signal is emitted when the layer of this layerable changes, i.e. this layerable is moved to + a different layer. + + \see setLayer +*/ + +/* end documentation of signals */ + +/*! + Creates a new QCPLayerable instance. + + Since QCPLayerable is an abstract base class, it can't be instantiated directly. Use one of the + derived classes. + + If \a plot is provided, it automatically places itself on the layer named \a targetLayer. If \a + targetLayer is an empty string, it places itself on the current layer of the plot (see \ref + QCustomPlot::setCurrentLayer). + + It is possible to provide 0 as \a plot. In that case, you should assign a parent plot at a later + time with \ref initializeParentPlot. + + The layerable's parent layerable is set to \a parentLayerable, if provided. Direct layerable parents + are mainly used to control visibility in a hierarchy of layerables. This means a layerable is + only drawn, if all its ancestor layerables are also visible. Note that \a parentLayerable does + not become the QObject-parent (for memory management) of this layerable, \a plot does. +*/ +QCPLayerable::QCPLayerable(QCustomPlot *plot, QString targetLayer, QCPLayerable *parentLayerable) : + QObject(plot), + mVisible(true), + mParentPlot(plot), + mParentLayerable(parentLayerable), + mLayer(0), + mAntialiased(true) +{ + if (mParentPlot) + { + if (targetLayer.isEmpty()) + setLayer(mParentPlot->currentLayer()); + else if (!setLayer(targetLayer)) + qDebug() << Q_FUNC_INFO << "setting QCPlayerable initial layer to" << targetLayer << "failed."; + } +} + +QCPLayerable::~QCPLayerable() +{ + if (mLayer) + { + mLayer->removeChild(this); + mLayer = 0; + } +} + +/*! + Sets the visibility of this layerable object. If an object is not visible, it will not be drawn + on the QCustomPlot surface, and user interaction with it (e.g. click and selection) is not + possible. +*/ +void QCPLayerable::setVisible(bool on) +{ + mVisible = on; +} + +/*! + Sets the \a layer of this layerable object. The object will be placed on top of the other objects + already on \a layer. + + Returns true on success, i.e. if \a layer is a valid layer. +*/ +bool QCPLayerable::setLayer(QCPLayer *layer) +{ + return moveToLayer(layer, false); +} + +/*! \overload + Sets the layer of this layerable object by name + + Returns true on success, i.e. if \a layerName is a valid layer name. +*/ +bool QCPLayerable::setLayer(const QString &layerName) +{ + if (!mParentPlot) + { + qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; + return false; + } + if (QCPLayer *layer = mParentPlot->layer(layerName)) + { + return setLayer(layer); + } else + { + qDebug() << Q_FUNC_INFO << "there is no layer with name" << layerName; + return false; + } +} + +/*! + Sets whether this object will be drawn antialiased or not. + + Note that antialiasing settings may be overridden by QCustomPlot::setAntialiasedElements and + QCustomPlot::setNotAntialiasedElements. +*/ +void QCPLayerable::setAntialiased(bool enabled) +{ + mAntialiased = enabled; +} + +/*! + Returns whether this layerable is visible, taking the visibility of the layerable parent and the + visibility of the layer this layerable is on into account. This is the method that is consulted + to decide whether a layerable shall be drawn or not. + + If this layerable has a direct layerable parent (usually set via hierarchies implemented in + subclasses, like in the case of QCPLayoutElement), this function returns true only if this + layerable has its visibility set to true and the parent layerable's \ref realVisibility returns + true. + + If this layerable doesn't have a direct layerable parent, returns the state of this layerable's + visibility. +*/ +bool QCPLayerable::realVisibility() const +{ + return mVisible && (!mLayer || mLayer->visible()) && (!mParentLayerable || mParentLayerable.data()->realVisibility()); +} + +/*! + This function is used to decide whether a click hits a layerable object or not. + + \a pos is a point in pixel coordinates on the QCustomPlot surface. This function returns the + shortest pixel distance of this point to the object. If the object is either invisible or the + distance couldn't be determined, -1.0 is returned. Further, if \a onlySelectable is true and the + object is not selectable, -1.0 is returned, too. + + If the item is represented not by single lines but by an area like QCPItemRect or QCPItemText, a + click inside the area returns a constant value greater zero (typically the selectionTolerance of + the parent QCustomPlot multiplied by 0.99). If the click lies outside the area, this function + returns -1.0. + + Providing a constant value for area objects allows selecting line objects even when they are + obscured by such area objects, by clicking close to the lines (i.e. closer than + 0.99*selectionTolerance). + + The actual setting of the selection state is not done by this function. This is handled by the + parent QCustomPlot when the mouseReleaseEvent occurs, and the finally selected object is notified + via the selectEvent/deselectEvent methods. + + \a details is an optional output parameter. Every layerable subclass may place any information + in \a details. This information will be passed to \ref selectEvent when the parent QCustomPlot + decides on the basis of this selectTest call, that the object was successfully selected. The + subsequent call to \ref selectEvent will carry the \a details. This is useful for multi-part + objects (like QCPAxis). This way, a possibly complex calculation to decide which part was clicked + is only done once in \ref selectTest. The result (i.e. the actually clicked part) can then be + placed in \a details. So in the subsequent \ref selectEvent, the decision which part was + selected doesn't have to be done a second time for a single selection operation. + + You may pass 0 as \a details to indicate that you are not interested in those selection details. + + \see selectEvent, deselectEvent, QCustomPlot::setInteractions +*/ +double QCPLayerable::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(pos) + Q_UNUSED(onlySelectable) + Q_UNUSED(details) + return -1.0; +} + +/*! \internal + + Sets the parent plot of this layerable. Use this function once to set the parent plot if you have + passed 0 in the constructor. It can not be used to move a layerable from one QCustomPlot to + another one. + + Note that, unlike when passing a non-null parent plot in the constructor, this function does not + make \a parentPlot the QObject-parent of this layerable. If you want this, call + QObject::setParent(\a parentPlot) in addition to this function. + + Further, you will probably want to set a layer (\ref setLayer) after calling this function, to + make the layerable appear on the QCustomPlot. + + The parent plot change will be propagated to subclasses via a call to \ref parentPlotInitialized + so they can react accordingly (e.g. also initialize the parent plot of child layerables, like + QCPLayout does). +*/ +void QCPLayerable::initializeParentPlot(QCustomPlot *parentPlot) +{ + if (mParentPlot) + { + qDebug() << Q_FUNC_INFO << "called with mParentPlot already initialized"; + return; + } + + if (!parentPlot) + qDebug() << Q_FUNC_INFO << "called with parentPlot zero"; + + mParentPlot = parentPlot; + parentPlotInitialized(mParentPlot); +} + +/*! \internal + + Sets the parent layerable of this layerable to \a parentLayerable. Note that \a parentLayerable does not + become the QObject-parent (for memory management) of this layerable. + + The parent layerable has influence on the return value of the \ref realVisibility method. Only + layerables with a fully visible parent tree will return true for \ref realVisibility, and thus be + drawn. + + \see realVisibility +*/ +void QCPLayerable::setParentLayerable(QCPLayerable *parentLayerable) +{ + mParentLayerable = parentLayerable; +} + +/*! \internal + + Moves this layerable object to \a layer. If \a prepend is true, this object will be prepended to + the new layer's list, i.e. it will be drawn below the objects already on the layer. If it is + false, the object will be appended. + + Returns true on success, i.e. if \a layer is a valid layer. +*/ +bool QCPLayerable::moveToLayer(QCPLayer *layer, bool prepend) +{ + if (layer && !mParentPlot) + { + qDebug() << Q_FUNC_INFO << "no parent QCustomPlot set"; + return false; + } + if (layer && layer->parentPlot() != mParentPlot) + { + qDebug() << Q_FUNC_INFO << "layer" << layer->name() << "is not in same QCustomPlot as this layerable"; + return false; + } + + QCPLayer *oldLayer = mLayer; + if (mLayer) + mLayer->removeChild(this); + mLayer = layer; + if (mLayer) + mLayer->addChild(this, prepend); + if (mLayer != oldLayer) + emit layerChanged(mLayer); + return true; +} + +/*! \internal + + Sets the QCPainter::setAntialiasing state on the provided \a painter, depending on the \a + localAntialiased value as well as the overrides \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. Which override enum this function takes into account is + controlled via \a overrideElement. +*/ +void QCPLayerable::applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const +{ + if (mParentPlot && mParentPlot->notAntialiasedElements().testFlag(overrideElement)) + painter->setAntialiasing(false); + else if (mParentPlot && mParentPlot->antialiasedElements().testFlag(overrideElement)) + painter->setAntialiasing(true); + else + painter->setAntialiasing(localAntialiased); +} + +/*! \internal + + This function is called by \ref initializeParentPlot, to allow subclasses to react on the setting + of a parent plot. This is the case when 0 was passed as parent plot in the constructor, and the + parent plot is set at a later time. + + For example, QCPLayoutElement/QCPLayout hierarchies may be created independently of any + QCustomPlot at first. When they are then added to a layout inside the QCustomPlot, the top level + element of the hierarchy gets its parent plot initialized with \ref initializeParentPlot. To + propagate the parent plot to all the children of the hierarchy, the top level element then uses + this function to pass the parent plot on to its child elements. + + The default implementation does nothing. + + \see initializeParentPlot +*/ +void QCPLayerable::parentPlotInitialized(QCustomPlot *parentPlot) +{ + Q_UNUSED(parentPlot) +} + +/*! \internal + + Returns the selection category this layerable shall belong to. The selection category is used in + conjunction with \ref QCustomPlot::setInteractions to control which objects are selectable and + which aren't. + + Subclasses that don't fit any of the normal \ref QCP::Interaction values can use \ref + QCP::iSelectOther. This is what the default implementation returns. + + \see QCustomPlot::setInteractions +*/ +QCP::Interaction QCPLayerable::selectionCategory() const +{ + return QCP::iSelectOther; +} + +/*! \internal + + Returns the clipping rectangle of this layerable object. By default, this is the viewport of the + parent QCustomPlot. Specific subclasses may reimplement this function to provide different + clipping rects. + + The returned clipping rect is set on the painter before the draw function of the respective + object is called. +*/ +QRect QCPLayerable::clipRect() const +{ + if (mParentPlot) + return mParentPlot->viewport(); + else + return QRect(); +} + +/*! \internal + + This event is called when the layerable shall be selected, as a consequence of a click by the + user. Subclasses should react to it by setting their selection state appropriately. The default + implementation does nothing. + + \a event is the mouse event that caused the selection. \a additive indicates, whether the user + was holding the multi-select-modifier while performing the selection (see \ref + QCustomPlot::setMultiSelectModifier). if \a additive is true, the selection state must be toggled + (i.e. become selected when unselected and unselected when selected). + + Every selectEvent is preceded by a call to \ref selectTest, which has returned positively (i.e. + returned a value greater than 0 and less than the selection tolerance of the parent QCustomPlot). + The \a details data you output from \ref selectTest is fed back via \a details here. You may + use it to transport any kind of information from the selectTest to the possibly subsequent + selectEvent. Usually \a details is used to transfer which part was clicked, if it is a layerable + that has multiple individually selectable parts (like QCPAxis). This way selectEvent doesn't need + to do the calculation again to find out which part was actually clicked. + + \a selectionStateChanged is an output parameter. If the pointer is non-null, this function must + set the value either to true or false, depending on whether the selection state of this layerable + was actually changed. For layerables that only are selectable as a whole and not in parts, this + is simple: if \a additive is true, \a selectionStateChanged must also be set to true, because the + selection toggles. If \a additive is false, \a selectionStateChanged is only set to true, if the + layerable was previously unselected and now is switched to the selected state. + + \see selectTest, deselectEvent +*/ +void QCPLayerable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +{ + Q_UNUSED(event) + Q_UNUSED(additive) + Q_UNUSED(details) + Q_UNUSED(selectionStateChanged) +} + +/*! \internal + + This event is called when the layerable shall be deselected, either as consequence of a user + interaction or a call to \ref QCustomPlot::deselectAll. Subclasses should react to it by + unsetting their selection appropriately. + + just as in \ref selectEvent, the output parameter \a selectionStateChanged (if non-null), must + return true or false when the selection state of this layerable has changed or not changed, + respectively. + + \see selectTest, selectEvent +*/ +void QCPLayerable::deselectEvent(bool *selectionStateChanged) +{ + Q_UNUSED(selectionStateChanged) +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPRange +//////////////////////////////////////////////////////////////////////////////////////////////////// +/*! \class QCPRange + \brief Represents the range an axis is encompassing. + + contains a \a lower and \a upper double value and provides convenience input, output and + modification functions. + + \see QCPAxis::setRange +*/ + +/*! + Minimum range size (\a upper - \a lower) the range changing functions will accept. Smaller + intervals would cause errors due to the 11-bit exponent of double precision numbers, + corresponding to a minimum magnitude of roughly 1e-308. + \see validRange, maxRange +*/ +const double QCPRange::minRange = 1e-280; + +/*! + Maximum values (negative and positive) the range will accept in range-changing functions. + Larger absolute values would cause errors due to the 11-bit exponent of double precision numbers, + corresponding to a maximum magnitude of roughly 1e308. + Since the number of planck-volumes in the entire visible universe is only ~1e183, this should + be enough. + \see validRange, minRange +*/ +const double QCPRange::maxRange = 1e250; + +/*! + Constructs a range with \a lower and \a upper set to zero. +*/ +QCPRange::QCPRange() : + lower(0), + upper(0) +{ +} + +/*! \overload + Constructs a range with the specified \a lower and \a upper values. +*/ +QCPRange::QCPRange(double lower, double upper) : + lower(lower), + upper(upper) +{ + normalize(); +} + +/*! + Returns the size of the range, i.e. \a upper-\a lower +*/ +double QCPRange::size() const +{ + return upper-lower; +} + +/*! + Returns the center of the range, i.e. (\a upper+\a lower)*0.5 +*/ +double QCPRange::center() const +{ + return (upper+lower)*0.5; +} + +/*! + Makes sure \a lower is numerically smaller than \a upper. If this is not the case, the values + are swapped. +*/ +void QCPRange::normalize() +{ + if (lower > upper) + qSwap(lower, upper); +} + +/*! + Expands this range such that \a otherRange is contained in the new range. It is assumed that both + this range and \a otherRange are normalized (see \ref normalize). + + If \a otherRange is already inside the current range, this function does nothing. + + \see expanded +*/ +void QCPRange::expand(const QCPRange &otherRange) +{ + if (lower > otherRange.lower) + lower = otherRange.lower; + if (upper < otherRange.upper) + upper = otherRange.upper; +} + + +/*! + Returns an expanded range that contains this and \a otherRange. It is assumed that both this + range and \a otherRange are normalized (see \ref normalize). + + \see expand +*/ +QCPRange QCPRange::expanded(const QCPRange &otherRange) const +{ + QCPRange result = *this; + result.expand(otherRange); + return result; +} + +/*! + Returns a sanitized version of the range. Sanitized means for logarithmic scales, that + the range won't span the positive and negative sign domain, i.e. contain zero. Further + \a lower will always be numerically smaller (or equal) to \a upper. + + If the original range does span positive and negative sign domains or contains zero, + the returned range will try to approximate the original range as good as possible. + If the positive interval of the original range is wider than the negative interval, the + returned range will only contain the positive interval, with lower bound set to \a rangeFac or + \a rangeFac *\a upper, whichever is closer to zero. Same procedure is used if the negative interval + is wider than the positive interval, this time by changing the \a upper bound. +*/ +QCPRange QCPRange::sanitizedForLogScale() const +{ + double rangeFac = 1e-3; + QCPRange sanitizedRange(lower, upper); + sanitizedRange.normalize(); + // can't have range spanning negative and positive values in log plot, so change range to fix it + //if (qFuzzyCompare(sanitizedRange.lower+1, 1) && !qFuzzyCompare(sanitizedRange.upper+1, 1)) + if (sanitizedRange.lower == 0.0 && sanitizedRange.upper != 0.0) + { + // case lower is 0 + if (rangeFac < sanitizedRange.upper*rangeFac) + sanitizedRange.lower = rangeFac; + else + sanitizedRange.lower = sanitizedRange.upper*rangeFac; + } //else if (!qFuzzyCompare(lower+1, 1) && qFuzzyCompare(upper+1, 1)) + else if (sanitizedRange.lower != 0.0 && sanitizedRange.upper == 0.0) + { + // case upper is 0 + if (-rangeFac > sanitizedRange.lower*rangeFac) + sanitizedRange.upper = -rangeFac; + else + sanitizedRange.upper = sanitizedRange.lower*rangeFac; + } else if (sanitizedRange.lower < 0 && sanitizedRange.upper > 0) + { + // find out whether negative or positive interval is wider to decide which sign domain will be chosen + if (-sanitizedRange.lower > sanitizedRange.upper) + { + // negative is wider, do same as in case upper is 0 + if (-rangeFac > sanitizedRange.lower*rangeFac) + sanitizedRange.upper = -rangeFac; + else + sanitizedRange.upper = sanitizedRange.lower*rangeFac; + } else + { + // positive is wider, do same as in case lower is 0 + if (rangeFac < sanitizedRange.upper*rangeFac) + sanitizedRange.lower = rangeFac; + else + sanitizedRange.lower = sanitizedRange.upper*rangeFac; + } + } + // due to normalization, case lower>0 && upper<0 should never occur, because that implies upper= lower && value <= upper; +} + +/*! + Checks, whether the specified range is within valid bounds, which are defined + as QCPRange::maxRange and QCPRange::minRange. + A valid range means: + \li range bounds within -maxRange and maxRange + \li range size above minRange + \li range size below maxRange +*/ +bool QCPRange::validRange(double lower, double upper) +{ + /* + return (lower > -maxRange && + upper < maxRange && + qAbs(lower-upper) > minRange && + (lower < -minRange || lower > minRange) && + (upper < -minRange || upper > minRange)); + */ + return (lower > -maxRange && + upper < maxRange && + qAbs(lower-upper) > minRange && + qAbs(lower-upper) < maxRange); +} + +/*! + \overload + Checks, whether the specified range is within valid bounds, which are defined + as QCPRange::maxRange and QCPRange::minRange. + A valid range means: + \li range bounds within -maxRange and maxRange + \li range size above minRange + \li range size below maxRange +*/ +bool QCPRange::validRange(const QCPRange &range) +{ + /* + return (range.lower > -maxRange && + range.upper < maxRange && + qAbs(range.lower-range.upper) > minRange && + qAbs(range.lower-range.upper) < maxRange && + (range.lower < -minRange || range.lower > minRange) && + (range.upper < -minRange || range.upper > minRange)); + */ + return (range.lower > -maxRange && + range.upper < maxRange && + qAbs(range.lower-range.upper) > minRange && + qAbs(range.lower-range.upper) < maxRange); +} + + +/*! \page thelayoutsystem The Layout System + + The layout system is responsible for positioning and scaling layout elements such as axis rects, + legends and plot titles in a QCustomPlot. + + \section layoutsystem-classesandmechanisms Classes and mechanisms + + The layout system is based on the abstract base class \ref QCPLayoutElement. All objects that + take part in the layout system derive from this class, either directly or indirectly. + + Since QCPLayoutElement itself derives from \ref QCPLayerable, a layout element may draw its own + content. However, it is perfectly possible for a layout element to only serve as a structuring + and/or positioning element, not drawing anything on its own. + + \subsection layoutsystem-rects Rects of a layout element + + A layout element is a rectangular object described by two rects: the inner rect (\ref + QCPLayoutElement::rect) and the outer rect (\ref QCPLayoutElement::setOuterRect). The inner rect + is calculated automatically by applying the margin (\ref QCPLayoutElement::setMargins) inward + from the outer rect. The inner rect is meant for main content while the margin area may either be + left blank or serve for displaying peripheral graphics. For example, \ref QCPAxisRect positions + the four main axes at the sides of the inner rect, so graphs end up inside it and the axis labels + and tick labels are in the margin area. + + \subsection layoutsystem-margins Margins + + Each layout element may provide a mechanism to automatically determine its margins. Internally, + this is realized with the \ref QCPLayoutElement::calculateAutoMargin function which takes a \ref + QCP::MarginSide and returns an integer value which represents the ideal margin for the specified + side. The automatic margin will be used on the sides specified in \ref + QCPLayoutElement::setAutoMargins. By default, it is set to \ref QCP::msAll meaning automatic + margin calculation is enabled for all four sides. In this case, a minimum margin may be set with + \ref QCPLayoutElement::setMinimumMargins, to prevent the automatic margin mechanism from setting + margins smaller than desired for a specific situation. If automatic margin calculation is unset + for a specific side, the margin of that side can be controlled directy via \ref + QCPLayoutElement::setMargins. + + If multiple layout ements are arranged next to or beneath each other, it may be desirable to + align their inner rects on certain sides. Since they all might have different automatic margins, + this usually isn't the case. The class \ref QCPMarginGroup and \ref + QCPLayoutElement::setMarginGroup fix this by allowing to synchronize multiple margins. See the + documentation there for details. + + \subsection layoutsystem-layout Layouts + + As mentioned, a QCPLayoutElement may have an arbitrary number of child layout elements and in + princple can have the only purpose to manage/arrange those child elements. This is what the + subclass \ref QCPLayout specializes on. It is a QCPLayoutElement itself but has no visual + representation. It defines an interface to add, remove and manage child layout elements. + QCPLayout isn't a usable layout though, it's an abstract base class that concrete layouts derive + from, like \ref QCPLayoutGrid which arranges its child elements in a grid and \ref QCPLayoutInset + which allows placing child elements freely inside its rect. + + Since a QCPLayout is a layout element itself, it may be placed inside other layouts. This way, + complex hierarchies may be created, offering very flexible arrangements. + + Below is a sketch of the default \ref QCPLayoutGrid accessible via \ref QCustomPlot::plotLayout. + It shows how two child layout elements are placed inside the grid layout next to each other in + cells (0, 0) and (0, 1). + + \image html LayoutsystemSketch.png + + \subsection layoutsystem-plotlayout The top level plot layout + + Every QCustomPlot has one top level layout of type \ref QCPLayoutGrid. It is accessible via \ref + QCustomPlot::plotLayout and contains (directly or indirectly via other sub-layouts) all layout + elements in the QCustomPlot. By default, this top level grid layout contains a single cell which + holds the main axis rect. + + \subsection layoutsystem-examples Examples + + Adding a plot title is a typical and simple case to demonstrate basic workings of the layout system. + \code + // first we create and prepare a plot title layout element: + QCPPlotTitle *title = new QCPPlotTitle(customPlot); + title->setText("Plot Title Example"); + title->setFont(QFont("sans", 12, QFont::Bold)); + // then we add it to the main plot layout: + customPlot->plotLayout()->insertRow(0); // insert an empty row above the axis rect + customPlot->plotLayout()->addElement(0, 0, title); // place the title in the empty cell we've just created + \endcode + \image html layoutsystem-addingplottitle.png + + Arranging multiple axis rects actually is the central purpose of the layout system. + \code + customPlot->plotLayout()->clear(); // let's start from scratch and remove the default axis rect + // add the first axis rect in second row (row index 1): + QCPAxisRect *bottomAxisRect = new QCPAxisRect(customPlot); + customPlot->plotLayout()->addElement(1, 0, bottomAxisRect); + // create a sub layout that we'll place in first row: + QCPLayoutGrid *subLayout = new QCPLayoutGrid; + customPlot->plotLayout()->addElement(0, 0, subLayout); + // add two axis rects in the sub layout next to each other: + QCPAxisRect *leftAxisRect = new QCPAxisRect(customPlot); + QCPAxisRect *rightAxisRect = new QCPAxisRect(customPlot); + subLayout->addElement(0, 0, leftAxisRect); + subLayout->addElement(0, 1, rightAxisRect); + subLayout->setColumnStretchFactor(0, 3); // left axis rect shall have 60% of width + subLayout->setColumnStretchFactor(1, 2); // right one only 40% (3:2 = 60:40) + // since we've created the axis rects and axes from scratch, we need to place them on + // according layers, if we don't want the grid to be drawn above the axes etc. + // place the axis on "axes" layer and grids on the "grid" layer, which is below "axes": + QList allAxes; + allAxes << bottomAxisRect->axes() << leftAxisRect->axes() << rightAxisRect->axes(); + foreach (QCPAxis *axis, allAxes) + { + axis->setLayer("axes"); + axis->grid()->setLayer("grid"); + } + \endcode + \image html layoutsystem-multipleaxisrects.png + +*/ + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPMarginGroup +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPMarginGroup + \brief A margin group allows synchronization of margin sides if working with multiple layout elements. + + QCPMarginGroup allows you to tie a margin side of two or more layout elements together, such that + they will all have the same size, based on the largest required margin in the group. + + \n + \image html QCPMarginGroup.png "Demonstration of QCPMarginGroup" + \n + + In certain situations it is desirable that margins at specific sides are synchronized across + layout elements. For example, if one QCPAxisRect is below another one in a grid layout, it will + provide a cleaner look to the user if the left and right margins of the two axis rects are of the + same size. The left axis of the top axis rect will then be at the same horizontal position as the + left axis of the lower axis rect, making them appear aligned. The same applies for the right + axes. This is what QCPMarginGroup makes possible. + + To add/remove a specific side of a layout element to/from a margin group, use the \ref + QCPLayoutElement::setMarginGroup method. To completely break apart the margin group, either call + \ref clear, or just delete the margin group. + + \section QCPMarginGroup-example Example + + First create a margin group: + \code + QCPMarginGroup *group = new QCPMarginGroup(customPlot); + \endcode + Then set this group on the layout element sides: + \code + customPlot->axisRect(0)->setMarginGroup(QCP::msLeft|QCP::msRight, group); + customPlot->axisRect(1)->setMarginGroup(QCP::msLeft|QCP::msRight, group); + \endcode + Here, we've used the first two axis rects of the plot and synchronized their left margins with + each other and their right margins with each other. +*/ + +/* start documentation of inline functions */ + +/*! \fn QList QCPMarginGroup::elements(QCP::MarginSide side) const + + Returns a list of all layout elements that have their margin \a side associated with this margin + group. +*/ + +/* end documentation of inline functions */ + +/*! + Creates a new QCPMarginGroup instance in \a parentPlot. +*/ +QCPMarginGroup::QCPMarginGroup(QCustomPlot *parentPlot) : + QObject(parentPlot), + mParentPlot(parentPlot) +{ + mChildren.insert(QCP::msLeft, QList()); + mChildren.insert(QCP::msRight, QList()); + mChildren.insert(QCP::msTop, QList()); + mChildren.insert(QCP::msBottom, QList()); +} + +QCPMarginGroup::~QCPMarginGroup() +{ + clear(); +} + +/*! + Returns whether this margin group is empty. If this function returns true, no layout elements use + this margin group to synchronize margin sides. +*/ +bool QCPMarginGroup::isEmpty() const +{ + QHashIterator > it(mChildren); + while (it.hasNext()) + { + it.next(); + if (!it.value().isEmpty()) + return false; + } + return true; +} + +/*! + Clears this margin group. The synchronization of the margin sides that use this margin group is + lifted and they will use their individual margin sizes again. +*/ +void QCPMarginGroup::clear() +{ + // make all children remove themselves from this margin group: + QHashIterator > it(mChildren); + while (it.hasNext()) + { + it.next(); + const QList elements = it.value(); + for (int i=elements.size()-1; i>=0; --i) + elements.at(i)->setMarginGroup(it.key(), 0); // removes itself from mChildren via removeChild + } +} + +/*! \internal + + Returns the synchronized common margin for \a side. This is the margin value that will be used by + the layout element on the respective side, if it is part of this margin group. + + The common margin is calculated by requesting the automatic margin (\ref + QCPLayoutElement::calculateAutoMargin) of each element associated with \a side in this margin + group, and choosing the largest returned value. (QCPLayoutElement::minimumMargins is taken into + account, too.) +*/ +int QCPMarginGroup::commonMargin(QCP::MarginSide side) const +{ + // query all automatic margins of the layout elements in this margin group side and find maximum: + int result = 0; + const QList elements = mChildren.value(side); + for (int i=0; iautoMargins().testFlag(side)) + continue; + int m = qMax(elements.at(i)->calculateAutoMargin(side), QCP::getMarginValue(elements.at(i)->minimumMargins(), side)); + if (m > result) + result = m; + } + return result; +} + +/*! \internal + + Adds \a element to the internal list of child elements, for the margin \a side. + + This function does not modify the margin group property of \a element. +*/ +void QCPMarginGroup::addChild(QCP::MarginSide side, QCPLayoutElement *element) +{ + if (!mChildren[side].contains(element)) + mChildren[side].append(element); + else + qDebug() << Q_FUNC_INFO << "element is already child of this margin group side" << reinterpret_cast(element); +} + +/*! \internal + + Removes \a element from the internal list of child elements, for the margin \a side. + + This function does not modify the margin group property of \a element. +*/ +void QCPMarginGroup::removeChild(QCP::MarginSide side, QCPLayoutElement *element) +{ + if (!mChildren[side].removeOne(element)) + qDebug() << Q_FUNC_INFO << "element is not child of this margin group side" << reinterpret_cast(element); +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPLayoutElement +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPLayoutElement + \brief The abstract base class for all objects that form \ref thelayoutsystem "the layout system". + + This is an abstract base class. As such, it can't be instantiated directly, rather use one of its subclasses. + + A Layout element is a rectangular object which can be placed in layouts. It has an outer rect + (QCPLayoutElement::outerRect) and an inner rect (\ref QCPLayoutElement::rect). The difference + between outer and inner rect is called its margin. The margin can either be set to automatic or + manual (\ref setAutoMargins) on a per-side basis. If a side is set to manual, that margin can be + set explicitly with \ref setMargins and will stay fixed at that value. If it's set to automatic, + the layout element subclass will control the value itself (via \ref calculateAutoMargin). + + Layout elements can be placed in layouts (base class QCPLayout) like QCPLayoutGrid. The top level + layout is reachable via \ref QCustomPlot::plotLayout, and is a \ref QCPLayoutGrid. Since \ref + QCPLayout itself derives from \ref QCPLayoutElement, layouts can be nested. + + Thus in QCustomPlot one can divide layout elements into two categories: The ones that are + invisible by themselves, because they don't draw anything. Their only purpose is to manage the + position and size of other layout elements. This category of layout elements usually use + QCPLayout as base class. Then there is the category of layout elements which actually draw + something. For example, QCPAxisRect, QCPLegend and QCPPlotTitle are of this category. This does + not necessarily mean that the latter category can't have child layout elements. QCPLegend for + instance, actually derives from QCPLayoutGrid and the individual legend items are child layout + elements in the grid layout. +*/ + +/* start documentation of inline functions */ + +/*! \fn QCPLayout *QCPLayoutElement::layout() const + + Returns the parent layout of this layout element. +*/ + +/*! \fn QRect QCPLayoutElement::rect() const + + Returns the inner rect of this layout element. The inner rect is the outer rect (\ref + setOuterRect) shrinked by the margins (\ref setMargins, \ref setAutoMargins). + + In some cases, the area between outer and inner rect is left blank. In other cases the margin + area is used to display peripheral graphics while the main content is in the inner rect. This is + where automatic margin calculation becomes interesting because it allows the layout element to + adapt the margins to the peripheral graphics it wants to draw. For example, \ref QCPAxisRect + draws the axis labels and tick labels in the margin area, thus needs to adjust the margins (if + \ref setAutoMargins is enabled) according to the space required by the labels of the axes. +*/ + +/*! \fn virtual void QCPLayoutElement::mousePressEvent(QMouseEvent *event) + + This event is called, if the mouse was pressed while being inside the outer rect of this layout + element. +*/ + +/*! \fn virtual void QCPLayoutElement::mouseMoveEvent(QMouseEvent *event) + + This event is called, if the mouse is moved inside the outer rect of this layout element. +*/ + +/*! \fn virtual void QCPLayoutElement::mouseReleaseEvent(QMouseEvent *event) + + This event is called, if the mouse was previously pressed inside the outer rect of this layout + element and is now released. +*/ + +/*! \fn virtual void QCPLayoutElement::mouseDoubleClickEvent(QMouseEvent *event) + + This event is called, if the mouse is double-clicked inside the outer rect of this layout + element. +*/ + +/*! \fn virtual void QCPLayoutElement::wheelEvent(QWheelEvent *event) + + This event is called, if the mouse wheel is scrolled while the cursor is inside the rect of this + layout element. +*/ + +/* end documentation of inline functions */ + +/*! + Creates an instance of QCPLayoutElement and sets default values. +*/ +QCPLayoutElement::QCPLayoutElement(QCustomPlot *parentPlot) : + QCPLayerable(parentPlot), // parenthood is changed as soon as layout element gets inserted into a layout (except for top level layout) + mParentLayout(0), + mMinimumSize(), + mMaximumSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX), + mRect(0, 0, 0, 0), + mOuterRect(0, 0, 0, 0), + mMargins(0, 0, 0, 0), + mMinimumMargins(0, 0, 0, 0), + mAutoMargins(QCP::msAll) +{ +} + +QCPLayoutElement::~QCPLayoutElement() +{ + setMarginGroup(QCP::msAll, 0); // unregister at margin groups, if there are any + // unregister at layout: + if (qobject_cast(mParentLayout)) // the qobject_cast is just a safeguard in case the layout forgets to call clear() in its dtor and this dtor is called by QObject dtor + mParentLayout->take(this); +} + +/*! + Sets the outer rect of this layout element. If the layout element is inside a layout, the layout + sets the position and size of this layout element using this function. + + Calling this function externally has no effect, since the layout will overwrite any changes to + the outer rect upon the next replot. + + The layout element will adapt its inner \ref rect by applying the margins inward to the outer rect. + + \see rect +*/ +void QCPLayoutElement::setOuterRect(const QRect &rect) +{ + if (mOuterRect != rect) + { + mOuterRect = rect; + mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); + } +} + +/*! + Sets the margins of this layout element. If \ref setAutoMargins is disabled for some or all + sides, this function is used to manually set the margin on those sides. Sides that are still set + to be handled automatically are ignored and may have any value in \a margins. + + The margin is the distance between the outer rect (controlled by the parent layout via \ref + setOuterRect) and the inner \ref rect (which usually contains the main content of this layout + element). + + \see setAutoMargins +*/ +void QCPLayoutElement::setMargins(const QMargins &margins) +{ + if (mMargins != margins) + { + mMargins = margins; + mRect = mOuterRect.adjusted(mMargins.left(), mMargins.top(), -mMargins.right(), -mMargins.bottom()); + } +} + +/*! + If \ref setAutoMargins is enabled on some or all margins, this function is used to provide + minimum values for those margins. + + The minimum values are not enforced on margin sides that were set to be under manual control via + \ref setAutoMargins. + + \see setAutoMargins +*/ +void QCPLayoutElement::setMinimumMargins(const QMargins &margins) +{ + if (mMinimumMargins != margins) + { + mMinimumMargins = margins; + } +} + +/*! + Sets on which sides the margin shall be calculated automatically. If a side is calculated + automatically, a minimum margin value may be provided with \ref setMinimumMargins. If a side is + set to be controlled manually, the value may be specified with \ref setMargins. + + Margin sides that are under automatic control may participate in a \ref QCPMarginGroup (see \ref + setMarginGroup), to synchronize (align) it with other layout elements in the plot. + + \see setMinimumMargins, setMargins +*/ +void QCPLayoutElement::setAutoMargins(QCP::MarginSides sides) +{ + mAutoMargins = sides; +} + +/*! + Sets the minimum size for the inner \ref rect of this layout element. A parent layout tries to + respect the \a size here by changing row/column sizes in the layout accordingly. + + If the parent layout size is not sufficient to satisfy all minimum size constraints of its child + layout elements, the layout may set a size that is actually smaller than \a size. QCustomPlot + propagates the layout's size constraints to the outside by setting its own minimum QWidget size + accordingly, so violations of \a size should be exceptions. +*/ +void QCPLayoutElement::setMinimumSize(const QSize &size) +{ + if (mMinimumSize != size) + { + mMinimumSize = size; + if (mParentLayout) + mParentLayout->sizeConstraintsChanged(); + } +} + +/*! \overload + + Sets the minimum size for the inner \ref rect of this layout element. +*/ +void QCPLayoutElement::setMinimumSize(int width, int height) +{ + setMinimumSize(QSize(width, height)); +} + +/*! + Sets the maximum size for the inner \ref rect of this layout element. A parent layout tries to + respect the \a size here by changing row/column sizes in the layout accordingly. +*/ +void QCPLayoutElement::setMaximumSize(const QSize &size) +{ + if (mMaximumSize != size) + { + mMaximumSize = size; + if (mParentLayout) + mParentLayout->sizeConstraintsChanged(); + } +} + +/*! \overload + + Sets the maximum size for the inner \ref rect of this layout element. +*/ +void QCPLayoutElement::setMaximumSize(int width, int height) +{ + setMaximumSize(QSize(width, height)); +} + +/*! + Sets the margin \a group of the specified margin \a sides. + + Margin groups allow synchronizing specified margins across layout elements, see the documentation + of \ref QCPMarginGroup. + + To unset the margin group of \a sides, set \a group to 0. + + Note that margin groups only work for margin sides that are set to automatic (\ref + setAutoMargins). +*/ +void QCPLayoutElement::setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group) +{ + QVector sideVector; + if (sides.testFlag(QCP::msLeft)) sideVector.append(QCP::msLeft); + if (sides.testFlag(QCP::msRight)) sideVector.append(QCP::msRight); + if (sides.testFlag(QCP::msTop)) sideVector.append(QCP::msTop); + if (sides.testFlag(QCP::msBottom)) sideVector.append(QCP::msBottom); + + for (int i=0; iremoveChild(side, this); + + if (!group) // if setting to 0, remove hash entry. Else set hash entry to new group and register there + { + mMarginGroups.remove(side); + } else // setting to a new group + { + mMarginGroups[side] = group; + group->addChild(side, this); + } + } + } +} + +/*! + Updates the layout element and sub-elements. This function is automatically called before every + replot by the parent layout element. It is called multiple times, once for every \ref + UpdatePhase. The phases are run through in the order of the enum values. For details about what + happens at the different phases, see the documentation of \ref UpdatePhase. + + Layout elements that have child elements should call the \ref update method of their child + elements, and pass the current \a phase unchanged. + + The default implementation executes the automatic margin mechanism in the \ref upMargins phase. + Subclasses should make sure to call the base class implementation. +*/ +void QCPLayoutElement::update(UpdatePhase phase) +{ + if (phase == upMargins) + { + if (mAutoMargins != QCP::msNone) + { + // set the margins of this layout element according to automatic margin calculation, either directly or via a margin group: + QMargins newMargins = mMargins; + foreach (QCP::MarginSide side, QList() << QCP::msLeft << QCP::msRight << QCP::msTop << QCP::msBottom) + { + if (mAutoMargins.testFlag(side)) // this side's margin shall be calculated automatically + { + if (mMarginGroups.contains(side)) + QCP::setMarginValue(newMargins, side, mMarginGroups[side]->commonMargin(side)); // this side is part of a margin group, so get the margin value from that group + else + QCP::setMarginValue(newMargins, side, calculateAutoMargin(side)); // this side is not part of a group, so calculate the value directly + // apply minimum margin restrictions: + if (QCP::getMarginValue(newMargins, side) < QCP::getMarginValue(mMinimumMargins, side)) + QCP::setMarginValue(newMargins, side, QCP::getMarginValue(mMinimumMargins, side)); + } + } + setMargins(newMargins); + } + } +} + +/*! + Returns the minimum size this layout element (the inner \ref rect) may be compressed to. + + if a minimum size (\ref setMinimumSize) was not set manually, parent layouts consult this + function to determine the minimum allowed size of this layout element. (A manual minimum size is + considered set if it is non-zero.) +*/ +QSize QCPLayoutElement::minimumSizeHint() const +{ + return mMinimumSize; +} + +/*! + Returns the maximum size this layout element (the inner \ref rect) may be expanded to. + + if a maximum size (\ref setMaximumSize) was not set manually, parent layouts consult this + function to determine the maximum allowed size of this layout element. (A manual maximum size is + considered set if it is smaller than Qt's QWIDGETSIZE_MAX.) +*/ +QSize QCPLayoutElement::maximumSizeHint() const +{ + return mMaximumSize; +} + +/*! + Returns a list of all child elements in this layout element. If \a recursive is true, all + sub-child elements are included in the list, too. + + \warning There may be entries with value 0 in the returned list. (For example, QCPLayoutGrid may have + empty cells which yield 0 at the respective index.) +*/ +QList QCPLayoutElement::elements(bool recursive) const +{ + Q_UNUSED(recursive) + return QList(); +} + +/*! + Layout elements are sensitive to events inside their outer rect. If \a pos is within the outer + rect, this method returns a value corresponding to 0.99 times the parent plot's selection + tolerance. However, layout elements are not selectable by default. So if \a onlySelectable is + true, -1.0 is returned. + + See \ref QCPLayerable::selectTest for a general explanation of this virtual method. + + QCPLayoutElement subclasses may reimplement this method to provide more specific selection test + behaviour. +*/ +double QCPLayoutElement::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + + if (onlySelectable) + return -1; + + if (QRectF(mOuterRect).contains(pos)) + { + if (mParentPlot) + return mParentPlot->selectionTolerance()*0.99; + else + { + qDebug() << Q_FUNC_INFO << "parent plot not defined"; + return -1; + } + } else + return -1; +} + +/*! \internal + + propagates the parent plot initialization to all child elements, by calling \ref + QCPLayerable::initializeParentPlot on them. +*/ +void QCPLayoutElement::parentPlotInitialized(QCustomPlot *parentPlot) +{ + foreach (QCPLayoutElement* el, elements(false)) + { + if (!el->parentPlot()) + el->initializeParentPlot(parentPlot); + } +} + +/*! \internal + + Returns the margin size for this \a side. It is used if automatic margins is enabled for this \a + side (see \ref setAutoMargins). If a minimum margin was set with \ref setMinimumMargins, the + returned value will not be smaller than the specified minimum margin. + + The default implementation just returns the respective manual margin (\ref setMargins) or the + minimum margin, whichever is larger. +*/ +int QCPLayoutElement::calculateAutoMargin(QCP::MarginSide side) +{ + return qMax(QCP::getMarginValue(mMargins, side), QCP::getMarginValue(mMinimumMargins, side)); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPLayout +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPLayout + \brief The abstract base class for layouts + + This is an abstract base class for layout elements whose main purpose is to define the position + and size of other child layout elements. In most cases, layouts don't draw anything themselves + (but there are exceptions to this, e.g. QCPLegend). + + QCPLayout derives from QCPLayoutElement, and thus can itself be nested in other layouts. + + QCPLayout introduces a common interface for accessing and manipulating the child elements. Those + functions are most notably \ref elementCount, \ref elementAt, \ref takeAt, \ref take, \ref + simplify, \ref removeAt, \ref remove and \ref clear. Individual subclasses may add more functions + to this interface which are more specialized to the form of the layout. For example, \ref + QCPLayoutGrid adds functions that take row and column indices to access cells of the layout grid + more conveniently. + + Since this is an abstract base class, you can't instantiate it directly. Rather use one of its + subclasses like QCPLayoutGrid or QCPLayoutInset. + + For a general introduction to the layout system, see the dedicated documentation page \ref + thelayoutsystem "The Layout System". +*/ + +/* start documentation of pure virtual functions */ + +/*! \fn virtual int QCPLayout::elementCount() const = 0 + + Returns the number of elements/cells in the layout. + + \see elements, elementAt +*/ + +/*! \fn virtual QCPLayoutElement* QCPLayout::elementAt(int index) const = 0 + + Returns the element in the cell with the given \a index. If \a index is invalid, returns 0. + + Note that even if \a index is valid, the respective cell may be empty in some layouts (e.g. + QCPLayoutGrid), so this function may return 0 in those cases. You may use this function to check + whether a cell is empty or not. + + \see elements, elementCount, takeAt +*/ + +/*! \fn virtual QCPLayoutElement* QCPLayout::takeAt(int index) = 0 + + Removes the element with the given \a index from the layout and returns it. + + If the \a index is invalid or the cell with that index is empty, returns 0. + + Note that some layouts don't remove the respective cell right away but leave an empty cell after + successful removal of the layout element. To collapse empty cells, use \ref simplify. + + \see elementAt, take +*/ + +/*! \fn virtual bool QCPLayout::take(QCPLayoutElement* element) = 0 + + Removes the specified \a element from the layout and returns true on success. + + If the \a element isn't in this layout, returns false. + + Note that some layouts don't remove the respective cell right away but leave an empty cell after + successful removal of the layout element. To collapse empty cells, use \ref simplify. + + \see takeAt +*/ + +/* end documentation of pure virtual functions */ + +/*! + Creates an instance of QCPLayout and sets default values. Note that since QCPLayout + is an abstract base class, it can't be instantiated directly. +*/ +QCPLayout::QCPLayout() +{ +} + +/*! + First calls the QCPLayoutElement::update base class implementation to update the margins on this + layout. + + Then calls \ref updateLayout which subclasses reimplement to reposition and resize their cells. + + Finally, \ref update is called on all child elements. +*/ +void QCPLayout::update(UpdatePhase phase) +{ + QCPLayoutElement::update(phase); + + // set child element rects according to layout: + if (phase == upLayout) + updateLayout(); + + // propagate update call to child elements: + const int elCount = elementCount(); + for (int i=0; iupdate(phase); + } +} + +/* inherits documentation from base class */ +QList QCPLayout::elements(bool recursive) const +{ + const int c = elementCount(); + QList result; +#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) + result.reserve(c); +#endif + for (int i=0; ielements(recursive); + } + } + return result; +} + +/*! + Simplifies the layout by collapsing empty cells. The exact behavior depends on subclasses, the + default implementation does nothing. + + Not all layouts need simplification. For example, QCPLayoutInset doesn't use explicit + simplification while QCPLayoutGrid does. +*/ +void QCPLayout::simplify() +{ +} + +/*! + Removes and deletes the element at the provided \a index. Returns true on success. If \a index is + invalid or points to an empty cell, returns false. + + This function internally uses \ref takeAt to remove the element from the layout and then deletes + the returned element. + + \see remove, takeAt +*/ +bool QCPLayout::removeAt(int index) +{ + if (QCPLayoutElement *el = takeAt(index)) + { + delete el; + return true; + } else + return false; +} + +/*! + Removes and deletes the provided \a element. Returns true on success. If \a element is not in the + layout, returns false. + + This function internally uses \ref takeAt to remove the element from the layout and then deletes + the element. + + \see removeAt, take +*/ +bool QCPLayout::remove(QCPLayoutElement *element) +{ + if (take(element)) + { + delete element; + return true; + } else + return false; +} + +/*! + Removes and deletes all layout elements in this layout. + + \see remove, removeAt +*/ +void QCPLayout::clear() +{ + for (int i=elementCount()-1; i>=0; --i) + { + if (elementAt(i)) + removeAt(i); + } + simplify(); +} + +/*! + Subclasses call this method to report changed (minimum/maximum) size constraints. + + If the parent of this layout is again a QCPLayout, forwards the call to the parent's \ref + sizeConstraintsChanged. If the parent is a QWidget (i.e. is the \ref QCustomPlot::plotLayout of + QCustomPlot), calls QWidget::updateGeometry, so if the QCustomPlot widget is inside a Qt QLayout, + it may update itself and resize cells accordingly. +*/ +void QCPLayout::sizeConstraintsChanged() const +{ + if (QWidget *w = qobject_cast(parent())) + w->updateGeometry(); + else if (QCPLayout *l = qobject_cast(parent())) + l->sizeConstraintsChanged(); +} + +/*! \internal + + Subclasses reimplement this method to update the position and sizes of the child elements/cells + via calling their \ref QCPLayoutElement::setOuterRect. The default implementation does nothing. + + The geometry used as a reference is the inner \ref rect of this layout. Child elements should stay + within that rect. + + \ref getSectionSizes may help with the reimplementation of this function. + + \see update +*/ +void QCPLayout::updateLayout() +{ +} + + +/*! \internal + + Associates \a el with this layout. This is done by setting the \ref QCPLayoutElement::layout, the + \ref QCPLayerable::parentLayerable and the QObject parent to this layout. + + Further, if \a el didn't previously have a parent plot, calls \ref + QCPLayerable::initializeParentPlot on \a el to set the paret plot. + + This method is used by subclass specific methods that add elements to the layout. Note that this + method only changes properties in \a el. The removal from the old layout and the insertion into + the new layout must be done additionally. +*/ +void QCPLayout::adoptElement(QCPLayoutElement *el) +{ + if (el) + { + el->mParentLayout = this; + el->setParentLayerable(this); + el->setParent(this); + if (!el->parentPlot()) + el->initializeParentPlot(mParentPlot); + } else + qDebug() << Q_FUNC_INFO << "Null element passed"; +} + +/*! \internal + + Disassociates \a el from this layout. This is done by setting the \ref QCPLayoutElement::layout + and the \ref QCPLayerable::parentLayerable to zero. The QObject parent is set to the parent + QCustomPlot. + + This method is used by subclass specific methods that remove elements from the layout (e.g. \ref + take or \ref takeAt). Note that this method only changes properties in \a el. The removal from + the old layout must be done additionally. +*/ +void QCPLayout::releaseElement(QCPLayoutElement *el) +{ + if (el) + { + el->mParentLayout = 0; + el->setParentLayerable(0); + el->setParent(mParentPlot); + // Note: Don't initializeParentPlot(0) here, because layout element will stay in same parent plot + } else + qDebug() << Q_FUNC_INFO << "Null element passed"; +} + +/*! \internal + + This is a helper function for the implementation of \ref updateLayout in subclasses. + + It calculates the sizes of one-dimensional sections with provided constraints on maximum section + sizes, minimum section sizes, relative stretch factors and the final total size of all sections. + + The QVector entries refer to the sections. Thus all QVectors must have the same size. + + \a maxSizes gives the maximum allowed size of each section. If there shall be no maximum size + imposed, set all vector values to Qt's QWIDGETSIZE_MAX. + + \a minSizes gives the minimum allowed size of each section. If there shall be no minimum size + imposed, set all vector values to zero. If the \a minSizes entries add up to a value greater than + \a totalSize, sections will be scaled smaller than the proposed minimum sizes. (In other words, + not exceeding the allowed total size is taken to be more important than not going below minimum + section sizes.) + + \a stretchFactors give the relative proportions of the sections to each other. If all sections + shall be scaled equally, set all values equal. If the first section shall be double the size of + each individual other section, set the first number of \a stretchFactors to double the value of + the other individual values (e.g. {2, 1, 1, 1}). + + \a totalSize is the value that the final section sizes will add up to. Due to rounding, the + actual sum may differ slightly. If you want the section sizes to sum up to exactly that value, + you could distribute the remaining difference on the sections. + + The return value is a QVector containing the section sizes. +*/ +QVector QCPLayout::getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const +{ + if (maxSizes.size() != minSizes.size() || minSizes.size() != stretchFactors.size()) + { + qDebug() << Q_FUNC_INFO << "Passed vector sizes aren't equal:" << maxSizes << minSizes << stretchFactors; + return QVector(); + } + if (stretchFactors.isEmpty()) + return QVector(); + int sectionCount = stretchFactors.size(); + QVector sectionSizes(sectionCount); + // if provided total size is forced smaller than total minimum size, ignore minimum sizes (squeeze sections): + int minSizeSum = 0; + for (int i=0; i minimumLockedSections; + QList unfinishedSections; + for (int i=0; i result(sectionCount); + for (int i=0; i= 0 && row < mElements.size()) + { + if (column >= 0 && column < mElements.first().size()) + { + if (QCPLayoutElement *result = mElements.at(row).at(column)) + return result; + else + qDebug() << Q_FUNC_INFO << "Requested cell is empty. Row:" << row << "Column:" << column; + } else + qDebug() << Q_FUNC_INFO << "Invalid column. Row:" << row << "Column:" << column; + } else + qDebug() << Q_FUNC_INFO << "Invalid row. Row:" << row << "Column:" << column; + return 0; +} + +/*! + Returns the number of rows in the layout. + + \see columnCount +*/ +int QCPLayoutGrid::rowCount() const +{ + return mElements.size(); +} + +/*! + Returns the number of columns in the layout. + + \see rowCount +*/ +int QCPLayoutGrid::columnCount() const +{ + if (mElements.size() > 0) + return mElements.first().size(); + else + return 0; +} + +/*! + Adds the \a element to cell with \a row and \a column. If \a element is already in a layout, it + is first removed from there. If \a row or \a column don't exist yet, the layout is expanded + accordingly. + + Returns true if the element was added successfully, i.e. if the cell at \a row and \a column + didn't already have an element. + + \see element, hasElement, take, remove +*/ +bool QCPLayoutGrid::addElement(int row, int column, QCPLayoutElement *element) +{ + if (element) + { + if (!hasElement(row, column)) + { + if (element->layout()) // remove from old layout first + element->layout()->take(element); + expandTo(row+1, column+1); + mElements[row][column] = element; + adoptElement(element); + return true; + } else + qDebug() << Q_FUNC_INFO << "There is already an element in the specified row/column:" << row << column; + } else + qDebug() << Q_FUNC_INFO << "Can't add null element to row/column:" << row << column; + return false; +} + +/*! + Returns whether the cell at \a row and \a column exists and contains a valid element, i.e. isn't + empty. + + \see element +*/ +bool QCPLayoutGrid::hasElement(int row, int column) +{ + if (row >= 0 && row < rowCount() && column >= 0 && column < columnCount()) + return mElements.at(row).at(column); + else + return false; +} + +/*! + Sets the stretch \a factor of \a column. + + Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond + their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref + QCPLayoutElement::setMaximumSize), regardless of the stretch factor. + + The default stretch factor of newly created rows/columns is 1. + + \see setColumnStretchFactors, setRowStretchFactor +*/ +void QCPLayoutGrid::setColumnStretchFactor(int column, double factor) +{ + if (column >= 0 && column < columnCount()) + { + if (factor > 0) + mColumnStretchFactors[column] = factor; + else + qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; + } else + qDebug() << Q_FUNC_INFO << "Invalid column:" << column; +} + +/*! + Sets the stretch \a factors of all columns. \a factors must have the size \ref columnCount. + + Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond + their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref + QCPLayoutElement::setMaximumSize), regardless of the stretch factor. + + The default stretch factor of newly created rows/columns is 1. + + \see setColumnStretchFactor, setRowStretchFactors +*/ +void QCPLayoutGrid::setColumnStretchFactors(const QList &factors) +{ + if (factors.size() == mColumnStretchFactors.size()) + { + mColumnStretchFactors = factors; + for (int i=0; i= 0 && row < rowCount()) + { + if (factor > 0) + mRowStretchFactors[row] = factor; + else + qDebug() << Q_FUNC_INFO << "Invalid stretch factor, must be positive:" << factor; + } else + qDebug() << Q_FUNC_INFO << "Invalid row:" << row; +} + +/*! + Sets the stretch \a factors of all rows. \a factors must have the size \ref rowCount. + + Stretch factors control the relative sizes of rows and columns. Cells will not be resized beyond + their minimum and maximum widths/heights (\ref QCPLayoutElement::setMinimumSize, \ref + QCPLayoutElement::setMaximumSize), regardless of the stretch factor. + + The default stretch factor of newly created rows/columns is 1. + + \see setRowStretchFactor, setColumnStretchFactors +*/ +void QCPLayoutGrid::setRowStretchFactors(const QList &factors) +{ + if (factors.size() == mRowStretchFactors.size()) + { + mRowStretchFactors = factors; + for (int i=0; i()); + mRowStretchFactors.append(1); + } + // go through rows and expand columns as necessary: + int newColCount = qMax(columnCount(), newColumnCount); + for (int i=0; i rowCount()) + newIndex = rowCount(); + + mRowStretchFactors.insert(newIndex, 1); + QList newRow; + for (int col=0; col columnCount()) + newIndex = columnCount(); + + mColumnStretchFactors.insert(newIndex, 1); + for (int row=0; row minColWidths, minRowHeights, maxColWidths, maxRowHeights; + getMinimumRowColSizes(&minColWidths, &minRowHeights); + getMaximumRowColSizes(&maxColWidths, &maxRowHeights); + + int totalRowSpacing = (rowCount()-1) * mRowSpacing; + int totalColSpacing = (columnCount()-1) * mColumnSpacing; + QVector colWidths = getSectionSizes(maxColWidths, minColWidths, mColumnStretchFactors.toVector(), mRect.width()-totalColSpacing); + QVector rowHeights = getSectionSizes(maxRowHeights, minRowHeights, mRowStretchFactors.toVector(), mRect.height()-totalRowSpacing); + + // go through cells and set rects accordingly: + int yOffset = mRect.top(); + for (int row=0; row 0) + yOffset += rowHeights.at(row-1)+mRowSpacing; + int xOffset = mRect.left(); + for (int col=0; col 0) + xOffset += colWidths.at(col-1)+mColumnSpacing; + if (mElements.at(row).at(col)) + mElements.at(row).at(col)->setOuterRect(QRect(xOffset, yOffset, colWidths.at(col), rowHeights.at(row))); + } + } +} + +/* inherits documentation from base class */ +int QCPLayoutGrid::elementCount() const +{ + return rowCount()*columnCount(); +} + +/* inherits documentation from base class */ +QCPLayoutElement *QCPLayoutGrid::elementAt(int index) const +{ + if (index >= 0 && index < elementCount()) + return mElements.at(index / columnCount()).at(index % columnCount()); + else + return 0; +} + +/* inherits documentation from base class */ +QCPLayoutElement *QCPLayoutGrid::takeAt(int index) +{ + if (QCPLayoutElement *el = elementAt(index)) + { + releaseElement(el); + mElements[index / columnCount()][index % columnCount()] = 0; + return el; + } else + { + qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; + return 0; + } +} + +/* inherits documentation from base class */ +bool QCPLayoutGrid::take(QCPLayoutElement *element) +{ + if (element) + { + for (int i=0; i QCPLayoutGrid::elements(bool recursive) const +{ + QList result; + int colC = columnCount(); + int rowC = rowCount(); +#if QT_VERSION >= QT_VERSION_CHECK(4, 7, 0) + result.reserve(colC*rowC); +#endif + for (int row=0; rowelements(recursive); + } + } + return result; +} + +/*! + Simplifies the layout by collapsing rows and columns which only contain empty cells. +*/ +void QCPLayoutGrid::simplify() +{ + // remove rows with only empty cells: + for (int row=rowCount()-1; row>=0; --row) + { + bool hasElements = false; + for (int col=0; col=0; --col) + { + bool hasElements = false; + for (int row=0; row minColWidths, minRowHeights; + getMinimumRowColSizes(&minColWidths, &minRowHeights); + QSize result(0, 0); + for (int i=0; i maxColWidths, maxRowHeights; + getMaximumRowColSizes(&maxColWidths, &maxRowHeights); + + QSize result(0, 0); + for (int i=0; i *minColWidths, QVector *minRowHeights) const +{ + *minColWidths = QVector(columnCount(), 0); + *minRowHeights = QVector(rowCount(), 0); + for (int row=0; rowminimumSizeHint(); + QSize min = mElements.at(row).at(col)->minimumSize(); + QSize final(min.width() > 0 ? min.width() : minHint.width(), min.height() > 0 ? min.height() : minHint.height()); + if (minColWidths->at(col) < final.width()) + (*minColWidths)[col] = final.width(); + if (minRowHeights->at(row) < final.height()) + (*minRowHeights)[row] = final.height(); + } + } + } +} + +/*! \internal + + Places the maximum column widths and row heights into \a maxColWidths and \a maxRowHeights + respectively. + + The maximum height of a row is the smallest maximum height of any element in that row. The + maximum width of a column is the smallest maximum width of any element in that column. + + This is a helper function for \ref updateLayout. + + \see getMinimumRowColSizes +*/ +void QCPLayoutGrid::getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const +{ + *maxColWidths = QVector(columnCount(), QWIDGETSIZE_MAX); + *maxRowHeights = QVector(rowCount(), QWIDGETSIZE_MAX); + for (int row=0; rowmaximumSizeHint(); + QSize max = mElements.at(row).at(col)->maximumSize(); + QSize final(max.width() < QWIDGETSIZE_MAX ? max.width() : maxHint.width(), max.height() < QWIDGETSIZE_MAX ? max.height() : maxHint.height()); + if (maxColWidths->at(col) > final.width()) + (*maxColWidths)[col] = final.width(); + if (maxRowHeights->at(row) > final.height()) + (*maxRowHeights)[row] = final.height(); + } + } + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPLayoutInset +//////////////////////////////////////////////////////////////////////////////////////////////////// +/*! \class QCPLayoutInset + \brief A layout that places child elements aligned to the border or arbitrarily positioned + + Elements are placed either aligned to the border or at arbitrary position in the area of the + layout. Which placement applies is controlled with the \ref InsetPlacement (\ref + setInsetPlacement). + + Elements are added via \ref addElement(QCPLayoutElement *element, Qt::Alignment alignment) or + addElement(QCPLayoutElement *element, const QRectF &rect). If the first method is used, the inset + placement will default to \ref ipBorderAligned and the element will be aligned according to the + \a alignment parameter. The second method defaults to \ref ipFree and allows placing elements at + arbitrary position and size, defined by \a rect. + + The alignment or rect can be set via \ref setInsetAlignment or \ref setInsetRect, respectively. + + This is the layout that every QCPAxisRect has as \ref QCPAxisRect::insetLayout. +*/ + +/* start documentation of inline functions */ + +/*! \fn virtual void QCPLayoutInset::simplify() + + The QCPInsetLayout does not need simplification since it can never have empty cells due to its + linear index structure. This method does nothing. +*/ + +/* end documentation of inline functions */ + +/*! + Creates an instance of QCPLayoutInset and sets default values. +*/ +QCPLayoutInset::QCPLayoutInset() +{ +} + +QCPLayoutInset::~QCPLayoutInset() +{ + // clear all child layout elements. This is important because only the specific layouts know how + // to handle removing elements (clear calls virtual removeAt method to do that). + clear(); +} + +/*! + Returns the placement type of the element with the specified \a index. +*/ +QCPLayoutInset::InsetPlacement QCPLayoutInset::insetPlacement(int index) const +{ + if (elementAt(index)) + return mInsetPlacement.at(index); + else + { + qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; + return ipFree; + } +} + +/*! + Returns the alignment of the element with the specified \a index. The alignment only has a + meaning, if the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned. +*/ +Qt::Alignment QCPLayoutInset::insetAlignment(int index) const +{ + if (elementAt(index)) + return mInsetAlignment.at(index); + else + { + qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; + return 0; + } +} + +/*! + Returns the rect of the element with the specified \a index. The rect only has a + meaning, if the inset placement (\ref setInsetPlacement) is \ref ipFree. +*/ +QRectF QCPLayoutInset::insetRect(int index) const +{ + if (elementAt(index)) + return mInsetRect.at(index); + else + { + qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; + return QRectF(); + } +} + +/*! + Sets the inset placement type of the element with the specified \a index to \a placement. + + \see InsetPlacement +*/ +void QCPLayoutInset::setInsetPlacement(int index, QCPLayoutInset::InsetPlacement placement) +{ + if (elementAt(index)) + mInsetPlacement[index] = placement; + else + qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; +} + +/*! + If the inset placement (\ref setInsetPlacement) is \ref ipBorderAligned, this function + is used to set the alignment of the element with the specified \a index to \a alignment. + + \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, + Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other + alignment flags will be ignored. +*/ +void QCPLayoutInset::setInsetAlignment(int index, Qt::Alignment alignment) +{ + if (elementAt(index)) + mInsetAlignment[index] = alignment; + else + qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; +} + +/*! + If the inset placement (\ref setInsetPlacement) is \ref ipFree, this function is used to set the + position and size of the element with the specified \a index to \a rect. + + \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) + will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right + corner of the layout, with 35% width and height of the parent layout. + + Note that the minimum and maximum sizes of the embedded element (\ref + QCPLayoutElement::setMinimumSize, \ref QCPLayoutElement::setMaximumSize) are enforced. +*/ +void QCPLayoutInset::setInsetRect(int index, const QRectF &rect) +{ + if (elementAt(index)) + mInsetRect[index] = rect; + else + qDebug() << Q_FUNC_INFO << "Invalid element index:" << index; +} + +/* inherits documentation from base class */ +void QCPLayoutInset::updateLayout() +{ + for (int i=0; iminimumSizeHint(); + QSize maxSizeHint = mElements.at(i)->maximumSizeHint(); + finalMinSize.setWidth(mElements.at(i)->minimumSize().width() > 0 ? mElements.at(i)->minimumSize().width() : minSizeHint.width()); + finalMinSize.setHeight(mElements.at(i)->minimumSize().height() > 0 ? mElements.at(i)->minimumSize().height() : minSizeHint.height()); + finalMaxSize.setWidth(mElements.at(i)->maximumSize().width() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().width() : maxSizeHint.width()); + finalMaxSize.setHeight(mElements.at(i)->maximumSize().height() < QWIDGETSIZE_MAX ? mElements.at(i)->maximumSize().height() : maxSizeHint.height()); + if (mInsetPlacement.at(i) == ipFree) + { + insetRect = QRect(rect().x()+rect().width()*mInsetRect.at(i).x(), + rect().y()+rect().height()*mInsetRect.at(i).y(), + rect().width()*mInsetRect.at(i).width(), + rect().height()*mInsetRect.at(i).height()); + if (insetRect.size().width() < finalMinSize.width()) + insetRect.setWidth(finalMinSize.width()); + if (insetRect.size().height() < finalMinSize.height()) + insetRect.setHeight(finalMinSize.height()); + if (insetRect.size().width() > finalMaxSize.width()) + insetRect.setWidth(finalMaxSize.width()); + if (insetRect.size().height() > finalMaxSize.height()) + insetRect.setHeight(finalMaxSize.height()); + } else if (mInsetPlacement.at(i) == ipBorderAligned) + { + insetRect.setSize(finalMinSize); + Qt::Alignment al = mInsetAlignment.at(i); + if (al.testFlag(Qt::AlignLeft)) insetRect.moveLeft(rect().x()); + else if (al.testFlag(Qt::AlignRight)) insetRect.moveRight(rect().x()+rect().width()); + else insetRect.moveLeft(rect().x()+rect().width()*0.5-finalMinSize.width()*0.5); // default to Qt::AlignHCenter + if (al.testFlag(Qt::AlignTop)) insetRect.moveTop(rect().y()); + else if (al.testFlag(Qt::AlignBottom)) insetRect.moveBottom(rect().y()+rect().height()); + else insetRect.moveTop(rect().y()+rect().height()*0.5-finalMinSize.height()*0.5); // default to Qt::AlignVCenter + } + mElements.at(i)->setOuterRect(insetRect); + } +} + +/* inherits documentation from base class */ +int QCPLayoutInset::elementCount() const +{ + return mElements.size(); +} + +/* inherits documentation from base class */ +QCPLayoutElement *QCPLayoutInset::elementAt(int index) const +{ + if (index >= 0 && index < mElements.size()) + return mElements.at(index); + else + return 0; +} + +/* inherits documentation from base class */ +QCPLayoutElement *QCPLayoutInset::takeAt(int index) +{ + if (QCPLayoutElement *el = elementAt(index)) + { + releaseElement(el); + mElements.removeAt(index); + mInsetPlacement.removeAt(index); + mInsetAlignment.removeAt(index); + mInsetRect.removeAt(index); + return el; + } else + { + qDebug() << Q_FUNC_INFO << "Attempt to take invalid index:" << index; + return 0; + } +} + +/* inherits documentation from base class */ +bool QCPLayoutInset::take(QCPLayoutElement *element) +{ + if (element) + { + for (int i=0; irealVisibility() && mElements.at(i)->selectTest(pos, onlySelectable) >= 0) + return mParentPlot->selectionTolerance()*0.99; + } + return -1; +} + +/*! + Adds the specified \a element to the layout as an inset aligned at the border (\ref + setInsetAlignment is initialized with \ref ipBorderAligned). The alignment is set to \a + alignment. + + \a alignment is an or combination of the following alignment flags: Qt::AlignLeft, + Qt::AlignHCenter, Qt::AlighRight, Qt::AlignTop, Qt::AlignVCenter, Qt::AlignBottom. Any other + alignment flags will be ignored. + + \see addElement(QCPLayoutElement *element, const QRectF &rect) +*/ +void QCPLayoutInset::addElement(QCPLayoutElement *element, Qt::Alignment alignment) +{ + if (element) + { + if (element->layout()) // remove from old layout first + element->layout()->take(element); + mElements.append(element); + mInsetPlacement.append(ipBorderAligned); + mInsetAlignment.append(alignment); + mInsetRect.append(QRectF(0.6, 0.6, 0.4, 0.4)); + adoptElement(element); + } else + qDebug() << Q_FUNC_INFO << "Can't add null element"; +} + +/*! + Adds the specified \a element to the layout as an inset with free positioning/sizing (\ref + setInsetAlignment is initialized with \ref ipFree). The position and size is set to \a + rect. + + \a rect is given in fractions of the whole inset layout rect. So an inset with rect (0, 0, 1, 1) + will span the entire layout. An inset with rect (0.6, 0.1, 0.35, 0.35) will be in the top right + corner of the layout, with 35% width and height of the parent layout. + + \see addElement(QCPLayoutElement *element, Qt::Alignment alignment) +*/ +void QCPLayoutInset::addElement(QCPLayoutElement *element, const QRectF &rect) +{ + if (element) + { + if (element->layout()) // remove from old layout first + element->layout()->take(element); + mElements.append(element); + mInsetPlacement.append(ipFree); + mInsetAlignment.append(Qt::AlignRight|Qt::AlignTop); + mInsetRect.append(rect); + adoptElement(element); + } else + qDebug() << Q_FUNC_INFO << "Can't add null element"; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPLineEnding +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPLineEnding + \brief Handles the different ending decorations for line-like items + + \image html QCPLineEnding.png "The various ending styles currently supported" + + For every ending a line-like item has, an instance of this class exists. For example, QCPItemLine + has two endings which can be set with QCPItemLine::setHead and QCPItemLine::setTail. + + The styles themselves are defined via the enum QCPLineEnding::EndingStyle. Most decorations can + be modified regarding width and length, see \ref setWidth and \ref setLength. The direction of + the ending decoration (e.g. direction an arrow is pointing) is controlled by the line-like item. + For example, when both endings of a QCPItemLine are set to be arrows, they will point to opposite + directions, e.g. "outward". This can be changed by \ref setInverted, which would make the + respective arrow point inward. + + Note that due to the overloaded QCPLineEnding constructor, you may directly specify a + QCPLineEnding::EndingStyle where actually a QCPLineEnding is expected, e.g. \code + myItemLine->setHead(QCPLineEnding::esSpikeArrow) \endcode +*/ + +/*! + Creates a QCPLineEnding instance with default values (style \ref esNone). +*/ +QCPLineEnding::QCPLineEnding() : + mStyle(esNone), + mWidth(8), + mLength(10), + mInverted(false) +{ +} + +/*! + Creates a QCPLineEnding instance with the specified values. +*/ +QCPLineEnding::QCPLineEnding(QCPLineEnding::EndingStyle style, double width, double length, bool inverted) : + mStyle(style), + mWidth(width), + mLength(length), + mInverted(inverted) +{ +} + +/*! + Sets the style of the ending decoration. +*/ +void QCPLineEnding::setStyle(QCPLineEnding::EndingStyle style) +{ + mStyle = style; +} + +/*! + Sets the width of the ending decoration, if the style supports it. On arrows, for example, the + width defines the size perpendicular to the arrow's pointing direction. + + \see setLength +*/ +void QCPLineEnding::setWidth(double width) +{ + mWidth = width; +} + +/*! + Sets the length of the ending decoration, if the style supports it. On arrows, for example, the + length defines the size in pointing direction. + + \see setWidth +*/ +void QCPLineEnding::setLength(double length) +{ + mLength = length; +} + +/*! + Sets whether the ending decoration shall be inverted. For example, an arrow decoration will point + inward when \a inverted is set to true. + + Note that also the \a width direction is inverted. For symmetrical ending styles like arrows or + discs, this doesn't make a difference. However, asymmetric styles like \ref esHalfBar are + affected by it, which can be used to control to which side the half bar points to. +*/ +void QCPLineEnding::setInverted(bool inverted) +{ + mInverted = inverted; +} + +/*! \internal + + Returns the maximum pixel radius the ending decoration might cover, starting from the position + the decoration is drawn at (typically a line ending/\ref QCPItemPosition of an item). + + This is relevant for clipping. Only omit painting of the decoration when the position where the + decoration is supposed to be drawn is farther away from the clipping rect than the returned + distance. +*/ +double QCPLineEnding::boundingDistance() const +{ + switch (mStyle) + { + case esNone: + return 0; + + case esFlatArrow: + case esSpikeArrow: + case esLineArrow: + case esSkewedBar: + return qSqrt(mWidth*mWidth+mLength*mLength); // items that have width and length + + case esDisc: + case esSquare: + case esDiamond: + case esBar: + case esHalfBar: + return mWidth*1.42; // items that only have a width -> width*sqrt(2) + + } + return 0; +} + +/*! + Starting from the origin of this line ending (which is style specific), returns the length + covered by the line ending symbol, in backward direction. + + For example, the \ref esSpikeArrow has a shorter real length than a \ref esFlatArrow, even if + both have the same \ref setLength value, because the spike arrow has an inward curved back, which + reduces the length along its center axis (the drawing origin for arrows is at the tip). + + This function is used for precise, style specific placement of line endings, for example in + QCPAxes. +*/ +double QCPLineEnding::realLength() const +{ + switch (mStyle) + { + case esNone: + case esLineArrow: + case esSkewedBar: + case esBar: + case esHalfBar: + return 0; + + case esFlatArrow: + return mLength; + + case esDisc: + case esSquare: + case esDiamond: + return mWidth*0.5; + + case esSpikeArrow: + return mLength*0.8; + } + return 0; +} + +/*! \internal + + Draws the line ending with the specified \a painter at the position \a pos. The direction of the + line ending is controlled with \a dir. +*/ +void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const +{ + if (mStyle == esNone) + return; + + QVector2D lengthVec(dir.normalized()); + if (lengthVec.isNull()) + lengthVec = QVector2D(1, 0); + QVector2D widthVec(-lengthVec.y(), lengthVec.x()); + lengthVec *= (float)(mLength*(mInverted ? -1 : 1)); + widthVec *= (float)(mWidth*0.5*(mInverted ? -1 : 1)); + + QPen penBackup = painter->pen(); + QBrush brushBackup = painter->brush(); + QPen miterPen = penBackup; + miterPen.setJoinStyle(Qt::MiterJoin); // to make arrow heads spikey + QBrush brush(painter->pen().color(), Qt::SolidPattern); + switch (mStyle) + { + case esNone: break; + case esFlatArrow: + { + QPointF points[3] = {pos.toPointF(), + (pos-lengthVec+widthVec).toPointF(), + (pos-lengthVec-widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 3); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esSpikeArrow: + { + QPointF points[4] = {pos.toPointF(), + (pos-lengthVec+widthVec).toPointF(), + (pos-lengthVec*0.8f).toPointF(), + (pos-lengthVec-widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 4); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esLineArrow: + { + QPointF points[3] = {(pos-lengthVec+widthVec).toPointF(), + pos.toPointF(), + (pos-lengthVec-widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->drawPolyline(points, 3); + painter->setPen(penBackup); + break; + } + case esDisc: + { + painter->setBrush(brush); + painter->drawEllipse(pos.toPointF(), mWidth*0.5, mWidth*0.5); + painter->setBrush(brushBackup); + break; + } + case esSquare: + { + QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); + QPointF points[4] = {(pos-widthVecPerp+widthVec).toPointF(), + (pos-widthVecPerp-widthVec).toPointF(), + (pos+widthVecPerp-widthVec).toPointF(), + (pos+widthVecPerp+widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 4); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esDiamond: + { + QVector2D widthVecPerp(-widthVec.y(), widthVec.x()); + QPointF points[4] = {(pos-widthVecPerp).toPointF(), + (pos-widthVec).toPointF(), + (pos+widthVecPerp).toPointF(), + (pos+widthVec).toPointF() + }; + painter->setPen(miterPen); + painter->setBrush(brush); + painter->drawConvexPolygon(points, 4); + painter->setBrush(brushBackup); + painter->setPen(penBackup); + break; + } + case esBar: + { + painter->drawLine((pos+widthVec).toPointF(), (pos-widthVec).toPointF()); + break; + } + case esHalfBar: + { + painter->drawLine((pos+widthVec).toPointF(), pos.toPointF()); + break; + } + case esSkewedBar: + { + if (qFuzzyIsNull(painter->pen().widthF()) && !painter->modes().testFlag(QCPPainter::pmNonCosmetic)) + { + // if drawing with cosmetic pen (perfectly thin stroke, happens only in vector exports), draw bar exactly on tip of line + painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)).toPointF(), + (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)).toPointF()); + } else + { + // if drawing with thick (non-cosmetic) pen, shift bar a little in line direction to prevent line from sticking through bar slightly + painter->drawLine((pos+widthVec+lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF(), + (pos-widthVec-lengthVec*0.2f*(mInverted?-1:1)+dir.normalized()*qMax(1.0f, (float)painter->pen().widthF())*0.5f).toPointF()); + } + break; + } + } +} + +/*! \internal + \overload + + Draws the line ending. The direction is controlled with the \a angle parameter in radians. +*/ +void QCPLineEnding::draw(QCPPainter *painter, const QVector2D &pos, double angle) const +{ + draw(painter, pos, QVector2D(qCos(angle), qSin(angle))); +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPGrid +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPGrid + \brief Responsible for drawing the grid of a QCPAxis. + + This class is tightly bound to QCPAxis. Every axis owns a grid instance and uses it to draw the + grid lines, sub grid lines and zero-line. You can interact with the grid of an axis via \ref + QCPAxis::grid. Normally, you don't need to create an instance of QCPGrid yourself. + + The axis and grid drawing was split into two classes to allow them to be placed on different + layers (both QCPAxis and QCPGrid inherit from QCPLayerable). Thus it is possible to have the grid + in the background and the axes in the foreground, and any plottables/items in between. This + described situation is the default setup, see the QCPLayer documentation. +*/ + +/*! + Creates a QCPGrid instance and sets default values. + + You shouldn't instantiate grids on their own, since every QCPAxis brings its own QCPGrid. +*/ +QCPGrid::QCPGrid(QCPAxis *parentAxis) : + QCPLayerable(parentAxis->parentPlot(), "", parentAxis), + mParentAxis(parentAxis) +{ + // warning: this is called in QCPAxis constructor, so parentAxis members should not be accessed/called + setParent(parentAxis); + setPen(QPen(QColor(200,200,200), 0, Qt::DotLine)); + setSubGridPen(QPen(QColor(220,220,220), 0, Qt::DotLine)); + setZeroLinePen(QPen(QColor(200,200,200), 0, Qt::SolidLine)); + setSubGridVisible(false); + setAntialiased(false); + setAntialiasedSubGrid(false); + setAntialiasedZeroLine(false); +} + +/*! + Sets whether grid lines at sub tick marks are drawn. + + \see setSubGridPen +*/ +void QCPGrid::setSubGridVisible(bool visible) +{ + mSubGridVisible = visible; +} + +/*! + Sets whether sub grid lines are drawn antialiased. +*/ +void QCPGrid::setAntialiasedSubGrid(bool enabled) +{ + mAntialiasedSubGrid = enabled; +} + +/*! + Sets whether zero lines are drawn antialiased. +*/ +void QCPGrid::setAntialiasedZeroLine(bool enabled) +{ + mAntialiasedZeroLine = enabled; +} + +/*! + Sets the pen with which (major) grid lines are drawn. +*/ +void QCPGrid::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen with which sub grid lines are drawn. +*/ +void QCPGrid::setSubGridPen(const QPen &pen) +{ + mSubGridPen = pen; +} + +/*! + Sets the pen with which zero lines are drawn. + + Zero lines are lines at value coordinate 0 which may be drawn with a different pen than other grid + lines. To disable zero lines and just draw normal grid lines at zero, set \a pen to Qt::NoPen. +*/ +void QCPGrid::setZeroLinePen(const QPen &pen) +{ + mZeroLinePen = pen; +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing the major grid lines. + + This is the antialiasing state the painter passed to the \ref draw method is in by default. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased +*/ +void QCPGrid::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiased, QCP::aeGrid); +} + +/*! \internal + + Draws grid lines and sub grid lines at the positions of (sub) ticks of the parent axis, spanning + over the complete axis rect. Also draws the zero line, if appropriate (\ref setZeroLinePen). +*/ +void QCPGrid::draw(QCPPainter *painter) +{ + if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } + + if (mSubGridVisible) + drawSubGridLines(painter); + drawGridLines(painter); +} + +/*! \internal + + Draws the main grid lines and possibly a zero line with the specified painter. + + This is a helper function called by \ref draw. +*/ +void QCPGrid::drawGridLines(QCPPainter *painter) const +{ + if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } + + int lowTick = mParentAxis->mLowestVisibleTick; + int highTick = mParentAxis->mHighestVisibleTick; + double t; // helper variable, result of coordinate-to-pixel transforms + if (mParentAxis->orientation() == Qt::Horizontal) + { + // draw zeroline: + int zeroLineIndex = -1; + if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) + { + applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); + painter->setPen(mZeroLinePen); + double epsilon = mParentAxis->range().size()*1E-6; // for comparing double to zero + for (int i=lowTick; i <= highTick; ++i) + { + if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) + { + zeroLineIndex = i; + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x + painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + break; + } + } + } + // draw grid lines: + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + for (int i=lowTick; i <= highTick; ++i) + { + if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // x + painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + } + } else + { + // draw zeroline: + int zeroLineIndex = -1; + if (mZeroLinePen.style() != Qt::NoPen && mParentAxis->mRange.lower < 0 && mParentAxis->mRange.upper > 0) + { + applyAntialiasingHint(painter, mAntialiasedZeroLine, QCP::aeZeroLine); + painter->setPen(mZeroLinePen); + double epsilon = mParentAxis->mRange.size()*1E-6; // for comparing double to zero + for (int i=lowTick; i <= highTick; ++i) + { + if (qAbs(mParentAxis->mTickVector.at(i)) < epsilon) + { + zeroLineIndex = i; + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y + painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + break; + } + } + } + // draw grid lines: + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + for (int i=lowTick; i <= highTick; ++i) + { + if (i == zeroLineIndex) continue; // don't draw a gridline on top of the zeroline + t = mParentAxis->coordToPixel(mParentAxis->mTickVector.at(i)); // y + painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + } + } +} + +/*! \internal + + Draws the sub grid lines with the specified painter. + + This is a helper function called by \ref draw. +*/ +void QCPGrid::drawSubGridLines(QCPPainter *painter) const +{ + if (!mParentAxis) { qDebug() << Q_FUNC_INFO << "invalid parent axis"; return; } + + applyAntialiasingHint(painter, mAntialiasedSubGrid, QCP::aeSubGrid); + double t; // helper variable, result of coordinate-to-pixel transforms + painter->setPen(mSubGridPen); + if (mParentAxis->orientation() == Qt::Horizontal) + { + for (int i=0; imSubTickVector.size(); ++i) + { + t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // x + painter->drawLine(QLineF(t, mParentAxis->mAxisRect->bottom(), t, mParentAxis->mAxisRect->top())); + } + } else + { + for (int i=0; imSubTickVector.size(); ++i) + { + t = mParentAxis->coordToPixel(mParentAxis->mSubTickVector.at(i)); // y + painter->drawLine(QLineF(mParentAxis->mAxisRect->left(), t, mParentAxis->mAxisRect->right(), t)); + } + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPAxis +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPAxis + \brief Manages a single axis inside a QCustomPlot. + + Usually doesn't need to be instantiated externally. Access %QCustomPlot's default four axes via + QCustomPlot::xAxis (bottom), QCustomPlot::yAxis (left), QCustomPlot::xAxis2 (top) and + QCustomPlot::yAxis2 (right). + + Axes are always part of an axis rect, see QCPAxisRect. + \image html AxisNamesOverview.png +
Naming convention of axis parts
+ \n + + \image html AxisRectSpacingOverview.png +
Overview of the spacings and paddings that define the geometry of an axis. The dashed gray line + on the left represents the QCustomPlot widget border.
+ +*/ + +/* start of documentation of inline functions */ + +/*! \fn Qt::Orientation QCPAxis::orientation() const + + Returns the orientation of this axis. The axis orientation (horizontal or vertical) is deduced + from the axis type (left, top, right or bottom). + + \see orientation(AxisType type) +*/ + +/*! \fn QCPGrid *QCPAxis::grid() const + + Returns the \ref QCPGrid instance belonging to this axis. Access it to set details about the way the + grid is displayed. +*/ + +/*! \fn static Qt::Orientation QCPAxis::orientation(AxisType type) + + Returns the orientation of the specified axis type + + \see orientation() +*/ + +/* end of documentation of inline functions */ +/* start of documentation of signals */ + +/*! \fn void QCPAxis::ticksRequest() + + This signal is emitted when \ref setAutoTicks is false and the axis is about to generate tick + labels for a replot. + + Modifying the tick positions can be done with \ref setTickVector. If you also want to control the + tick labels, set \ref setAutoTickLabels to false and also provide the labels with \ref + setTickVectorLabels. + + If you only want static ticks you probably don't need this signal, since you can just set the + tick vector (and possibly tick label vector) once. However, if you want to provide ticks (and + maybe labels) dynamically, e.g. depending on the current axis range, connect a slot to this + signal and set the vector/vectors there. +*/ + +/*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange) + + This signal is emitted when the range of this axis has changed. You can connect it to the \ref + setRange slot of another axis to communicate the new range to the other axis, in order for it to + be synchronized. +*/ + +/*! \fn void QCPAxis::rangeChanged(const QCPRange &newRange, const QCPRange &oldRange) + \overload + + Additionally to the new range, this signal also provides the previous range held by the axis as + \a oldRange. +*/ + +/*! \fn void QCPAxis::scaleTypeChanged(QCPAxis::ScaleType scaleType); + + This signal is emitted when the scale type changes, by calls to \ref setScaleType +*/ + +/*! \fn void QCPAxis::selectionChanged(QCPAxis::SelectableParts selection) + + This signal is emitted when the selection state of this axis has changed, either by user interaction + or by a direct call to \ref setSelectedParts. +*/ + +/*! \fn void QCPAxis::selectableChanged(const QCPAxis::SelectableParts &parts); + + This signal is emitted when the selectability changes, by calls to \ref setSelectableParts +*/ + +/* end of documentation of signals */ + +/*! + Constructs an Axis instance of Type \a type for the axis rect \a parent. + You shouldn't instantiate axes directly, rather use \ref QCPAxisRect::addAxis. +*/ +QCPAxis::QCPAxis(QCPAxisRect *parent, AxisType type) : + QCPLayerable(parent->parentPlot(), "", parent), + // axis base: + mAxisType(type), + mAxisRect(parent), + mPadding(5), + mOrientation(orientation(type)), + mSelectableParts(spAxis | spTickLabels | spAxisLabel), + mSelectedParts(spNone), + mBasePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedBasePen(QPen(Qt::blue, 2)), + // axis label: + mLabel(""), + mLabelFont(mParentPlot->font()), + mSelectedLabelFont(QFont(mLabelFont.family(), mLabelFont.pointSize(), QFont::Bold)), + mLabelColor(Qt::black), + mSelectedLabelColor(Qt::blue), + // tick labels: + mTickLabels(true), + mAutoTickLabels(true), + mTickLabelType(ltNumber), + mTickLabelFont(mParentPlot->font()), + mSelectedTickLabelFont(QFont(mTickLabelFont.family(), mTickLabelFont.pointSize(), QFont::Bold)), + mTickLabelColor(Qt::black), + mSelectedTickLabelColor(Qt::blue), + mDateTimeFormat("hh:mm:ss\ndd.MM.yy"), + mDateTimeSpec(Qt::LocalTime), + mNumberPrecision(6), + mNumberFormatChar('g'), + mNumberBeautifulPowers(true), + // ticks and subticks: + mTicks(true), + mTickStep(1), + mSubTickCount(4), + mAutoTickCount(6), + mAutoTicks(true), + mAutoTickStep(true), + mAutoSubTicks(true), + mTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedTickPen(QPen(Qt::blue, 2)), + mSubTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + mSelectedSubTickPen(QPen(Qt::blue, 2)), + // scale and range: + mRange(0, 5), + mRangeReversed(false), + mScaleType(stLinear), + mScaleLogBase(10), + mScaleLogBaseLogInv(1.0/qLn(mScaleLogBase)), + // internal members: + mGrid(new QCPGrid(this)), + mAxisPainter(new QCPAxisPainterPrivate(parent->parentPlot())), + mLowestVisibleTick(0), + mHighestVisibleTick(-1), + mCachedMarginValid(false), + mCachedMargin(0) +{ + mGrid->setVisible(false); + setAntialiased(false); + setLayer(mParentPlot->currentLayer()); // it's actually on that layer already, but we want it in front of the grid, so we place it on there again + + if (type == atTop) + { + setTickLabelPadding(3); + setLabelPadding(6); + } else if (type == atRight) + { + setTickLabelPadding(7); + setLabelPadding(12); + } else if (type == atBottom) + { + setTickLabelPadding(3); + setLabelPadding(3); + } else if (type == atLeft) + { + setTickLabelPadding(5); + setLabelPadding(10); + } +} + +QCPAxis::~QCPAxis() +{ + delete mAxisPainter; +} + +/* No documentation as it is a property getter */ +int QCPAxis::tickLabelPadding() const +{ + return mAxisPainter->tickLabelPadding; +} + +/* No documentation as it is a property getter */ +double QCPAxis::tickLabelRotation() const +{ + return mAxisPainter->tickLabelRotation; +} + +/* No documentation as it is a property getter */ +QCPAxis::LabelSide QCPAxis::tickLabelSide() const +{ + return mAxisPainter->tickLabelSide; +} + +/* No documentation as it is a property getter */ +QString QCPAxis::numberFormat() const +{ + QString result; + result.append(mNumberFormatChar); + if (mNumberBeautifulPowers) + { + result.append("b"); + if (mAxisPainter->numberMultiplyCross) + result.append("c"); + } + return result; +} + +/* No documentation as it is a property getter */ +int QCPAxis::tickLengthIn() const +{ + return mAxisPainter->tickLengthIn; +} + +/* No documentation as it is a property getter */ +int QCPAxis::tickLengthOut() const +{ + return mAxisPainter->tickLengthOut; +} + +/* No documentation as it is a property getter */ +int QCPAxis::subTickLengthIn() const +{ + return mAxisPainter->subTickLengthIn; +} + +/* No documentation as it is a property getter */ +int QCPAxis::subTickLengthOut() const +{ + return mAxisPainter->subTickLengthOut; +} + +/* No documentation as it is a property getter */ +int QCPAxis::labelPadding() const +{ + return mAxisPainter->labelPadding; +} + +/* No documentation as it is a property getter */ +int QCPAxis::offset() const +{ + return mAxisPainter->offset; +} + +/* No documentation as it is a property getter */ +QCPLineEnding QCPAxis::lowerEnding() const +{ + return mAxisPainter->lowerEnding; +} + +/* No documentation as it is a property getter */ +QCPLineEnding QCPAxis::upperEnding() const +{ + return mAxisPainter->upperEnding; +} + +/*! + Sets whether the axis uses a linear scale or a logarithmic scale. If \a type is set to \ref + stLogarithmic, the logarithm base can be set with \ref setScaleLogBase. In logarithmic axis + scaling, major tick marks appear at all powers of the logarithm base. Properties like tick step + (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but less major + ticks, consider choosing a logarithm base of 100, 1000 or even higher. + + If \a type is \ref stLogarithmic and the number format (\ref setNumberFormat) uses the 'b' option + (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10 + [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]" + part). To only display the decimal power, set the number precision to zero with + \ref setNumberPrecision. +*/ +void QCPAxis::setScaleType(QCPAxis::ScaleType type) +{ + if (mScaleType != type) + { + mScaleType = type; + if (mScaleType == stLogarithmic) + setRange(mRange.sanitizedForLogScale()); + mCachedMarginValid = false; + emit scaleTypeChanged(mScaleType); + } +} + +/*! + If \ref setScaleType is set to \ref stLogarithmic, \a base will be the logarithm base of the + scaling. In logarithmic axis scaling, major tick marks appear at all powers of \a base. + + Properties like tick step (\ref setTickStep) don't apply in logarithmic scaling. If you wish a decimal base but + less major ticks, consider choosing \a base 100, 1000 or even higher. +*/ +void QCPAxis::setScaleLogBase(double base) +{ + if (base > 1) + { + mScaleLogBase = base; + mScaleLogBaseLogInv = 1.0/qLn(mScaleLogBase); // buffer for faster baseLog() calculation + mCachedMarginValid = false; + } else + qDebug() << Q_FUNC_INFO << "Invalid logarithmic scale base (must be greater 1):" << base; +} + +/*! + Sets the range of the axis. + + This slot may be connected with the \ref rangeChanged signal of another axis so this axis + is always synchronized with the other axis range, when it changes. + + To invert the direction of an axis, use \ref setRangeReversed. +*/ +void QCPAxis::setRange(const QCPRange &range) +{ + if (range.lower == mRange.lower && range.upper == mRange.upper) + return; + + if (!QCPRange::validRange(range)) return; + QCPRange oldRange = mRange; + if (mScaleType == stLogarithmic) + { + mRange = range.sanitizedForLogScale(); + } else + { + mRange = range.sanitizedForLinScale(); + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); +} + +/*! + Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. + (When \ref QCustomPlot::setInteractions contains iSelectAxes.) + + However, even when \a selectable is set to a value not allowing the selection of a specific part, + it is still possible to set the selection of this part manually, by calling \ref setSelectedParts + directly. + + \see SelectablePart, setSelectedParts +*/ +void QCPAxis::setSelectableParts(const SelectableParts &selectable) +{ + if (mSelectableParts != selectable) + { + mSelectableParts = selectable; + emit selectableChanged(mSelectableParts); + } +} + +/*! + Sets the selected state of the respective axis parts described by \ref SelectablePart. When a part + is selected, it uses a different pen/font. + + The entire selection mechanism for axes is handled automatically when \ref + QCustomPlot::setInteractions contains iSelectAxes. You only need to call this function when you + wish to change the selection state manually. + + This function can change the selection state of a part, independent of the \ref setSelectableParts setting. + + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. + + \see SelectablePart, setSelectableParts, selectTest, setSelectedBasePen, setSelectedTickPen, setSelectedSubTickPen, + setSelectedTickLabelFont, setSelectedLabelFont, setSelectedTickLabelColor, setSelectedLabelColor +*/ +void QCPAxis::setSelectedParts(const SelectableParts &selected) +{ + if (mSelectedParts != selected) + { + mSelectedParts = selected; + emit selectionChanged(mSelectedParts); + } +} + +/*! + \overload + + Sets the lower and upper bound of the axis range. + + To invert the direction of an axis, use \ref setRangeReversed. + + There is also a slot to set a range, see \ref setRange(const QCPRange &range). +*/ +void QCPAxis::setRange(double lower, double upper) +{ + if (lower == mRange.lower && upper == mRange.upper) + return; + + if (!QCPRange::validRange(lower, upper)) return; + QCPRange oldRange = mRange; + mRange.lower = lower; + mRange.upper = upper; + if (mScaleType == stLogarithmic) + { + mRange = mRange.sanitizedForLogScale(); + } else + { + mRange = mRange.sanitizedForLinScale(); + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); +} + +/*! + \overload + + Sets the range of the axis. + + The \a position coordinate indicates together with the \a alignment parameter, where the new + range will be positioned. \a size defines the size of the new axis range. \a alignment may be + Qt::AlignLeft, Qt::AlignRight or Qt::AlignCenter. This will cause the left border, right border, + or center of the range to be aligned with \a position. Any other values of \a alignment will + default to Qt::AlignCenter. +*/ +void QCPAxis::setRange(double position, double size, Qt::AlignmentFlag alignment) +{ + if (alignment == Qt::AlignLeft) + setRange(position, position+size); + else if (alignment == Qt::AlignRight) + setRange(position-size, position); + else // alignment == Qt::AlignCenter + setRange(position-size/2.0, position+size/2.0); +} + +/*! + Sets the lower bound of the axis range. The upper bound is not changed. + \see setRange +*/ +void QCPAxis::setRangeLower(double lower) +{ + if (mRange.lower == lower) + return; + + QCPRange oldRange = mRange; + mRange.lower = lower; + if (mScaleType == stLogarithmic) + { + mRange = mRange.sanitizedForLogScale(); + } else + { + mRange = mRange.sanitizedForLinScale(); + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); +} + +/*! + Sets the upper bound of the axis range. The lower bound is not changed. + \see setRange +*/ +void QCPAxis::setRangeUpper(double upper) +{ + if (mRange.upper == upper) + return; + + QCPRange oldRange = mRange; + mRange.upper = upper; + if (mScaleType == stLogarithmic) + { + mRange = mRange.sanitizedForLogScale(); + } else + { + mRange = mRange.sanitizedForLinScale(); + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); +} + +/*! + Sets whether the axis range (direction) is displayed reversed. Normally, the values on horizontal + axes increase left to right, on vertical axes bottom to top. When \a reversed is set to true, the + direction of increasing values is inverted. + + Note that the range and data interface stays the same for reversed axes, e.g. the \a lower part + of the \ref setRange interface will still reference the mathematically smaller number than the \a + upper part. +*/ +void QCPAxis::setRangeReversed(bool reversed) +{ + if (mRangeReversed != reversed) + { + mRangeReversed = reversed; + mCachedMarginValid = false; + } +} + +/*! + Sets whether the tick positions should be calculated automatically (either from an automatically + generated tick step or a tick step provided manually via \ref setTickStep, see \ref setAutoTickStep). + + If \a on is set to false, you must provide the tick positions manually via \ref setTickVector. + For these manual ticks you may let QCPAxis generate the appropriate labels automatically by + leaving \ref setAutoTickLabels set to true. If you also wish to control the displayed labels + manually, set \ref setAutoTickLabels to false and provide the label strings with \ref + setTickVectorLabels. + + If you need dynamically calculated tick vectors (and possibly tick label vectors), set the + vectors in a slot connected to the \ref ticksRequest signal. + + \see setAutoTickLabels, setAutoSubTicks, setAutoTickCount, setAutoTickStep +*/ +void QCPAxis::setAutoTicks(bool on) +{ + if (mAutoTicks != on) + { + mAutoTicks = on; + mCachedMarginValid = false; + } +} + +/*! + When \ref setAutoTickStep is true, \a approximateCount determines how many ticks should be + generated in the visible range, approximately. + + It's not guaranteed that this number of ticks is met exactly, but approximately within a + tolerance of about two. + + Only values greater than zero are accepted as \a approximateCount. + + \see setAutoTickStep, setAutoTicks, setAutoSubTicks +*/ +void QCPAxis::setAutoTickCount(int approximateCount) +{ + if (mAutoTickCount != approximateCount) + { + if (approximateCount > 0) + { + mAutoTickCount = approximateCount; + mCachedMarginValid = false; + } else + qDebug() << Q_FUNC_INFO << "approximateCount must be greater than zero:" << approximateCount; + } +} + +/*! + Sets whether the tick labels are generated automatically. Depending on the tick label type (\ref + ltNumber or \ref ltDateTime), the labels will either show the coordinate as floating point + number (\ref setNumberFormat), or a date/time formatted according to \ref setDateTimeFormat. + + If \a on is set to false, you should provide the tick labels via \ref setTickVectorLabels. This + is usually used in a combination with \ref setAutoTicks set to false for complete control over + tick positions and labels, e.g. when the ticks should be at multiples of pi and show "2pi", "3pi" + etc. as tick labels. + + If you need dynamically calculated tick vectors (and possibly tick label vectors), set the + vectors in a slot connected to the \ref ticksRequest signal. + + \see setAutoTicks +*/ +void QCPAxis::setAutoTickLabels(bool on) +{ + if (mAutoTickLabels != on) + { + mAutoTickLabels = on; + mCachedMarginValid = false; + } +} + +/*! + Sets whether the tick step, i.e. the interval between two (major) ticks, is calculated + automatically. If \a on is set to true, the axis finds a tick step that is reasonable for human + readable plots. + + The number of ticks the algorithm aims for within the visible range can be specified with \ref + setAutoTickCount. + + If \a on is set to false, you may set the tick step manually with \ref setTickStep. + + \see setAutoTicks, setAutoSubTicks, setAutoTickCount +*/ +void QCPAxis::setAutoTickStep(bool on) +{ + if (mAutoTickStep != on) + { + mAutoTickStep = on; + mCachedMarginValid = false; + } +} + +/*! + Sets whether the number of sub ticks in one tick interval is determined automatically. This + works, as long as the tick step mantissa is a multiple of 0.5. When \ref setAutoTickStep is + enabled, this is always the case. + + When \a on is set to false, you may set the sub tick count with \ref setSubTickCount manually. + + \see setAutoTickCount, setAutoTicks, setAutoTickStep +*/ +void QCPAxis::setAutoSubTicks(bool on) +{ + if (mAutoSubTicks != on) + { + mAutoSubTicks = on; + mCachedMarginValid = false; + } +} + +/*! + Sets whether tick marks are displayed. + + Note that setting \a show to false does not imply that tick labels are invisible, too. To achieve + that, see \ref setTickLabels. +*/ +void QCPAxis::setTicks(bool show) +{ + if (mTicks != show) + { + mTicks = show; + mCachedMarginValid = false; + } +} + +/*! + Sets whether tick labels are displayed. Tick labels are the numbers drawn next to tick marks. +*/ +void QCPAxis::setTickLabels(bool show) +{ + if (mTickLabels != show) + { + mTickLabels = show; + mCachedMarginValid = false; + } +} + +/*! + Sets the distance between the axis base line (including any outward ticks) and the tick labels. + \see setLabelPadding, setPadding +*/ +void QCPAxis::setTickLabelPadding(int padding) +{ + if (mAxisPainter->tickLabelPadding != padding) + { + mAxisPainter->tickLabelPadding = padding; + mCachedMarginValid = false; + } +} + +/*! + Sets whether the tick labels display numbers or dates/times. + + If \a type is set to \ref ltNumber, the format specifications of \ref setNumberFormat apply. + + If \a type is set to \ref ltDateTime, the format specifications of \ref setDateTimeFormat apply. + + In QCustomPlot, date/time coordinates are double numbers representing the seconds since + 1970-01-01T00:00:00 UTC. This format can be retrieved from QDateTime objects with the + QDateTime::toTime_t() function. Since this only gives a resolution of one second, there is also + the QDateTime::toMSecsSinceEpoch() function which returns the timespan described above in + milliseconds. Divide its return value by 1000.0 to get a value with the format needed for + date/time plotting, with a resolution of one millisecond. + + Using the toMSecsSinceEpoch function allows dates that go back to 2nd January 4713 B.C. + (represented by a negative number), unlike the toTime_t function, which works with unsigned + integers and thus only goes back to 1st January 1970. So both for range and accuracy, use of + toMSecsSinceEpoch()/1000.0 should be preferred as key coordinate for date/time axes. + + \see setTickLabels +*/ +void QCPAxis::setTickLabelType(LabelType type) +{ + if (mTickLabelType != type) + { + mTickLabelType = type; + mCachedMarginValid = false; + } +} + +/*! + Sets the font of the tick labels. + + \see setTickLabels, setTickLabelColor +*/ +void QCPAxis::setTickLabelFont(const QFont &font) +{ + if (font != mTickLabelFont) + { + mTickLabelFont = font; + mCachedMarginValid = false; + } +} + +/*! + Sets the color of the tick labels. + + \see setTickLabels, setTickLabelFont +*/ +void QCPAxis::setTickLabelColor(const QColor &color) +{ + if (color != mTickLabelColor) + { + mTickLabelColor = color; + mCachedMarginValid = false; + } +} + +/*! + Sets the rotation of the tick labels. If \a degrees is zero, the labels are drawn normally. Else, + the tick labels are drawn rotated by \a degrees clockwise. The specified angle is bound to values + from -90 to 90 degrees. + + If \a degrees is exactly -90, 0 or 90, the tick labels are centered on the tick coordinate. For + other angles, the label is drawn with an offset such that it seems to point toward or away from + the tick mark. +*/ +void QCPAxis::setTickLabelRotation(double degrees) +{ + if (!qFuzzyIsNull(degrees-mAxisPainter->tickLabelRotation)) + { + mAxisPainter->tickLabelRotation = qBound(-90.0, degrees, 90.0); + mCachedMarginValid = false; + } +} + +/*! + Sets whether the tick labels (numbers) shall appear inside or outside the axis rect. + + The usual and default setting is \ref lsOutside. Very compact plots sometimes require tick labels + to be inside the axis rect, to save space. If \a side is set to \ref lsInside, the tick labels + appear on the inside are additionally clipped to the axis rect. +*/ +void QCPAxis::setTickLabelSide(LabelSide side) +{ + mAxisPainter->tickLabelSide = side; + mCachedMarginValid = false; +} + +/*! + Sets the format in which dates and times are displayed as tick labels, if \ref setTickLabelType is \ref ltDateTime. + for details about the \a format string, see the documentation of QDateTime::toString(). + + Newlines can be inserted with "\n". + + \see setDateTimeSpec +*/ +void QCPAxis::setDateTimeFormat(const QString &format) +{ + if (mDateTimeFormat != format) + { + mDateTimeFormat = format; + mCachedMarginValid = false; + } +} + +/*! + Sets the time spec that is used for the date time values when \ref setTickLabelType is \ref + ltDateTime. + + The default value of QDateTime objects (and also QCustomPlot) is Qt::LocalTime. However, + if the date time values passed to QCustomPlot are given in the UTC spec, set \a + timeSpec to Qt::UTC to get the correct axis labels. + + \see setDateTimeFormat +*/ +void QCPAxis::setDateTimeSpec(const Qt::TimeSpec &timeSpec) +{ + mDateTimeSpec = timeSpec; +} + +/*! + Sets the number format for the numbers drawn as tick labels (if tick label type is \ref + ltNumber). This \a formatCode is an extended version of the format code used e.g. by + QString::number() and QLocale::toString(). For reference about that, see the "Argument Formats" + section in the detailed description of the QString class. \a formatCode is a string of one, two + or three characters. The first character is identical to the normal format code used by Qt. In + short, this means: 'e'/'E' scientific format, 'f' fixed format, 'g'/'G' scientific or fixed, + whichever is shorter. + + The second and third characters are optional and specific to QCustomPlot:\n + If the first char was 'e' or 'g', numbers are/might be displayed in the scientific format, e.g. + "5.5e9", which is ugly in a plot. So when the second char of \a formatCode is set to 'b' (for + "beautiful"), those exponential numbers are formatted in a more natural way, i.e. "5.5 + [multiplication sign] 10 [superscript] 9". By default, the multiplication sign is a centered dot. + If instead a cross should be shown (as is usual in the USA), the third char of \a formatCode can + be set to 'c'. The inserted multiplication signs are the UTF-8 characters 215 (0xD7) for the + cross and 183 (0xB7) for the dot. + + If the scale type (\ref setScaleType) is \ref stLogarithmic and the \a formatCode uses the 'b' + option (beautifully typeset decimal powers), the display usually is "1 [multiplication sign] 10 + [superscript] n", which looks unnatural for logarithmic scaling (the "1 [multiplication sign]" + part). To only display the decimal power, set the number precision to zero with \ref + setNumberPrecision. + + Examples for \a formatCode: + \li \c g normal format code behaviour. If number is small, fixed format is used, if number is large, + normal scientific format is used + \li \c gb If number is small, fixed format is used, if number is large, scientific format is used with + beautifully typeset decimal powers and a dot as multiplication sign + \li \c ebc All numbers are in scientific format with beautifully typeset decimal power and a cross as + multiplication sign + \li \c fb illegal format code, since fixed format doesn't support (or need) beautifully typeset decimal + powers. Format code will be reduced to 'f'. + \li \c hello illegal format code, since first char is not 'e', 'E', 'f', 'g' or 'G'. Current format + code will not be changed. +*/ +void QCPAxis::setNumberFormat(const QString &formatCode) +{ + if (formatCode.isEmpty()) + { + qDebug() << Q_FUNC_INFO << "Passed formatCode is empty"; + return; + } + mCachedMarginValid = false; + + // interpret first char as number format char: + QString allowedFormatChars = "eEfgG"; + if (allowedFormatChars.contains(formatCode.at(0))) + { + mNumberFormatChar = formatCode.at(0).toLatin1(); + } else + { + qDebug() << Q_FUNC_INFO << "Invalid number format code (first char not in 'eEfgG'):" << formatCode; + return; + } + if (formatCode.length() < 2) + { + mNumberBeautifulPowers = false; + mAxisPainter->numberMultiplyCross = false; + return; + } + + // interpret second char as indicator for beautiful decimal powers: + if (formatCode.at(1) == 'b' && (mNumberFormatChar == 'e' || mNumberFormatChar == 'g')) + { + mNumberBeautifulPowers = true; + } else + { + qDebug() << Q_FUNC_INFO << "Invalid number format code (second char not 'b' or first char neither 'e' nor 'g'):" << formatCode; + return; + } + if (formatCode.length() < 3) + { + mAxisPainter->numberMultiplyCross = false; + return; + } + + // interpret third char as indicator for dot or cross multiplication symbol: + if (formatCode.at(2) == 'c') + { + mAxisPainter->numberMultiplyCross = true; + } else if (formatCode.at(2) == 'd') + { + mAxisPainter->numberMultiplyCross = false; + } else + { + qDebug() << Q_FUNC_INFO << "Invalid number format code (third char neither 'c' nor 'd'):" << formatCode; + return; + } +} + +/*! + Sets the precision of the tick label numbers. See QLocale::toString(double i, char f, int prec) + for details. The effect of precisions are most notably for number Formats starting with 'e', see + \ref setNumberFormat + + If the scale type (\ref setScaleType) is \ref stLogarithmic and the number format (\ref + setNumberFormat) uses the 'b' format code (beautifully typeset decimal powers), the display + usually is "1 [multiplication sign] 10 [superscript] n", which looks unnatural for logarithmic + scaling (the redundant "1 [multiplication sign]" part). To only display the decimal power "10 + [superscript] n", set \a precision to zero. +*/ +void QCPAxis::setNumberPrecision(int precision) +{ + if (mNumberPrecision != precision) + { + mNumberPrecision = precision; + mCachedMarginValid = false; + } +} + +/*! + If \ref setAutoTickStep is set to false, use this function to set the tick step manually. + The tick step is the interval between (major) ticks, in plot coordinates. + \see setSubTickCount +*/ +void QCPAxis::setTickStep(double step) +{ + if (mTickStep != step) + { + mTickStep = step; + mCachedMarginValid = false; + } +} + +/*! + If you want full control over what ticks (and possibly labels) the axes show, this function is + used to set the coordinates at which ticks will appear.\ref setAutoTicks must be disabled, else + the provided tick vector will be overwritten with automatically generated tick coordinates upon + replot. The labels of the ticks can be generated automatically when \ref setAutoTickLabels is + left enabled. If it is disabled, you can set the labels manually with \ref setTickVectorLabels. + + \a vec is a vector containing the positions of the ticks, in plot coordinates. + + \warning \a vec must be sorted in ascending order, no additional checks are made to ensure this. + + \see setTickVectorLabels +*/ +void QCPAxis::setTickVector(const QVector &vec) +{ + // don't check whether mTickVector != vec here, because it takes longer than we would save + mTickVector = vec; + mCachedMarginValid = false; +} + +/*! + If you want full control over what ticks and labels the axes show, this function is used to set a + number of QStrings that will be displayed at the tick positions which you need to provide with + \ref setTickVector. These two vectors should have the same size. (Note that you need to disable + \ref setAutoTicks and \ref setAutoTickLabels first.) + + \a vec is a vector containing the labels of the ticks. The entries correspond to the respective + indices in the tick vector, passed via \ref setTickVector. + + \see setTickVector +*/ +void QCPAxis::setTickVectorLabels(const QVector &vec) +{ + // don't check whether mTickVectorLabels != vec here, because it takes longer than we would save + mTickVectorLabels = vec; + mCachedMarginValid = false; +} + +/*! + Sets the length of the ticks in pixels. \a inside is the length the ticks will reach inside the + plot and \a outside is the length they will reach outside the plot. If \a outside is greater than + zero, the tick labels and axis label will increase their distance to the axis accordingly, so + they won't collide with the ticks. + + \see setSubTickLength, setTickLengthIn, setTickLengthOut +*/ +void QCPAxis::setTickLength(int inside, int outside) +{ + setTickLengthIn(inside); + setTickLengthOut(outside); +} + +/*! + Sets the length of the inward ticks in pixels. \a inside is the length the ticks will reach + inside the plot. + + \see setTickLengthOut, setTickLength, setSubTickLength +*/ +void QCPAxis::setTickLengthIn(int inside) +{ + if (mAxisPainter->tickLengthIn != inside) + { + mAxisPainter->tickLengthIn = inside; + } +} + +/*! + Sets the length of the outward ticks in pixels. \a outside is the length the ticks will reach + outside the plot. If \a outside is greater than zero, the tick labels and axis label will + increase their distance to the axis accordingly, so they won't collide with the ticks. + + \see setTickLengthIn, setTickLength, setSubTickLength +*/ +void QCPAxis::setTickLengthOut(int outside) +{ + if (mAxisPainter->tickLengthOut != outside) + { + mAxisPainter->tickLengthOut = outside; + mCachedMarginValid = false; // only outside tick length can change margin + } +} + +/*! + Sets the number of sub ticks in one (major) tick step. A sub tick count of three for example, + divides the tick intervals in four sub intervals. + + By default, the number of sub ticks is chosen automatically in a reasonable manner as long as the + mantissa of the tick step is a multiple of 0.5. When \ref setAutoTickStep is enabled, this is + always the case. + + If you want to disable automatic sub tick count and use this function to set the count manually, + see \ref setAutoSubTicks. +*/ +void QCPAxis::setSubTickCount(int count) +{ + mSubTickCount = count; +} + +/*! + Sets the length of the subticks in pixels. \a inside is the length the subticks will reach inside + the plot and \a outside is the length they will reach outside the plot. If \a outside is greater + than zero, the tick labels and axis label will increase their distance to the axis accordingly, + so they won't collide with the ticks. + + \see setTickLength, setSubTickLengthIn, setSubTickLengthOut +*/ +void QCPAxis::setSubTickLength(int inside, int outside) +{ + setSubTickLengthIn(inside); + setSubTickLengthOut(outside); +} + +/*! + Sets the length of the inward subticks in pixels. \a inside is the length the subticks will reach inside + the plot. + + \see setSubTickLengthOut, setSubTickLength, setTickLength +*/ +void QCPAxis::setSubTickLengthIn(int inside) +{ + if (mAxisPainter->subTickLengthIn != inside) + { + mAxisPainter->subTickLengthIn = inside; + } +} + +/*! + Sets the length of the outward subticks in pixels. \a outside is the length the subticks will reach + outside the plot. If \a outside is greater than zero, the tick labels will increase their + distance to the axis accordingly, so they won't collide with the ticks. + + \see setSubTickLengthIn, setSubTickLength, setTickLength +*/ +void QCPAxis::setSubTickLengthOut(int outside) +{ + if (mAxisPainter->subTickLengthOut != outside) + { + mAxisPainter->subTickLengthOut = outside; + mCachedMarginValid = false; // only outside tick length can change margin + } +} + +/*! + Sets the pen, the axis base line is drawn with. + + \see setTickPen, setSubTickPen +*/ +void QCPAxis::setBasePen(const QPen &pen) +{ + mBasePen = pen; +} + +/*! + Sets the pen, tick marks will be drawn with. + + \see setTickLength, setBasePen +*/ +void QCPAxis::setTickPen(const QPen &pen) +{ + mTickPen = pen; +} + +/*! + Sets the pen, subtick marks will be drawn with. + + \see setSubTickCount, setSubTickLength, setBasePen +*/ +void QCPAxis::setSubTickPen(const QPen &pen) +{ + mSubTickPen = pen; +} + +/*! + Sets the font of the axis label. + + \see setLabelColor +*/ +void QCPAxis::setLabelFont(const QFont &font) +{ + if (mLabelFont != font) + { + mLabelFont = font; + mCachedMarginValid = false; + } +} + +/*! + Sets the color of the axis label. + + \see setLabelFont +*/ +void QCPAxis::setLabelColor(const QColor &color) +{ + mLabelColor = color; +} + +/*! + Sets the text of the axis label that will be shown below/above or next to the axis, depending on + its orientation. To disable axis labels, pass an empty string as \a str. +*/ +void QCPAxis::setLabel(const QString &str) +{ + if (mLabel != str) + { + mLabel = str; + mCachedMarginValid = false; + } +} + +/*! + Sets the distance between the tick labels and the axis label. + + \see setTickLabelPadding, setPadding +*/ +void QCPAxis::setLabelPadding(int padding) +{ + if (mAxisPainter->labelPadding != padding) + { + mAxisPainter->labelPadding = padding; + mCachedMarginValid = false; + } +} + +/*! + Sets the padding of the axis. + + When \ref QCPAxisRect::setAutoMargins is enabled, the padding is the additional outer most space, + that is left blank. + + The axis padding has no meaning if \ref QCPAxisRect::setAutoMargins is disabled. + + \see setLabelPadding, setTickLabelPadding +*/ +void QCPAxis::setPadding(int padding) +{ + if (mPadding != padding) + { + mPadding = padding; + mCachedMarginValid = false; + } +} + +/*! + Sets the offset the axis has to its axis rect side. + + If an axis rect side has multiple axes and automatic margin calculation is enabled for that side, + only the offset of the inner most axis has meaning (even if it is set to be invisible). The + offset of the other, outer axes is controlled automatically, to place them at appropriate + positions. +*/ +void QCPAxis::setOffset(int offset) +{ + mAxisPainter->offset = offset; +} + +/*! + Sets the font that is used for tick labels when they are selected. + + \see setTickLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAxis::setSelectedTickLabelFont(const QFont &font) +{ + if (font != mSelectedTickLabelFont) + { + mSelectedTickLabelFont = font; + // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts + } +} + +/*! + Sets the font that is used for the axis label when it is selected. + + \see setLabelFont, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAxis::setSelectedLabelFont(const QFont &font) +{ + mSelectedLabelFont = font; + // don't set mCachedMarginValid to false here because margin calculation is always done with non-selected fonts +} + +/*! + Sets the color that is used for tick labels when they are selected. + + \see setTickLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAxis::setSelectedTickLabelColor(const QColor &color) +{ + if (color != mSelectedTickLabelColor) + { + mSelectedTickLabelColor = color; + } +} + +/*! + Sets the color that is used for the axis label when it is selected. + + \see setLabelColor, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAxis::setSelectedLabelColor(const QColor &color) +{ + mSelectedLabelColor = color; +} + +/*! + Sets the pen that is used to draw the axis base line when selected. + + \see setBasePen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAxis::setSelectedBasePen(const QPen &pen) +{ + mSelectedBasePen = pen; +} + +/*! + Sets the pen that is used to draw the (major) ticks when selected. + + \see setTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAxis::setSelectedTickPen(const QPen &pen) +{ + mSelectedTickPen = pen; +} + +/*! + Sets the pen that is used to draw the subticks when selected. + + \see setSubTickPen, setSelectableParts, setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAxis::setSelectedSubTickPen(const QPen &pen) +{ + mSelectedSubTickPen = pen; +} + +/*! + Sets the style for the lower axis ending. See the documentation of QCPLineEnding for available + styles. + + For horizontal axes, this method refers to the left ending, for vertical axes the bottom ending. + Note that this meaning does not change when the axis range is reversed with \ref + setRangeReversed. + + \see setUpperEnding +*/ +void QCPAxis::setLowerEnding(const QCPLineEnding &ending) +{ + mAxisPainter->lowerEnding = ending; +} + +/*! + Sets the style for the upper axis ending. See the documentation of QCPLineEnding for available + styles. + + For horizontal axes, this method refers to the right ending, for vertical axes the top ending. + Note that this meaning does not change when the axis range is reversed with \ref + setRangeReversed. + + \see setLowerEnding +*/ +void QCPAxis::setUpperEnding(const QCPLineEnding &ending) +{ + mAxisPainter->upperEnding = ending; +} + +/*! + If the scale type (\ref setScaleType) is \ref stLinear, \a diff is added to the lower and upper + bounds of the range. The range is simply moved by \a diff. + + If the scale type is \ref stLogarithmic, the range bounds are multiplied by \a diff. This + corresponds to an apparent "linear" move in logarithmic scaling by a distance of log(diff). +*/ +void QCPAxis::moveRange(double diff) +{ + QCPRange oldRange = mRange; + if (mScaleType == stLinear) + { + mRange.lower += diff; + mRange.upper += diff; + } else // mScaleType == stLogarithmic + { + mRange.lower *= diff; + mRange.upper *= diff; + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); +} + +/*! + Scales the range of this axis by \a factor around the coordinate \a center. For example, if \a + factor is 2.0, \a center is 1.0, then the axis range will double its size, and the point at + coordinate 1.0 won't have changed its position in the QCustomPlot widget (i.e. coordinates + around 1.0 will have moved symmetrically closer to 1.0). +*/ +void QCPAxis::scaleRange(double factor, double center) +{ + QCPRange oldRange = mRange; + if (mScaleType == stLinear) + { + QCPRange newRange; + newRange.lower = (mRange.lower-center)*factor + center; + newRange.upper = (mRange.upper-center)*factor + center; + if (QCPRange::validRange(newRange)) + mRange = newRange.sanitizedForLinScale(); + } else // mScaleType == stLogarithmic + { + if ((mRange.upper < 0 && center < 0) || (mRange.upper > 0 && center > 0)) // make sure center has same sign as range + { + QCPRange newRange; + newRange.lower = qPow(mRange.lower/center, factor)*center; + newRange.upper = qPow(mRange.upper/center, factor)*center; + if (QCPRange::validRange(newRange)) + mRange = newRange.sanitizedForLogScale(); + } else + qDebug() << Q_FUNC_INFO << "Center of scaling operation doesn't lie in same logarithmic sign domain as range:" << center; + } + mCachedMarginValid = false; + emit rangeChanged(mRange); + emit rangeChanged(mRange, oldRange); +} + +/*! + Scales the range of this axis to have a certain scale \a ratio to \a otherAxis. The scaling will + be done around the center of the current axis range. + + For example, if \a ratio is 1, this axis is the \a yAxis and \a otherAxis is \a xAxis, graphs + plotted with those axes will appear in a 1:1 aspect ratio, independent of the aspect ratio the + axis rect has. + + This is an operation that changes the range of this axis once, it doesn't fix the scale ratio + indefinitely. Note that calling this function in the constructor of the QCustomPlot's parent + won't have the desired effect, since the widget dimensions aren't defined yet, and a resizeEvent + will follow. +*/ +void QCPAxis::setScaleRatio(const QCPAxis *otherAxis, double ratio) +{ + int otherPixelSize, ownPixelSize; + + if (otherAxis->orientation() == Qt::Horizontal) + otherPixelSize = otherAxis->axisRect()->width(); + else + otherPixelSize = otherAxis->axisRect()->height(); + + if (orientation() == Qt::Horizontal) + ownPixelSize = axisRect()->width(); + else + ownPixelSize = axisRect()->height(); + + double newRangeSize = ratio*otherAxis->range().size()*ownPixelSize/(double)otherPixelSize; + setRange(range().center(), newRangeSize, Qt::AlignCenter); +} + +/*! + Changes the axis range such that all plottables associated with this axis are fully visible in + that dimension. + + \see QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes +*/ +void QCPAxis::rescale(bool onlyVisiblePlottables) +{ + QList p = plottables(); + QCPRange newRange; + bool haveRange = false; + for (int i=0; irealVisibility() && onlyVisiblePlottables) + continue; + QCPRange plottableRange; + bool currentFoundRange; + QCPAbstractPlottable::SignDomain signDomain = QCPAbstractPlottable::sdBoth; + if (mScaleType == stLogarithmic) + signDomain = (mRange.upper < 0 ? QCPAbstractPlottable::sdNegative : QCPAbstractPlottable::sdPositive); + if (p.at(i)->keyAxis() == this) + plottableRange = p.at(i)->getKeyRange(currentFoundRange, signDomain); + else + plottableRange = p.at(i)->getValueRange(currentFoundRange, signDomain); + if (currentFoundRange) + { + if (!haveRange) + newRange = plottableRange; + else + newRange.expand(plottableRange); + haveRange = true; + } + } + if (haveRange) + { + if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + { + double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (mScaleType == stLinear) + { + newRange.lower = center-mRange.size()/2.0; + newRange.upper = center+mRange.size()/2.0; + } else // mScaleType == stLogarithmic + { + newRange.lower = center/qSqrt(mRange.upper/mRange.lower); + newRange.upper = center*qSqrt(mRange.upper/mRange.lower); + } + } + setRange(newRange); + } +} + +/*! + Transforms \a value, in pixel coordinates of the QCustomPlot widget, to axis coordinates. +*/ +double QCPAxis::pixelToCoord(double value) const +{ + if (orientation() == Qt::Horizontal) + { + if (mScaleType == stLinear) + { + if (!mRangeReversed) + return (value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.lower; + else + return -(value-mAxisRect->left())/(double)mAxisRect->width()*mRange.size()+mRange.upper; + } else // mScaleType == stLogarithmic + { + if (!mRangeReversed) + return qPow(mRange.upper/mRange.lower, (value-mAxisRect->left())/(double)mAxisRect->width())*mRange.lower; + else + return qPow(mRange.upper/mRange.lower, (mAxisRect->left()-value)/(double)mAxisRect->width())*mRange.upper; + } + } else // orientation() == Qt::Vertical + { + if (mScaleType == stLinear) + { + if (!mRangeReversed) + return (mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.lower; + else + return -(mAxisRect->bottom()-value)/(double)mAxisRect->height()*mRange.size()+mRange.upper; + } else // mScaleType == stLogarithmic + { + if (!mRangeReversed) + return qPow(mRange.upper/mRange.lower, (mAxisRect->bottom()-value)/(double)mAxisRect->height())*mRange.lower; + else + return qPow(mRange.upper/mRange.lower, (value-mAxisRect->bottom())/(double)mAxisRect->height())*mRange.upper; + } + } +} + +/*! + Transforms \a value, in coordinates of the axis, to pixel coordinates of the QCustomPlot widget. +*/ +double QCPAxis::coordToPixel(double value) const +{ + if (orientation() == Qt::Horizontal) + { + if (mScaleType == stLinear) + { + if (!mRangeReversed) + return (value-mRange.lower)/mRange.size()*mAxisRect->width()+mAxisRect->left(); + else + return (mRange.upper-value)/mRange.size()*mAxisRect->width()+mAxisRect->left(); + } else // mScaleType == stLogarithmic + { + if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->right()+200 : mAxisRect->left()-200; + else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->left()-200 : mAxisRect->right()+200; + else + { + if (!mRangeReversed) + return baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); + else + return baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->width()+mAxisRect->left(); + } + } + } else // orientation() == Qt::Vertical + { + if (mScaleType == stLinear) + { + if (!mRangeReversed) + return mAxisRect->bottom()-(value-mRange.lower)/mRange.size()*mAxisRect->height(); + else + return mAxisRect->bottom()-(mRange.upper-value)/mRange.size()*mAxisRect->height(); + } else // mScaleType == stLogarithmic + { + if (value >= 0 && mRange.upper < 0) // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->top()-200 : mAxisRect->bottom()+200; + else if (value <= 0 && mRange.upper > 0) // invalid value for logarithmic scale, just draw it outside visible range + return !mRangeReversed ? mAxisRect->bottom()+200 : mAxisRect->top()-200; + else + { + if (!mRangeReversed) + return mAxisRect->bottom()-baseLog(value/mRange.lower)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height(); + else + return mAxisRect->bottom()-baseLog(mRange.upper/value)/baseLog(mRange.upper/mRange.lower)*mAxisRect->height(); + } + } + } +} + +/*! + Returns the part of the axis that is hit by \a pos (in pixels). The return value of this function + is independent of the user-selectable parts defined with \ref setSelectableParts. Further, this + function does not change the current selection state of the axis. + + If the axis is not visible (\ref setVisible), this function always returns \ref spNone. + + \see setSelectedParts, setSelectableParts, QCustomPlot::setInteractions +*/ +QCPAxis::SelectablePart QCPAxis::getPartAt(const QPointF &pos) const +{ + if (!mVisible) + return spNone; + + if (mAxisPainter->axisSelectionBox().contains(pos.toPoint())) + return spAxis; + else if (mAxisPainter->tickLabelsSelectionBox().contains(pos.toPoint())) + return spTickLabels; + else if (mAxisPainter->labelSelectionBox().contains(pos.toPoint())) + return spAxisLabel; + else + return spNone; +} + +/* inherits documentation from base class */ +double QCPAxis::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + if (!mParentPlot) return -1; + SelectablePart part = getPartAt(pos); + if ((onlySelectable && !mSelectableParts.testFlag(part)) || part == spNone) + return -1; + + if (details) + details->setValue(part); + return mParentPlot->selectionTolerance()*0.99; +} + +/*! + Returns a list of all the plottables that have this axis as key or value axis. + + If you are only interested in plottables of type QCPGraph, see \ref graphs. + + \see graphs, items +*/ +QList QCPAxis::plottables() const +{ + QList result; + if (!mParentPlot) return result; + + for (int i=0; imPlottables.size(); ++i) + { + if (mParentPlot->mPlottables.at(i)->keyAxis() == this ||mParentPlot->mPlottables.at(i)->valueAxis() == this) + result.append(mParentPlot->mPlottables.at(i)); + } + return result; +} + +/*! + Returns a list of all the graphs that have this axis as key or value axis. + + \see plottables, items +*/ +QList QCPAxis::graphs() const +{ + QList result; + if (!mParentPlot) return result; + + for (int i=0; imGraphs.size(); ++i) + { + if (mParentPlot->mGraphs.at(i)->keyAxis() == this || mParentPlot->mGraphs.at(i)->valueAxis() == this) + result.append(mParentPlot->mGraphs.at(i)); + } + return result; +} + +/*! + Returns a list of all the items that are associated with this axis. An item is considered + associated with an axis if at least one of its positions uses the axis as key or value axis. + + \see plottables, graphs +*/ +QList QCPAxis::items() const +{ + QList result; + if (!mParentPlot) return result; + + for (int itemId=0; itemIdmItems.size(); ++itemId) + { + QList positions = mParentPlot->mItems.at(itemId)->positions(); + for (int posId=0; posIdkeyAxis() == this || positions.at(posId)->valueAxis() == this) + { + result.append(mParentPlot->mItems.at(itemId)); + break; + } + } + } + return result; +} + +/*! + Transforms a margin side to the logically corresponding axis type. (QCP::msLeft to + QCPAxis::atLeft, QCP::msRight to QCPAxis::atRight, etc.) +*/ +QCPAxis::AxisType QCPAxis::marginSideToAxisType(QCP::MarginSide side) +{ + switch (side) + { + case QCP::msLeft: return atLeft; + case QCP::msRight: return atRight; + case QCP::msTop: return atTop; + case QCP::msBottom: return atBottom; + default: break; + } + qDebug() << Q_FUNC_INFO << "Invalid margin side passed:" << (int)side; + return atLeft; +} + +/*! + Returns the axis type that describes the opposite axis of an axis with the specified \a type. +*/ +QCPAxis::AxisType QCPAxis::opposite(QCPAxis::AxisType type) +{ + switch (type) + { + case atLeft: return atRight; break; + case atRight: return atLeft; break; + case atBottom: return atTop; break; + case atTop: return atBottom; break; + default: qDebug() << Q_FUNC_INFO << "invalid axis type"; return atLeft; break; + } +} + +/*! \internal + + This function is called to prepare the tick vector, sub tick vector and tick label vector. If + \ref setAutoTicks is set to true, appropriate tick values are determined automatically via \ref + generateAutoTicks. If it's set to false, the signal ticksRequest is emitted, which can be used to + provide external tick positions. Then the sub tick vectors and tick label vectors are created. +*/ +void QCPAxis::setupTickVectors() +{ + if (!mParentPlot) return; + if ((!mTicks && !mTickLabels && !mGrid->visible()) || mRange.size() <= 0) return; + + // fill tick vectors, either by auto generating or by notifying user to fill the vectors himself + if (mAutoTicks) + { + generateAutoTicks(); + } else + { + emit ticksRequest(); + } + + visibleTickBounds(mLowestVisibleTick, mHighestVisibleTick); + if (mTickVector.isEmpty()) + { + mSubTickVector.clear(); + return; + } + + // generate subticks between ticks: + mSubTickVector.resize((mTickVector.size()-1)*mSubTickCount); + if (mSubTickCount > 0) + { + double subTickStep = 0; + double subTickPosition = 0; + int subTickIndex = 0; + bool done = false; + int lowTick = mLowestVisibleTick > 0 ? mLowestVisibleTick-1 : mLowestVisibleTick; + int highTick = mHighestVisibleTick < mTickVector.size()-1 ? mHighestVisibleTick+1 : mHighestVisibleTick; + for (int i=lowTick+1; i<=highTick; ++i) + { + subTickStep = (mTickVector.at(i)-mTickVector.at(i-1))/(double)(mSubTickCount+1); + for (int k=1; k<=mSubTickCount; ++k) + { + subTickPosition = mTickVector.at(i-1) + k*subTickStep; + if (subTickPosition < mRange.lower) + continue; + if (subTickPosition > mRange.upper) + { + done = true; + break; + } + mSubTickVector[subTickIndex] = subTickPosition; + subTickIndex++; + } + if (done) break; + } + mSubTickVector.resize(subTickIndex); + } + + // generate tick labels according to tick positions: + if (mAutoTickLabels) + { + int vecsize = mTickVector.size(); + mTickVectorLabels.resize(vecsize); + if (mTickLabelType == ltNumber) + { + for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i) + mTickVectorLabels[i] = mParentPlot->locale().toString(mTickVector.at(i), mNumberFormatChar, mNumberPrecision); + } else if (mTickLabelType == ltDateTime) + { + for (int i=mLowestVisibleTick; i<=mHighestVisibleTick; ++i) + { +#if QT_VERSION < QT_VERSION_CHECK(4, 7, 0) // use fromMSecsSinceEpoch function if available, to gain sub-second accuracy on tick labels (e.g. for format "hh:mm:ss:zzz") + mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromTime_t(mTickVector.at(i)).toTimeSpec(mDateTimeSpec), mDateTimeFormat); +#else + mTickVectorLabels[i] = mParentPlot->locale().toString(QDateTime::fromMSecsSinceEpoch(mTickVector.at(i)*1000).toTimeSpec(mDateTimeSpec), mDateTimeFormat); +#endif + } + } + } else // mAutoTickLabels == false + { + if (mAutoTicks) // ticks generated automatically, but not ticklabels, so emit ticksRequest here for labels + { + emit ticksRequest(); + } + // make sure provided tick label vector has correct (minimal) length: + if (mTickVectorLabels.size() < mTickVector.size()) + mTickVectorLabels.resize(mTickVector.size()); + } +} + +/*! \internal + + If \ref setAutoTicks is set to true, this function is called by \ref setupTickVectors to + generate reasonable tick positions (and subtick count). The algorithm tries to create + approximately mAutoTickCount ticks (set via \ref setAutoTickCount). + + If the scale is logarithmic, \ref setAutoTickCount is ignored, and one tick is generated at every + power of the current logarithm base, set via \ref setScaleLogBase. +*/ +void QCPAxis::generateAutoTicks() +{ + if (mScaleType == stLinear) + { + if (mAutoTickStep) + { + // Generate tick positions according to linear scaling: + mTickStep = mRange.size()/(double)(mAutoTickCount+1e-10); // mAutoTickCount ticks on average, the small addition is to prevent jitter on exact integers + double magnitudeFactor = qPow(10.0, qFloor(qLn(mTickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc. + double tickStepMantissa = mTickStep/magnitudeFactor; + if (tickStepMantissa < 5) + { + // round digit after decimal point to 0.5 + mTickStep = (int)(tickStepMantissa*2)/2.0*magnitudeFactor; + } else + { + // round to first digit in multiples of 2 + mTickStep = (int)(tickStepMantissa/2.0)*2.0*magnitudeFactor; + } + } + if (mAutoSubTicks) + mSubTickCount = calculateAutoSubTickCount(mTickStep); + // Generate tick positions according to mTickStep: + qint64 firstStep = floor(mRange.lower/mTickStep); // do not use qFloor here, or we'll lose 64 bit precision + qint64 lastStep = ceil(mRange.upper/mTickStep); // do not use qCeil here, or we'll lose 64 bit precision + int tickcount = lastStep-firstStep+1; + if (tickcount < 0) tickcount = 0; + mTickVector.resize(tickcount); + for (int i=0; i 0 && mRange.upper > 0) // positive range + { + double lowerMag = basePow(qFloor(baseLog(mRange.lower))); + double currentMag = lowerMag; + mTickVector.clear(); + mTickVector.append(currentMag); + while (currentMag < mRange.upper && currentMag > 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case + { + currentMag *= mScaleLogBase; + mTickVector.append(currentMag); + } + } else if (mRange.lower < 0 && mRange.upper < 0) // negative range + { + double lowerMag = -basePow(qCeil(baseLog(-mRange.lower))); + double currentMag = lowerMag; + mTickVector.clear(); + mTickVector.append(currentMag); + while (currentMag < mRange.upper && currentMag < 0) // currentMag might be zero for ranges ~1e-300, just cancel in that case + { + currentMag /= mScaleLogBase; + mTickVector.append(currentMag); + } + } else // invalid range for logarithmic scale, because lower and upper have different sign + { + mTickVector.clear(); + qDebug() << Q_FUNC_INFO << "Invalid range for logarithmic plot: " << mRange.lower << "-" << mRange.upper; + } + } +} + +/*! \internal + + Called by generateAutoTicks when \ref setAutoSubTicks is set to true. Depending on the \a + tickStep between two major ticks on the axis, a different number of sub ticks is appropriate. For + Example taking 4 sub ticks for a \a tickStep of 1 makes more sense than taking 5 sub ticks, + because this corresponds to a sub tick step of 0.2, instead of the less intuitive 0.16667. Note + that a subtick count of 4 means dividing the major tick step into 5 sections. + + This is implemented by a hand made lookup for integer tick steps as well as fractional tick steps + with a fractional part of (approximately) 0.5. If a tick step is different (i.e. has no + fractional part close to 0.5), the currently set sub tick count (\ref setSubTickCount) is + returned. +*/ +int QCPAxis::calculateAutoSubTickCount(double tickStep) const +{ + int result = mSubTickCount; // default to current setting, if no proper value can be found + + // get mantissa of tickstep: + double magnitudeFactor = qPow(10.0, qFloor(qLn(tickStep)/qLn(10.0))); // get magnitude factor e.g. 0.01, 1, 10, 1000 etc. + double tickStepMantissa = tickStep/magnitudeFactor; + + // separate integer and fractional part of mantissa: + double epsilon = 0.01; + double intPartf; + int intPart; + double fracPart = modf(tickStepMantissa, &intPartf); + intPart = intPartf; + + // handle cases with (almost) integer mantissa: + if (fracPart < epsilon || 1.0-fracPart < epsilon) + { + if (1.0-fracPart < epsilon) + ++intPart; + switch (intPart) + { + case 1: result = 4; break; // 1.0 -> 0.2 substep + case 2: result = 3; break; // 2.0 -> 0.5 substep + case 3: result = 2; break; // 3.0 -> 1.0 substep + case 4: result = 3; break; // 4.0 -> 1.0 substep + case 5: result = 4; break; // 5.0 -> 1.0 substep + case 6: result = 2; break; // 6.0 -> 2.0 substep + case 7: result = 6; break; // 7.0 -> 1.0 substep + case 8: result = 3; break; // 8.0 -> 2.0 substep + case 9: result = 2; break; // 9.0 -> 3.0 substep + } + } else + { + // handle cases with significantly fractional mantissa: + if (qAbs(fracPart-0.5) < epsilon) // *.5 mantissa + { + switch (intPart) + { + case 1: result = 2; break; // 1.5 -> 0.5 substep + case 2: result = 4; break; // 2.5 -> 0.5 substep + case 3: result = 4; break; // 3.5 -> 0.7 substep + case 4: result = 2; break; // 4.5 -> 1.5 substep + case 5: result = 4; break; // 5.5 -> 1.1 substep (won't occur with autoTickStep from here on) + case 6: result = 4; break; // 6.5 -> 1.3 substep + case 7: result = 2; break; // 7.5 -> 2.5 substep + case 8: result = 4; break; // 8.5 -> 1.7 substep + case 9: result = 4; break; // 9.5 -> 1.9 substep + } + } + // if mantissa fraction isnt 0.0 or 0.5, don't bother finding good sub tick marks, leave default + } + + return result; +} + +/* inherits documentation from base class */ +void QCPAxis::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +{ + Q_UNUSED(event) + SelectablePart part = details.value(); + if (mSelectableParts.testFlag(part)) + { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(additive ? mSelectedParts^part : part); + if (selectionStateChanged) + *selectionStateChanged = mSelectedParts != selBefore; + } +} + +/* inherits documentation from base class */ +void QCPAxis::deselectEvent(bool *selectionStateChanged) +{ + SelectableParts selBefore = mSelectedParts; + setSelectedParts(mSelectedParts & ~mSelectableParts); + if (selectionStateChanged) + *selectionStateChanged = mSelectedParts != selBefore; +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing axis lines. + + This is the antialiasing state the painter passed to the \ref draw method is in by default. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased +*/ +void QCPAxis::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiased, QCP::aeAxes); +} + +/*! \internal + + Draws the axis with the specified \a painter, using the internal QCPAxisPainterPrivate instance. + +*/ +void QCPAxis::draw(QCPPainter *painter) +{ + const int lowTick = mLowestVisibleTick; + const int highTick = mHighestVisibleTick; + QVector subTickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter + QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter + QVector tickLabels; // the final vector passed to QCPAxisPainter + tickPositions.reserve(highTick-lowTick+1); + tickLabels.reserve(highTick-lowTick+1); + subTickPositions.reserve(mSubTickVector.size()); + + if (mTicks) + { + for (int i=lowTick; i<=highTick; ++i) + { + tickPositions.append(coordToPixel(mTickVector.at(i))); + if (mTickLabels) + tickLabels.append(mTickVectorLabels.at(i)); + } + + if (mSubTickCount > 0) + { + const int subTickCount = mSubTickVector.size(); + for (int i=0; itype = mAxisType; + mAxisPainter->basePen = getBasePen(); + mAxisPainter->labelFont = getLabelFont(); + mAxisPainter->labelColor = getLabelColor(); + mAxisPainter->label = mLabel; + mAxisPainter->substituteExponent = mAutoTickLabels && mNumberBeautifulPowers && mTickLabelType == ltNumber; + mAxisPainter->tickPen = getTickPen(); + mAxisPainter->subTickPen = getSubTickPen(); + mAxisPainter->tickLabelFont = getTickLabelFont(); + mAxisPainter->tickLabelColor = getTickLabelColor(); + mAxisPainter->axisRect = mAxisRect->rect(); + mAxisPainter->viewportRect = mParentPlot->viewport(); + mAxisPainter->abbreviateDecimalPowers = mScaleType == stLogarithmic; + mAxisPainter->reversedEndings = mRangeReversed; + mAxisPainter->tickPositions = tickPositions; + mAxisPainter->tickLabels = tickLabels; + mAxisPainter->subTickPositions = subTickPositions; + mAxisPainter->draw(painter); +} + +/*! \internal + + Returns via \a lowIndex and \a highIndex, which ticks in the current tick vector are visible in + the current range. The return values are indices of the tick vector, not the positions of the + ticks themselves. + + The actual use of this function is when an external tick vector is provided, since it might + exceed far beyond the currently displayed range, and would cause unnecessary calculations e.g. of + subticks. + + If all ticks are outside the axis range, an inverted range is returned, i.e. highIndex will be + smaller than lowIndex. There is one case, where this function returns indices that are not really + visible in the current axis range: When the tick spacing is larger than the axis range size and + one tick is below the axis range and the next tick is already above the axis range. Because in + such cases it is usually desirable to know the tick pair, to draw proper subticks. +*/ +void QCPAxis::visibleTickBounds(int &lowIndex, int &highIndex) const +{ + bool lowFound = false; + bool highFound = false; + lowIndex = 0; + highIndex = -1; + + for (int i=0; i < mTickVector.size(); ++i) + { + if (mTickVector.at(i) >= mRange.lower) + { + lowFound = true; + lowIndex = i; + break; + } + } + for (int i=mTickVector.size()-1; i >= 0; --i) + { + if (mTickVector.at(i) <= mRange.upper) + { + highFound = true; + highIndex = i; + break; + } + } + + if (!lowFound && highFound) + lowIndex = highIndex+1; + else if (lowFound && !highFound) + highIndex = lowIndex-1; +} + +/*! \internal + + A log function with the base mScaleLogBase, used mostly for coordinate transforms in logarithmic + scales with arbitrary log base. Uses the buffered mScaleLogBaseLogInv for faster calculation. + This is set to 1.0/qLn(mScaleLogBase) in \ref setScaleLogBase. + + \see basePow, setScaleLogBase, setScaleType +*/ +double QCPAxis::baseLog(double value) const +{ + return qLn(value)*mScaleLogBaseLogInv; +} + +/*! \internal + + A power function with the base mScaleLogBase, used mostly for coordinate transforms in + logarithmic scales with arbitrary log base. + + \see baseLog, setScaleLogBase, setScaleType +*/ +double QCPAxis::basePow(double value) const +{ + return qPow(mScaleLogBase, value); +} + +/*! \internal + + Returns the pen that is used to draw the axis base line. Depending on the selection state, this + is either mSelectedBasePen or mBasePen. +*/ +QPen QCPAxis::getBasePen() const +{ + return mSelectedParts.testFlag(spAxis) ? mSelectedBasePen : mBasePen; +} + +/*! \internal + + Returns the pen that is used to draw the (major) ticks. Depending on the selection state, this + is either mSelectedTickPen or mTickPen. +*/ +QPen QCPAxis::getTickPen() const +{ + return mSelectedParts.testFlag(spAxis) ? mSelectedTickPen : mTickPen; +} + +/*! \internal + + Returns the pen that is used to draw the subticks. Depending on the selection state, this + is either mSelectedSubTickPen or mSubTickPen. +*/ +QPen QCPAxis::getSubTickPen() const +{ + return mSelectedParts.testFlag(spAxis) ? mSelectedSubTickPen : mSubTickPen; +} + +/*! \internal + + Returns the font that is used to draw the tick labels. Depending on the selection state, this + is either mSelectedTickLabelFont or mTickLabelFont. +*/ +QFont QCPAxis::getTickLabelFont() const +{ + return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelFont : mTickLabelFont; +} + +/*! \internal + + Returns the font that is used to draw the axis label. Depending on the selection state, this + is either mSelectedLabelFont or mLabelFont. +*/ +QFont QCPAxis::getLabelFont() const +{ + return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelFont : mLabelFont; +} + +/*! \internal + + Returns the color that is used to draw the tick labels. Depending on the selection state, this + is either mSelectedTickLabelColor or mTickLabelColor. +*/ +QColor QCPAxis::getTickLabelColor() const +{ + return mSelectedParts.testFlag(spTickLabels) ? mSelectedTickLabelColor : mTickLabelColor; +} + +/*! \internal + + Returns the color that is used to draw the axis label. Depending on the selection state, this + is either mSelectedLabelColor or mLabelColor. +*/ +QColor QCPAxis::getLabelColor() const +{ + return mSelectedParts.testFlag(spAxisLabel) ? mSelectedLabelColor : mLabelColor; +} + +/*! \internal + + Returns the appropriate outward margin for this axis. It is needed if \ref + QCPAxisRect::setAutoMargins is set to true on the parent axis rect. An axis with axis type \ref + atLeft will return an appropriate left margin, \ref atBottom will return an appropriate bottom + margin and so forth. For the calculation, this function goes through similar steps as \ref draw, + so changing one function likely requires the modification of the other one as well. + + The margin consists of the outward tick length, tick label padding, tick label size, label + padding, label size, and padding. + + The margin is cached internally, so repeated calls while leaving the axis range, fonts, etc. + unchanged are very fast. +*/ +int QCPAxis::calculateMargin() +{ + if (!mVisible) // if not visible, directly return 0, don't cache 0 because we can't react to setVisible in QCPAxis + return 0; + + if (mCachedMarginValid) + return mCachedMargin; + + // run through similar steps as QCPAxis::draw, and caluclate margin needed to fit axis and its labels + int margin = 0; + + int lowTick, highTick; + visibleTickBounds(lowTick, highTick); + QVector tickPositions; // the final coordToPixel transformed vector passed to QCPAxisPainter + QVector tickLabels; // the final vector passed to QCPAxisPainter + tickPositions.reserve(highTick-lowTick+1); + tickLabels.reserve(highTick-lowTick+1); + if (mTicks) + { + for (int i=lowTick; i<=highTick; ++i) + { + tickPositions.append(coordToPixel(mTickVector.at(i))); + if (mTickLabels) + tickLabels.append(mTickVectorLabels.at(i)); + } + } + // transfer all properties of this axis to QCPAxisPainterPrivate which it needs to calculate the size. + // Note that some axis painter properties are already set by direct feed-through with QCPAxis setters + mAxisPainter->type = mAxisType; + mAxisPainter->labelFont = getLabelFont(); + mAxisPainter->label = mLabel; + mAxisPainter->tickLabelFont = mTickLabelFont; + mAxisPainter->axisRect = mAxisRect->rect(); + mAxisPainter->viewportRect = mParentPlot->viewport(); + mAxisPainter->tickPositions = tickPositions; + mAxisPainter->tickLabels = tickLabels; + margin += mAxisPainter->size(); + margin += mPadding; + + mCachedMargin = margin; + mCachedMarginValid = true; + return margin; +} + +/* inherits documentation from base class */ +QCP::Interaction QCPAxis::selectionCategory() const +{ + return QCP::iSelectAxes; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPAxisPainterPrivate +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPAxisPainterPrivate + + \internal + \brief (Private) + + This is a private class and not part of the public QCustomPlot interface. + + It is used by QCPAxis to do the low-level drawing of axis backbone, tick marks, tick labels and + axis label. It also buffers the labels to reduce replot times. The parameters are configured by + directly accessing the public member variables. +*/ + +/*! + Constructs a QCPAxisPainterPrivate instance. Make sure to not create a new instance on every + redraw, to utilize the caching mechanisms. +*/ +QCPAxisPainterPrivate::QCPAxisPainterPrivate(QCustomPlot *parentPlot) : + type(QCPAxis::atLeft), + basePen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + lowerEnding(QCPLineEnding::esNone), + upperEnding(QCPLineEnding::esNone), + labelPadding(0), + tickLabelPadding(0), + tickLabelRotation(0), + tickLabelSide(QCPAxis::lsOutside), + substituteExponent(true), + numberMultiplyCross(false), + tickLengthIn(5), + tickLengthOut(0), + subTickLengthIn(2), + subTickLengthOut(0), + tickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + subTickPen(QPen(Qt::black, 0, Qt::SolidLine, Qt::SquareCap)), + offset(0), + abbreviateDecimalPowers(false), + reversedEndings(false), + mParentPlot(parentPlot), + mLabelCache(16) // cache at most 16 (tick) labels +{ +} + +QCPAxisPainterPrivate::~QCPAxisPainterPrivate() +{ +} + +/*! \internal + + Draws the axis with the specified \a painter. + + The selection boxes (mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox) are set + here, too. +*/ +void QCPAxisPainterPrivate::draw(QCPPainter *painter) +{ + QByteArray newHash = generateLabelParameterHash(); + if (newHash != mLabelParameterHash) + { + mLabelCache.clear(); + mLabelParameterHash = newHash; + } + + QPoint origin; + switch (type) + { + case QCPAxis::atLeft: origin = axisRect.bottomLeft() +QPoint(-offset, 0); break; + case QCPAxis::atRight: origin = axisRect.bottomRight()+QPoint(+offset, 0); break; + case QCPAxis::atTop: origin = axisRect.topLeft() +QPoint(0, -offset); break; + case QCPAxis::atBottom: origin = axisRect.bottomLeft() +QPoint(0, +offset); break; + } + + double xCor = 0, yCor = 0; // paint system correction, for pixel exact matches (affects baselines and ticks of top/right axes) + switch (type) + { + case QCPAxis::atTop: yCor = -1; break; + case QCPAxis::atRight: xCor = 1; break; + default: break; + } + + int margin = 0; + // draw baseline: + QLineF baseLine; + painter->setPen(basePen); + if (QCPAxis::orientation(type) == Qt::Horizontal) + baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(axisRect.width()+xCor, yCor)); + else + baseLine.setPoints(origin+QPointF(xCor, yCor), origin+QPointF(xCor, -axisRect.height()+yCor)); + if (reversedEndings) + baseLine = QLineF(baseLine.p2(), baseLine.p1()); // won't make a difference for line itself, but for line endings later + painter->drawLine(baseLine); + + // draw ticks: + if (!tickPositions.isEmpty()) + { + painter->setPen(tickPen); + int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; // direction of ticks ("inward" is right for left axis and left for right axis) + if (QCPAxis::orientation(type) == Qt::Horizontal) + { + for (int i=0; idrawLine(QLineF(tickPositions.at(i)+xCor, origin.y()-tickLengthOut*tickDir+yCor, tickPositions.at(i)+xCor, origin.y()+tickLengthIn*tickDir+yCor)); + } else + { + for (int i=0; idrawLine(QLineF(origin.x()-tickLengthOut*tickDir+xCor, tickPositions.at(i)+yCor, origin.x()+tickLengthIn*tickDir+xCor, tickPositions.at(i)+yCor)); + } + } + + // draw subticks: + if (!subTickPositions.isEmpty()) + { + painter->setPen(subTickPen); + // direction of ticks ("inward" is right for left axis and left for right axis) + int tickDir = (type == QCPAxis::atBottom || type == QCPAxis::atRight) ? -1 : 1; + if (QCPAxis::orientation(type) == Qt::Horizontal) + { + for (int i=0; idrawLine(QLineF(subTickPositions.at(i)+xCor, origin.y()-subTickLengthOut*tickDir+yCor, subTickPositions.at(i)+xCor, origin.y()+subTickLengthIn*tickDir+yCor)); + } else + { + for (int i=0; idrawLine(QLineF(origin.x()-subTickLengthOut*tickDir+xCor, subTickPositions.at(i)+yCor, origin.x()+subTickLengthIn*tickDir+xCor, subTickPositions.at(i)+yCor)); + } + } + margin += qMax(0, qMax(tickLengthOut, subTickLengthOut)); + + // draw axis base endings: + bool antialiasingBackup = painter->antialiasing(); + painter->setAntialiasing(true); // always want endings to be antialiased, even if base and ticks themselves aren't + painter->setBrush(QBrush(basePen.color())); + QVector2D baseLineVector(baseLine.dx(), baseLine.dy()); + if (lowerEnding.style() != QCPLineEnding::esNone) + lowerEnding.draw(painter, QVector2D(baseLine.p1())-baseLineVector.normalized()*lowerEnding.realLength()*(lowerEnding.inverted()?-1:1), -baseLineVector); + if (upperEnding.style() != QCPLineEnding::esNone) + upperEnding.draw(painter, QVector2D(baseLine.p2())+baseLineVector.normalized()*upperEnding.realLength()*(upperEnding.inverted()?-1:1), baseLineVector); + painter->setAntialiasing(antialiasingBackup); + + // tick labels: + QRect oldClipRect; + if (tickLabelSide == QCPAxis::lsInside) // if using inside labels, clip them to the axis rect + { + oldClipRect = painter->clipRegion().boundingRect(); + painter->setClipRect(axisRect); + } + QSize tickLabelsSize(0, 0); // size of largest tick label, for offset calculation of axis label + if (!tickLabels.isEmpty()) + { + if (tickLabelSide == QCPAxis::lsOutside) + margin += tickLabelPadding; + painter->setFont(tickLabelFont); + painter->setPen(QPen(tickLabelColor)); + const int maxLabelIndex = qMin(tickPositions.size(), tickLabels.size()); + int distanceToAxis = margin; + if (tickLabelSide == QCPAxis::lsInside) + distanceToAxis = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); + for (int i=0; isetClipRect(oldClipRect); + + // axis label: + QRect labelBounds; + if (!label.isEmpty()) + { + margin += labelPadding; + painter->setFont(labelFont); + painter->setPen(QPen(labelColor)); + labelBounds = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip, label); + if (type == QCPAxis::atLeft) + { + QTransform oldTransform = painter->transform(); + painter->translate((origin.x()-margin-labelBounds.height()), origin.y()); + painter->rotate(-90); + painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + painter->setTransform(oldTransform); + } + else if (type == QCPAxis::atRight) + { + QTransform oldTransform = painter->transform(); + painter->translate((origin.x()+margin+labelBounds.height()), origin.y()-axisRect.height()); + painter->rotate(90); + painter->drawText(0, 0, axisRect.height(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + painter->setTransform(oldTransform); + } + else if (type == QCPAxis::atTop) + painter->drawText(origin.x(), origin.y()-margin-labelBounds.height(), axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + else if (type == QCPAxis::atBottom) + painter->drawText(origin.x(), origin.y()+margin, axisRect.width(), labelBounds.height(), Qt::TextDontClip | Qt::AlignCenter, label); + } + + // set selection boxes: + int selectionTolerance = 0; + if (mParentPlot) + selectionTolerance = mParentPlot->selectionTolerance(); + else + qDebug() << Q_FUNC_INFO << "mParentPlot is null"; + int selAxisOutSize = qMax(qMax(tickLengthOut, subTickLengthOut), selectionTolerance); + int selAxisInSize = selectionTolerance; + int selTickLabelSize; + int selTickLabelOffset; + if (tickLabelSide == QCPAxis::lsOutside) + { + selTickLabelSize = (QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); + selTickLabelOffset = qMax(tickLengthOut, subTickLengthOut)+tickLabelPadding; + } else + { + selTickLabelSize = -(QCPAxis::orientation(type) == Qt::Horizontal ? tickLabelsSize.height() : tickLabelsSize.width()); + selTickLabelOffset = -(qMax(tickLengthIn, subTickLengthIn)+tickLabelPadding); + } + int selLabelSize = labelBounds.height(); + int selLabelOffset = qMax(tickLengthOut, subTickLengthOut)+(!tickLabels.isEmpty() && tickLabelSide == QCPAxis::lsOutside ? tickLabelPadding+selTickLabelSize : 0)+labelPadding; + if (type == QCPAxis::atLeft) + { + mAxisSelectionBox.setCoords(origin.x()-selAxisOutSize, axisRect.top(), origin.x()+selAxisInSize, axisRect.bottom()); + mTickLabelsSelectionBox.setCoords(origin.x()-selTickLabelOffset-selTickLabelSize, axisRect.top(), origin.x()-selTickLabelOffset, axisRect.bottom()); + mLabelSelectionBox.setCoords(origin.x()-selLabelOffset-selLabelSize, axisRect.top(), origin.x()-selLabelOffset, axisRect.bottom()); + } else if (type == QCPAxis::atRight) + { + mAxisSelectionBox.setCoords(origin.x()-selAxisInSize, axisRect.top(), origin.x()+selAxisOutSize, axisRect.bottom()); + mTickLabelsSelectionBox.setCoords(origin.x()+selTickLabelOffset+selTickLabelSize, axisRect.top(), origin.x()+selTickLabelOffset, axisRect.bottom()); + mLabelSelectionBox.setCoords(origin.x()+selLabelOffset+selLabelSize, axisRect.top(), origin.x()+selLabelOffset, axisRect.bottom()); + } else if (type == QCPAxis::atTop) + { + mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisOutSize, axisRect.right(), origin.y()+selAxisInSize); + mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()-selTickLabelOffset-selTickLabelSize, axisRect.right(), origin.y()-selTickLabelOffset); + mLabelSelectionBox.setCoords(axisRect.left(), origin.y()-selLabelOffset-selLabelSize, axisRect.right(), origin.y()-selLabelOffset); + } else if (type == QCPAxis::atBottom) + { + mAxisSelectionBox.setCoords(axisRect.left(), origin.y()-selAxisInSize, axisRect.right(), origin.y()+selAxisOutSize); + mTickLabelsSelectionBox.setCoords(axisRect.left(), origin.y()+selTickLabelOffset+selTickLabelSize, axisRect.right(), origin.y()+selTickLabelOffset); + mLabelSelectionBox.setCoords(axisRect.left(), origin.y()+selLabelOffset+selLabelSize, axisRect.right(), origin.y()+selLabelOffset); + } + mAxisSelectionBox = mAxisSelectionBox.normalized(); + mTickLabelsSelectionBox = mTickLabelsSelectionBox.normalized(); + mLabelSelectionBox = mLabelSelectionBox.normalized(); + // draw hitboxes for debug purposes: + //painter->setBrush(Qt::NoBrush); + //painter->drawRects(QVector() << mAxisSelectionBox << mTickLabelsSelectionBox << mLabelSelectionBox); +} + +/*! \internal + + Returns the size ("margin" in QCPAxisRect context, so measured perpendicular to the axis backbone + direction) needed to fit the axis. +*/ +int QCPAxisPainterPrivate::size() const +{ + int result = 0; + + // get length of tick marks pointing outwards: + if (!tickPositions.isEmpty()) + result += qMax(0, qMax(tickLengthOut, subTickLengthOut)); + + // calculate size of tick labels: + if (tickLabelSide == QCPAxis::lsOutside) + { + QSize tickLabelsSize(0, 0); + if (!tickLabels.isEmpty()) + { + for (int i=0; iplottingHints().testFlag(QCP::phCacheLabels) && !painter->modes().testFlag(QCPPainter::pmNoCaching)) // label caching enabled + { + if (!mLabelCache.contains(text)) // no cached label exists, create it + { + CachedLabel *newCachedLabel = new CachedLabel; + TickLabelData labelData = getTickLabelData(painter->font(), text); + newCachedLabel->offset = getTickLabelDrawOffset(labelData)+labelData.rotatedTotalBounds.topLeft(); + newCachedLabel->pixmap = QPixmap(labelData.rotatedTotalBounds.size()); + newCachedLabel->pixmap.fill(Qt::transparent); + QCPPainter cachePainter(&newCachedLabel->pixmap); + cachePainter.setPen(painter->pen()); + drawTickLabel(&cachePainter, -labelData.rotatedTotalBounds.topLeft().x(), -labelData.rotatedTotalBounds.topLeft().y(), labelData); + mLabelCache.insert(text, newCachedLabel, 1); + } + // draw cached label: + const CachedLabel *cachedLabel = mLabelCache.object(text); + // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): + if (tickLabelSide == QCPAxis::lsOutside) + { + if (QCPAxis::orientation(type) == Qt::Horizontal) + { + if (labelAnchor.x()+cachedLabel->offset.x()+cachedLabel->pixmap.width() > viewportRect.right() || + labelAnchor.x()+cachedLabel->offset.x() < viewportRect.left()) + return; + } else + { + if (labelAnchor.y()+cachedLabel->offset.y()+cachedLabel->pixmap.height() >viewportRect.bottom() || + labelAnchor.y()+cachedLabel->offset.y() < viewportRect.top()) + return; + } + } + painter->drawPixmap(labelAnchor+cachedLabel->offset, cachedLabel->pixmap); + finalSize = cachedLabel->pixmap.size(); + } else // label caching disabled, draw text directly on surface: + { + TickLabelData labelData = getTickLabelData(painter->font(), text); + QPointF finalPosition = labelAnchor + getTickLabelDrawOffset(labelData); + // if label would be partly clipped by widget border on sides, don't draw it (only for outside tick labels): + if (tickLabelSide == QCPAxis::lsOutside) + { + if (QCPAxis::orientation(type) == Qt::Horizontal) + { + if (finalPosition.x()+(labelData.rotatedTotalBounds.width()+labelData.rotatedTotalBounds.left()) > viewportRect.right() || + finalPosition.x()+labelData.rotatedTotalBounds.left() < viewportRect.left()) + return; + } else + { + if (finalPosition.y()+(labelData.rotatedTotalBounds.height()+labelData.rotatedTotalBounds.top()) > viewportRect.bottom() || + finalPosition.y()+labelData.rotatedTotalBounds.top() < viewportRect.top()) + return; + } + } + drawTickLabel(painter, finalPosition.x(), finalPosition.y(), labelData); + finalSize = labelData.rotatedTotalBounds.size(); + } + + // expand passed tickLabelsSize if current tick label is larger: + if (finalSize.width() > tickLabelsSize->width()) + tickLabelsSize->setWidth(finalSize.width()); + if (finalSize.height() > tickLabelsSize->height()) + tickLabelsSize->setHeight(finalSize.height()); +} + +/*! \internal + + This is a \ref placeTickLabel helper function. + + Draws the tick label specified in \a labelData with \a painter at the pixel positions \a x and \a + y. This function is used by \ref placeTickLabel to create new tick labels for the cache, or to + directly draw the labels on the QCustomPlot surface when label caching is disabled, i.e. when + QCP::phCacheLabels plotting hint is not set. +*/ +void QCPAxisPainterPrivate::drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const +{ + // backup painter settings that we're about to change: + QTransform oldTransform = painter->transform(); + QFont oldFont = painter->font(); + + // transform painter to position/rotation: + painter->translate(x, y); + if (!qFuzzyIsNull(tickLabelRotation)) + painter->rotate(tickLabelRotation); + + // draw text: + if (!labelData.expPart.isEmpty()) // indicator that beautiful powers must be used + { + painter->setFont(labelData.baseFont); + painter->drawText(0, 0, 0, 0, Qt::TextDontClip, labelData.basePart); + painter->setFont(labelData.expFont); + painter->drawText(labelData.baseBounds.width()+1, 0, labelData.expBounds.width(), labelData.expBounds.height(), Qt::TextDontClip, labelData.expPart); + } else + { + painter->setFont(labelData.baseFont); + painter->drawText(0, 0, labelData.totalBounds.width(), labelData.totalBounds.height(), Qt::TextDontClip | Qt::AlignHCenter, labelData.basePart); + } + + // reset painter settings to what it was before: + painter->setTransform(oldTransform); + painter->setFont(oldFont); +} + +/*! \internal + + This is a \ref placeTickLabel helper function. + + Transforms the passed \a text and \a font to a tickLabelData structure that can then be further + processed by \ref getTickLabelDrawOffset and \ref drawTickLabel. It splits the text into base and + exponent if necessary (member substituteExponent) and calculates appropriate bounding boxes. +*/ +QCPAxisPainterPrivate::TickLabelData QCPAxisPainterPrivate::getTickLabelData(const QFont &font, const QString &text) const +{ + TickLabelData result; + + // determine whether beautiful decimal powers should be used + bool useBeautifulPowers = false; + int ePos = -1; + if (substituteExponent) + { + ePos = text.indexOf('e'); + if (ePos > -1) + useBeautifulPowers = true; + } + + // calculate text bounding rects and do string preparation for beautiful decimal powers: + result.baseFont = font; + if (result.baseFont.pointSizeF() > 0) // On some rare systems, this sometimes is initialized with -1 (Qt bug?), so we check here before possibly setting a negative value in the next line + result.baseFont.setPointSizeF(result.baseFont.pointSizeF()+0.05); // QFontMetrics.boundingRect has a bug for exact point sizes that make the results oscillate due to internal rounding + if (useBeautifulPowers) + { + // split text into parts of number/symbol that will be drawn normally and part that will be drawn as exponent: + result.basePart = text.left(ePos); + // in log scaling, we want to turn "1*10^n" into "10^n", else add multiplication sign and decimal base: + if (abbreviateDecimalPowers && result.basePart == "1") + result.basePart = "10"; + else + result.basePart += (numberMultiplyCross ? QString(QChar(215)) : QString(QChar(183))) + "10"; + result.expPart = text.mid(ePos+1); + // clip "+" and leading zeros off expPart: + while (result.expPart.length() > 2 && result.expPart.at(1) == '0') // length > 2 so we leave one zero when numberFormatChar is 'e' + result.expPart.remove(1, 1); + if (!result.expPart.isEmpty() && result.expPart.at(0) == '+') + result.expPart.remove(0, 1); + // prepare smaller font for exponent: + result.expFont = font; + result.expFont.setPointSize(result.expFont.pointSize()*0.75); + // calculate bounding rects of base part, exponent part and total one: + result.baseBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.basePart); + result.expBounds = QFontMetrics(result.expFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip, result.expPart); + result.totalBounds = result.baseBounds.adjusted(0, 0, result.expBounds.width()+2, 0); // +2 consists of the 1 pixel spacing between base and exponent (see drawTickLabel) and an extra pixel to include AA + } else // useBeautifulPowers == false + { + result.basePart = text; + result.totalBounds = QFontMetrics(result.baseFont).boundingRect(0, 0, 0, 0, Qt::TextDontClip | Qt::AlignHCenter, result.basePart); + } + result.totalBounds.moveTopLeft(QPoint(0, 0)); // want bounding box aligned top left at origin, independent of how it was created, to make further processing simpler + + // calculate possibly different bounding rect after rotation: + result.rotatedTotalBounds = result.totalBounds; + if (!qFuzzyIsNull(tickLabelRotation)) + { + QTransform transform; + transform.rotate(tickLabelRotation); + result.rotatedTotalBounds = transform.mapRect(result.rotatedTotalBounds); + } + + return result; +} + +/*! \internal + + This is a \ref placeTickLabel helper function. + + Calculates the offset at which the top left corner of the specified tick label shall be drawn. + The offset is relative to a point right next to the tick the label belongs to. + + This function is thus responsible for e.g. centering tick labels under ticks and positioning them + appropriately when they are rotated. +*/ +QPointF QCPAxisPainterPrivate::getTickLabelDrawOffset(const TickLabelData &labelData) const +{ + /* + calculate label offset from base point at tick (non-trivial, for best visual appearance): short + explanation for bottom axis: The anchor, i.e. the point in the label that is placed + horizontally under the corresponding tick is always on the label side that is closer to the + axis (e.g. the left side of the text when we're rotating clockwise). On that side, the height + is halved and the resulting point is defined the anchor. This way, a 90 degree rotated text + will be centered under the tick (i.e. displaced horizontally by half its height). At the same + time, a 45 degree rotated text will "point toward" its tick, as is typical for rotated tick + labels. + */ + bool doRotation = !qFuzzyIsNull(tickLabelRotation); + bool flip = qFuzzyCompare(qAbs(tickLabelRotation), 90.0); // perfect +/-90 degree flip. Indicates vertical label centering on vertical axes. + double radians = tickLabelRotation/180.0*M_PI; + int x=0, y=0; + if ((type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsInside)) // Anchor at right side of tick label + { + if (doRotation) + { + if (tickLabelRotation > 0) + { + x = -qCos(radians)*labelData.totalBounds.width(); + y = flip ? -labelData.totalBounds.width()/2.0 : -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height()/2.0; + } else + { + x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height(); + y = flip ? +labelData.totalBounds.width()/2.0 : +qSin(-radians)*labelData.totalBounds.width()-qCos(-radians)*labelData.totalBounds.height()/2.0; + } + } else + { + x = -labelData.totalBounds.width(); + y = -labelData.totalBounds.height()/2.0; + } + } else if ((type == QCPAxis::atRight && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atLeft && tickLabelSide == QCPAxis::lsInside)) // Anchor at left side of tick label + { + if (doRotation) + { + if (tickLabelRotation > 0) + { + x = +qSin(radians)*labelData.totalBounds.height(); + y = flip ? -labelData.totalBounds.width()/2.0 : -qCos(radians)*labelData.totalBounds.height()/2.0; + } else + { + x = 0; + y = flip ? +labelData.totalBounds.width()/2.0 : -qCos(-radians)*labelData.totalBounds.height()/2.0; + } + } else + { + x = 0; + y = -labelData.totalBounds.height()/2.0; + } + } else if ((type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsInside)) // Anchor at bottom side of tick label + { + if (doRotation) + { + if (tickLabelRotation > 0) + { + x = -qCos(radians)*labelData.totalBounds.width()+qSin(radians)*labelData.totalBounds.height()/2.0; + y = -qSin(radians)*labelData.totalBounds.width()-qCos(radians)*labelData.totalBounds.height(); + } else + { + x = -qSin(-radians)*labelData.totalBounds.height()/2.0; + y = -qCos(-radians)*labelData.totalBounds.height(); + } + } else + { + x = -labelData.totalBounds.width()/2.0; + y = -labelData.totalBounds.height(); + } + } else if ((type == QCPAxis::atBottom && tickLabelSide == QCPAxis::lsOutside) || (type == QCPAxis::atTop && tickLabelSide == QCPAxis::lsInside)) // Anchor at top side of tick label + { + if (doRotation) + { + if (tickLabelRotation > 0) + { + x = +qSin(radians)*labelData.totalBounds.height()/2.0; + y = 0; + } else + { + x = -qCos(-radians)*labelData.totalBounds.width()-qSin(-radians)*labelData.totalBounds.height()/2.0; + y = +qSin(-radians)*labelData.totalBounds.width(); + } + } else + { + x = -labelData.totalBounds.width()/2.0; + y = 0; + } + } + + return QPointF(x, y); +} + +/*! \internal + + Simulates the steps done by \ref placeTickLabel by calculating bounding boxes of the text label + to be drawn, depending on number format etc. Since only the largest tick label is wanted for the + margin calculation, the passed \a tickLabelsSize is only expanded, if it's currently set to a + smaller width/height. +*/ +void QCPAxisPainterPrivate::getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const +{ + // note: this function must return the same tick label sizes as the placeTickLabel function. + QSize finalSize; + if (mParentPlot->plottingHints().testFlag(QCP::phCacheLabels) && mLabelCache.contains(text)) // label caching enabled and have cached label + { + const CachedLabel *cachedLabel = mLabelCache.object(text); + finalSize = cachedLabel->pixmap.size(); + } else // label caching disabled or no label with this text cached: + { + TickLabelData labelData = getTickLabelData(font, text); + finalSize = labelData.rotatedTotalBounds.size(); + } + + // expand passed tickLabelsSize if current tick label is larger: + if (finalSize.width() > tickLabelsSize->width()) + tickLabelsSize->setWidth(finalSize.width()); + if (finalSize.height() > tickLabelsSize->height()) + tickLabelsSize->setHeight(finalSize.height()); +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPAbstractPlottable +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPAbstractPlottable + \brief The abstract base class for all data representing objects in a plot. + + It defines a very basic interface like name, pen, brush, visibility etc. Since this class is + abstract, it can't be instantiated. Use one of the subclasses or create a subclass yourself to + create new ways of displaying data (see "Creating own plottables" below). + + All further specifics are in the subclasses, for example: + \li A normal graph with possibly a line, scatter points and error bars: \ref QCPGraph + (typically created with \ref QCustomPlot::addGraph) + \li A parametric curve: \ref QCPCurve + \li A bar chart: \ref QCPBars + \li A statistical box plot: \ref QCPStatisticalBox + \li A color encoded two-dimensional map: \ref QCPColorMap + \li An OHLC/Candlestick chart: \ref QCPFinancial + + \section plottables-subclassing Creating own plottables + + To create an own plottable, you implement a subclass of QCPAbstractPlottable. These are the pure + virtual functions, you must implement: + \li \ref clearData + \li \ref selectTest + \li \ref draw + \li \ref drawLegendIcon + \li \ref getKeyRange + \li \ref getValueRange + + See the documentation of those functions for what they need to do. + + For drawing your plot, you can use the \ref coordsToPixels functions to translate a point in plot + coordinates to pixel coordinates. This function is quite convenient, because it takes the + orientation of the key and value axes into account for you (x and y are swapped when the key axis + is vertical and the value axis horizontal). If you are worried about performance (i.e. you need + to translate many points in a loop like QCPGraph), you can directly use \ref + QCPAxis::coordToPixel. However, you must then take care about the orientation of the axis + yourself. + + Here are some important members you inherit from QCPAbstractPlottable: + + + + + + + + + + + + + + + + + + + + + + + + + + +
QCustomPlot *\b mParentPlotA pointer to the parent QCustomPlot instance. The parent plot is inferred from the axes that are passed in the constructor.
QString \b mNameThe name of the plottable.
QPen \b mPenThe generic pen of the plottable. You should use this pen for the most prominent data representing lines in the plottable (e.g QCPGraph uses this pen for its graph lines and scatters)
QPen \b mSelectedPenThe generic pen that should be used when the plottable is selected (hint: \ref mainPen gives you the right pen, depending on selection state).
QBrush \b mBrushThe generic brush of the plottable. You should use this brush for the most prominent fillable structures in the plottable (e.g. QCPGraph uses this brush to control filling under the graph)
QBrush \b mSelectedBrushThe generic brush that should be used when the plottable is selected (hint: \ref mainBrush gives you the right brush, depending on selection state).
QPointer\b mKeyAxis, \b mValueAxisThe key and value axes this plottable is attached to. Call their QCPAxis::coordToPixel functions to translate coordinates to pixels in either the key or value dimension. + Make sure to check whether the pointer is null before using it. If one of the axes is null, don't draw the plottable.
bool \b mSelectedindicates whether the plottable is selected or not.
+*/ + +/* start of documentation of pure virtual functions */ + +/*! \fn void QCPAbstractPlottable::clearData() = 0 + Clears all data in the plottable. +*/ + +/*! \fn void QCPAbstractPlottable::drawLegendIcon(QCPPainter *painter, const QRect &rect) const = 0 + \internal + + called by QCPLegend::draw (via QCPPlottableLegendItem::draw) to create a graphical representation + of this plottable inside \a rect, next to the plottable name. +*/ + +/*! \fn QCPRange QCPAbstractPlottable::getKeyRange(bool &foundRange, SignDomain inSignDomain) const = 0 + \internal + + called by rescaleAxes functions to get the full data key bounds. For logarithmic plots, one can + set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the + returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain + to \ref sdNegative and all positive points will be ignored for range calculation. For no + restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output + parameter that indicates whether a range could be found or not. If this is false, you shouldn't + use the returned range (e.g. no points in data). + + Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by + this function may have size zero, which wouldn't count as a valid range. + + \see rescaleAxes, getValueRange +*/ + +/*! \fn QCPRange QCPAbstractPlottable::getValueRange(bool &foundRange, SignDomain inSignDomain) const = 0 + \internal + + called by rescaleAxes functions to get the full data value bounds. For logarithmic plots, one can + set \a inSignDomain to either \ref sdNegative or \ref sdPositive in order to restrict the + returned range to that sign domain. E.g. when only negative range is wanted, set \a inSignDomain + to \ref sdNegative and all positive points will be ignored for range calculation. For no + restriction, just set \a inSignDomain to \ref sdBoth (default). \a foundRange is an output + parameter that indicates whether a range could be found or not. If this is false, you shouldn't + use the returned range (e.g. no points in data). + + Note that \a foundRange is not the same as \ref QCPRange::validRange, since the range returned by + this function may have size zero, which wouldn't count as a valid range. + + \see rescaleAxes, getKeyRange +*/ + +/* end of documentation of pure virtual functions */ +/* start of documentation of signals */ + +/*! \fn void QCPAbstractPlottable::selectionChanged(bool selected) + + This signal is emitted when the selection state of this plottable has changed, either by user + interaction or by a direct call to \ref setSelected. +*/ + +/*! \fn void QCPAbstractPlottable::selectableChanged(bool selectable); + + This signal is emitted when the selectability of this plottable has changed. + + \see setSelectable +*/ + +/* end of documentation of signals */ + +/*! + Constructs an abstract plottable which uses \a keyAxis as its key axis ("x") and \a valueAxis as + its value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance + and have perpendicular orientations. If either of these restrictions is violated, a corresponding + message is printed to the debug output (qDebug), the construction is not aborted, though. + + Since QCPAbstractPlottable is an abstract class that defines the basic interface to plottables, + it can't be directly instantiated. + + You probably want one of the subclasses like \ref QCPGraph or \ref QCPCurve instead. +*/ +QCPAbstractPlottable::QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis) : + QCPLayerable(keyAxis->parentPlot(), "", keyAxis->axisRect()), + mName(""), + mAntialiasedFill(true), + mAntialiasedScatters(true), + mAntialiasedErrorBars(false), + mPen(Qt::black), + mSelectedPen(Qt::black), + mBrush(Qt::NoBrush), + mSelectedBrush(Qt::NoBrush), + mKeyAxis(keyAxis), + mValueAxis(valueAxis), + mSelectable(true), + mSelected(false) +{ + if (keyAxis->parentPlot() != valueAxis->parentPlot()) + qDebug() << Q_FUNC_INFO << "Parent plot of keyAxis is not the same as that of valueAxis."; + if (keyAxis->orientation() == valueAxis->orientation()) + qDebug() << Q_FUNC_INFO << "keyAxis and valueAxis must be orthogonal to each other."; +} + +/*! + The name is the textual representation of this plottable as it is displayed in the legend + (\ref QCPLegend). It may contain any UTF-8 characters, including newlines. +*/ +void QCPAbstractPlottable::setName(const QString &name) +{ + mName = name; +} + +/*! + Sets whether fills of this plottable is drawn antialiased or not. + + Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. +*/ +void QCPAbstractPlottable::setAntialiasedFill(bool enabled) +{ + mAntialiasedFill = enabled; +} + +/*! + Sets whether the scatter symbols of this plottable are drawn antialiased or not. + + Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. +*/ +void QCPAbstractPlottable::setAntialiasedScatters(bool enabled) +{ + mAntialiasedScatters = enabled; +} + +/*! + Sets whether the error bars of this plottable are drawn antialiased or not. + + Note that this setting may be overridden by \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. +*/ +void QCPAbstractPlottable::setAntialiasedErrorBars(bool enabled) +{ + mAntialiasedErrorBars = enabled; +} + + +/*! + The pen is used to draw basic lines that make up the plottable representation in the + plot. + + For example, the \ref QCPGraph subclass draws its graph lines and scatter points + with this pen. + + \see setBrush +*/ +void QCPAbstractPlottable::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + When the plottable is selected, this pen is used to draw basic lines instead of the normal + pen set via \ref setPen. + + \see setSelected, setSelectable, setSelectedBrush, selectTest +*/ +void QCPAbstractPlottable::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + The brush is used to draw basic fills of the plottable representation in the + plot. The Fill can be a color, gradient or texture, see the usage of QBrush. + + For example, the \ref QCPGraph subclass draws the fill under the graph with this brush, when + it's not set to Qt::NoBrush. + + \see setPen +*/ +void QCPAbstractPlottable::setBrush(const QBrush &brush) +{ + mBrush = brush; +} + +/*! + When the plottable is selected, this brush is used to draw fills instead of the normal + brush set via \ref setBrush. + + \see setSelected, setSelectable, setSelectedPen, selectTest +*/ +void QCPAbstractPlottable::setSelectedBrush(const QBrush &brush) +{ + mSelectedBrush = brush; +} + +/*! + The key axis of a plottable can be set to any axis of a QCustomPlot, as long as it is orthogonal + to the plottable's value axis. This function performs no checks to make sure this is the case. + The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and the + y-axis (QCustomPlot::yAxis) as value axis. + + Normally, the key and value axes are set in the constructor of the plottable (or \ref + QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). + + \see setValueAxis +*/ +void QCPAbstractPlottable::setKeyAxis(QCPAxis *axis) +{ + mKeyAxis = axis; +} + +/*! + The value axis of a plottable can be set to any axis of a QCustomPlot, as long as it is + orthogonal to the plottable's key axis. This function performs no checks to make sure this is the + case. The typical mathematical choice is to use the x-axis (QCustomPlot::xAxis) as key axis and + the y-axis (QCustomPlot::yAxis) as value axis. + + Normally, the key and value axes are set in the constructor of the plottable (or \ref + QCustomPlot::addGraph when working with QCPGraphs through the dedicated graph interface). + + \see setKeyAxis +*/ +void QCPAbstractPlottable::setValueAxis(QCPAxis *axis) +{ + mValueAxis = axis; +} + +/*! + Sets whether the user can (de-)select this plottable by clicking on the QCustomPlot surface. + (When \ref QCustomPlot::setInteractions contains iSelectPlottables.) + + However, even when \a selectable was set to false, it is possible to set the selection manually, + by calling \ref setSelected directly. + + \see setSelected +*/ +void QCPAbstractPlottable::setSelectable(bool selectable) +{ + if (mSelectable != selectable) + { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } +} + +/*! + Sets whether this plottable is selected or not. When selected, it uses a different pen and brush + to draw its lines and fills, see \ref setSelectedPen and \ref setSelectedBrush. + + The entire selection mechanism for plottables is handled automatically when \ref + QCustomPlot::setInteractions contains iSelectPlottables. You only need to call this function when + you wish to change the selection state manually. + + This function can change the selection state even when \ref setSelectable was set to false. + + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. + + \see setSelectable, selectTest +*/ +void QCPAbstractPlottable::setSelected(bool selected) +{ + if (mSelected != selected) + { + mSelected = selected; + emit selectionChanged(mSelected); + } +} + +/*! + Rescales the key and value axes associated with this plottable to contain all displayed data, so + the whole plottable is visible. If the scaling of an axis is logarithmic, rescaleAxes will make + sure not to rescale to an illegal range i.e. a range containing different signs and/or zero. + Instead it will stay in the current sign domain and ignore all parts of the plottable that lie + outside of that domain. + + \a onlyEnlarge makes sure the ranges are only expanded, never reduced. So it's possible to show + multiple plottables in their entirety by multiple calls to rescaleAxes where the first call has + \a onlyEnlarge set to false (the default), and all subsequent set to true. + + \see rescaleKeyAxis, rescaleValueAxis, QCustomPlot::rescaleAxes, QCPAxis::rescale +*/ +void QCPAbstractPlottable::rescaleAxes(bool onlyEnlarge) const +{ + rescaleKeyAxis(onlyEnlarge); + rescaleValueAxis(onlyEnlarge); +} + +/*! + Rescales the key axis of the plottable so the whole plottable is visible. + + See \ref rescaleAxes for detailed behaviour. +*/ +void QCPAbstractPlottable::rescaleKeyAxis(bool onlyEnlarge) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } + + SignDomain signDomain = sdBoth; + if (keyAxis->scaleType() == QCPAxis::stLogarithmic) + signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive); + + bool foundRange; + QCPRange newRange = getKeyRange(foundRange, signDomain); + if (foundRange) + { + if (onlyEnlarge) + newRange.expand(keyAxis->range()); + if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + { + double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (keyAxis->scaleType() == QCPAxis::stLinear) + { + newRange.lower = center-keyAxis->range().size()/2.0; + newRange.upper = center+keyAxis->range().size()/2.0; + } else // scaleType() == stLogarithmic + { + newRange.lower = center/qSqrt(keyAxis->range().upper/keyAxis->range().lower); + newRange.upper = center*qSqrt(keyAxis->range().upper/keyAxis->range().lower); + } + } + keyAxis->setRange(newRange); + } +} + +/*! + Rescales the value axis of the plottable so the whole plottable is visible. + + Returns true if the axis was actually scaled. This might not be the case if this plottable has an + invalid range, e.g. because it has no data points. + + See \ref rescaleAxes for detailed behaviour. +*/ +void QCPAbstractPlottable::rescaleValueAxis(bool onlyEnlarge) const +{ + QCPAxis *valueAxis = mValueAxis.data(); + if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; } + + SignDomain signDomain = sdBoth; + if (valueAxis->scaleType() == QCPAxis::stLogarithmic) + signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive); + + bool foundRange; + QCPRange newRange = getValueRange(foundRange, signDomain); + if (foundRange) + { + if (onlyEnlarge) + newRange.expand(valueAxis->range()); + if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this axis dimension), shift current range to at least center the plottable + { + double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (valueAxis->scaleType() == QCPAxis::stLinear) + { + newRange.lower = center-valueAxis->range().size()/2.0; + newRange.upper = center+valueAxis->range().size()/2.0; + } else // scaleType() == stLogarithmic + { + newRange.lower = center/qSqrt(valueAxis->range().upper/valueAxis->range().lower); + newRange.upper = center*qSqrt(valueAxis->range().upper/valueAxis->range().lower); + } + } + valueAxis->setRange(newRange); + } +} + +/*! + Adds this plottable to the legend of the parent QCustomPlot (QCustomPlot::legend). + + Normally, a QCPPlottableLegendItem is created and inserted into the legend. If the plottable + needs a more specialized representation in the legend, this function will take this into account + and instead create the specialized subclass of QCPAbstractLegendItem. + + Returns true on success, i.e. when the legend exists and a legend item associated with this plottable isn't already in + the legend. + + \see removeFromLegend, QCPLegend::addItem +*/ +bool QCPAbstractPlottable::addToLegend() +{ + if (!mParentPlot || !mParentPlot->legend) + return false; + + if (!mParentPlot->legend->hasItemWithPlottable(this)) + { + mParentPlot->legend->addItem(new QCPPlottableLegendItem(mParentPlot->legend, this)); + return true; + } else + return false; +} + +/*! + Removes the plottable from the legend of the parent QCustomPlot. This means the + QCPAbstractLegendItem (usually a QCPPlottableLegendItem) that is associated with this plottable + is removed. + + Returns true on success, i.e. if the legend exists and a legend item associated with this + plottable was found and removed. + + \see addToLegend, QCPLegend::removeItem +*/ +bool QCPAbstractPlottable::removeFromLegend() const +{ + if (!mParentPlot->legend) + return false; + + if (QCPPlottableLegendItem *lip = mParentPlot->legend->itemWithPlottable(this)) + return mParentPlot->legend->removeItem(lip); + else + return false; +} + +/* inherits documentation from base class */ +QRect QCPAbstractPlottable::clipRect() const +{ + if (mKeyAxis && mValueAxis) + return mKeyAxis.data()->axisRect()->rect() & mValueAxis.data()->axisRect()->rect(); + else + return QRect(); +} + +/* inherits documentation from base class */ +QCP::Interaction QCPAbstractPlottable::selectionCategory() const +{ + return QCP::iSelectPlottables; +} + +/*! \internal + + Convenience function for transforming a key/value pair to pixels on the QCustomPlot surface, + taking the orientations of the axes associated with this plottable into account (e.g. whether key + represents x or y). + + \a key and \a value are transformed to the coodinates in pixels and are written to \a x and \a y. + + \see pixelsToCoords, QCPAxis::coordToPixel +*/ +void QCPAbstractPlottable::coordsToPixels(double key, double value, double &x, double &y) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + + if (keyAxis->orientation() == Qt::Horizontal) + { + x = keyAxis->coordToPixel(key); + y = valueAxis->coordToPixel(value); + } else + { + y = keyAxis->coordToPixel(key); + x = valueAxis->coordToPixel(value); + } +} + +/*! \internal + \overload + + Returns the input as pixel coordinates in a QPointF. +*/ +const QPointF QCPAbstractPlottable::coordsToPixels(double key, double value) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } + + if (keyAxis->orientation() == Qt::Horizontal) + return QPointF(keyAxis->coordToPixel(key), valueAxis->coordToPixel(value)); + else + return QPointF(valueAxis->coordToPixel(value), keyAxis->coordToPixel(key)); +} + +/*! \internal + + Convenience function for transforming a x/y pixel pair on the QCustomPlot surface to plot coordinates, + taking the orientations of the axes associated with this plottable into account (e.g. whether key + represents x or y). + + \a x and \a y are transformed to the plot coodinates and are written to \a key and \a value. + + \see coordsToPixels, QCPAxis::coordToPixel +*/ +void QCPAbstractPlottable::pixelsToCoords(double x, double y, double &key, double &value) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + + if (keyAxis->orientation() == Qt::Horizontal) + { + key = keyAxis->pixelToCoord(x); + value = valueAxis->pixelToCoord(y); + } else + { + key = keyAxis->pixelToCoord(y); + value = valueAxis->pixelToCoord(x); + } +} + +/*! \internal + \overload + + Returns the pixel input \a pixelPos as plot coordinates \a key and \a value. +*/ +void QCPAbstractPlottable::pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const +{ + pixelsToCoords(pixelPos.x(), pixelPos.y(), key, value); +} + +/*! \internal + + Returns the pen that should be used for drawing lines of the plottable. Returns mPen when the + graph is not selected and mSelectedPen when it is. +*/ +QPen QCPAbstractPlottable::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + +/*! \internal + + Returns the brush that should be used for drawing fills of the plottable. Returns mBrush when the + graph is not selected and mSelectedBrush when it is. +*/ +QBrush QCPAbstractPlottable::mainBrush() const +{ + return mSelected ? mSelectedBrush : mBrush; +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing plottable lines. + + This is the antialiasing state the painter passed to the \ref draw method is in by default. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint +*/ +void QCPAbstractPlottable::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiased, QCP::aePlottables); +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing plottable fills. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased, applyDefaultAntialiasingHint, applyScattersAntialiasingHint, applyErrorBarsAntialiasingHint +*/ +void QCPAbstractPlottable::applyFillAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiasedFill, QCP::aeFills); +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing plottable scatter points. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased, applyFillAntialiasingHint, applyDefaultAntialiasingHint, applyErrorBarsAntialiasingHint +*/ +void QCPAbstractPlottable::applyScattersAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiasedScatters, QCP::aeScatters); +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing plottable error bars. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased, applyFillAntialiasingHint, applyScattersAntialiasingHint, applyDefaultAntialiasingHint +*/ +void QCPAbstractPlottable::applyErrorBarsAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiasedErrorBars, QCP::aeErrorBars); +} + +/*! \internal + + Finds the shortest squared distance of \a point to the line segment defined by \a start and \a + end. + + This function may be used to help with the implementation of the \ref selectTest function for + specific plottables. + + \note This function is identical to QCPAbstractItem::distSqrToLine +*/ +double QCPAbstractPlottable::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const +{ + QVector2D a(start); + QVector2D b(end); + QVector2D p(point); + QVector2D v(b-a); + + double vLengthSqr = v.lengthSquared(); + if (!qFuzzyIsNull(vLengthSqr)) + { + double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr; + if (mu < 0) + return (a-p).lengthSquared(); + else if (mu > 1) + return (b-p).lengthSquared(); + else + return ((a + mu*v)-p).lengthSquared(); + } else + return (a-p).lengthSquared(); +} + +/* inherits documentation from base class */ +void QCPAbstractPlottable::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +{ + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable) + { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + +/* inherits documentation from base class */ +void QCPAbstractPlottable::deselectEvent(bool *selectionStateChanged) +{ + if (mSelectable) + { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemAnchor +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemAnchor + \brief An anchor of an item to which positions can be attached to. + + An item (QCPAbstractItem) may have one or more anchors. Unlike QCPItemPosition, an anchor doesn't + control anything on its item, but provides a way to tie other items via their positions to the + anchor. + + For example, a QCPItemRect is defined by its positions \a topLeft and \a bottomRight. + Additionally it has various anchors like \a top, \a topRight or \a bottomLeft etc. So you can + attach the \a start (which is a QCPItemPosition) of a QCPItemLine to one of the anchors by + calling QCPItemPosition::setParentAnchor on \a start, passing the wanted anchor of the + QCPItemRect. This way the start of the line will now always follow the respective anchor location + on the rect item. + + Note that QCPItemPosition derives from QCPItemAnchor, so every position can also serve as an + anchor to other positions. + + To learn how to provide anchors in your own item subclasses, see the subclassing section of the + QCPAbstractItem documentation. +*/ + +/* start documentation of inline functions */ + +/*! \fn virtual QCPItemPosition *QCPItemAnchor::toQCPItemPosition() + + Returns 0 if this instance is merely a QCPItemAnchor, and a valid pointer of type QCPItemPosition* if + it actually is a QCPItemPosition (which is a subclass of QCPItemAnchor). + + This safe downcast functionality could also be achieved with a dynamic_cast. However, QCustomPlot avoids + dynamic_cast to work with projects that don't have RTTI support enabled (e.g. -fno-rtti flag with + gcc compiler). +*/ + +/* end documentation of inline functions */ + +/*! + Creates a new QCPItemAnchor. You shouldn't create QCPItemAnchor instances directly, even if + you want to make a new item subclass. Use \ref QCPAbstractItem::createAnchor instead, as + explained in the subclassing section of the QCPAbstractItem documentation. +*/ +QCPItemAnchor::QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId) : + mName(name), + mParentPlot(parentPlot), + mParentItem(parentItem), + mAnchorId(anchorId) +{ +} + +QCPItemAnchor::~QCPItemAnchor() +{ + // unregister as parent at children: + foreach (QCPItemPosition *child, mChildrenX.toList()) + { + if (child->parentAnchorX() == this) + child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX + } + foreach (QCPItemPosition *child, mChildrenY.toList()) + { + if (child->parentAnchorY() == this) + child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY + } +} + +/*! + Returns the final absolute pixel position of the QCPItemAnchor on the QCustomPlot surface. + + The pixel information is internally retrieved via QCPAbstractItem::anchorPixelPosition of the + parent item, QCPItemAnchor is just an intermediary. +*/ +QPointF QCPItemAnchor::pixelPoint() const +{ + if (mParentItem) + { + if (mAnchorId > -1) + { + return mParentItem->anchorPixelPoint(mAnchorId); + } else + { + qDebug() << Q_FUNC_INFO << "no valid anchor id set:" << mAnchorId; + return QPointF(); + } + } else + { + qDebug() << Q_FUNC_INFO << "no parent item set"; + return QPointF(); + } +} + +/*! \internal + + Adds \a pos to the childX list of this anchor, which keeps track of which children use this + anchor as parent anchor for the respective coordinate. This is necessary to notify the children + prior to destruction of the anchor. + + Note that this function does not change the parent setting in \a pos. +*/ +void QCPItemAnchor::addChildX(QCPItemPosition *pos) +{ + if (!mChildrenX.contains(pos)) + mChildrenX.insert(pos); + else + qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); +} + +/*! \internal + + Removes \a pos from the childX list of this anchor. + + Note that this function does not change the parent setting in \a pos. +*/ +void QCPItemAnchor::removeChildX(QCPItemPosition *pos) +{ + if (!mChildrenX.remove(pos)) + qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); +} + +/*! \internal + + Adds \a pos to the childY list of this anchor, which keeps track of which children use this + anchor as parent anchor for the respective coordinate. This is necessary to notify the children + prior to destruction of the anchor. + + Note that this function does not change the parent setting in \a pos. +*/ +void QCPItemAnchor::addChildY(QCPItemPosition *pos) +{ + if (!mChildrenY.contains(pos)) + mChildrenY.insert(pos); + else + qDebug() << Q_FUNC_INFO << "provided pos is child already" << reinterpret_cast(pos); +} + +/*! \internal + + Removes \a pos from the childY list of this anchor. + + Note that this function does not change the parent setting in \a pos. +*/ +void QCPItemAnchor::removeChildY(QCPItemPosition *pos) +{ + if (!mChildrenY.remove(pos)) + qDebug() << Q_FUNC_INFO << "provided pos isn't child" << reinterpret_cast(pos); +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemPosition +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemPosition + \brief Manages the position of an item. + + Every item has at least one public QCPItemPosition member pointer which provides ways to position the + item on the QCustomPlot surface. Some items have multiple positions, for example QCPItemRect has two: + \a topLeft and \a bottomRight. + + QCPItemPosition has a type (\ref PositionType) that can be set with \ref setType. This type + defines how coordinates passed to \ref setCoords are to be interpreted, e.g. as absolute pixel + coordinates, as plot coordinates of certain axes, etc. For more advanced plots it is also + possible to assign different types per X/Y coordinate of the position (see \ref setTypeX, \ref + setTypeY). This way an item could be positioned at a fixed pixel distance from the top in the Y + direction, while following a plot coordinate in the X direction. + + A QCPItemPosition may have a parent QCPItemAnchor, see \ref setParentAnchor. This way you can tie + multiple items together. If the QCPItemPosition has a parent, its coordinates (\ref setCoords) + are considered to be absolute pixels in the reference frame of the parent anchor, where (0, 0) + means directly ontop of the parent anchor. For example, You could attach the \a start position of + a QCPItemLine to the \a bottom anchor of a QCPItemText to make the starting point of the line + always be centered under the text label, no matter where the text is moved to. For more advanced + plots, it is possible to assign different parent anchors per X/Y coordinate of the position, see + \ref setParentAnchorX, \ref setParentAnchorY. This way an item could follow another item in the X + direction but stay at a fixed position in the Y direction. Or even follow item A in X, and item B + in Y. + + Note that every QCPItemPosition inherits from QCPItemAnchor and thus can itself be used as parent + anchor for other positions. + + To set the apparent pixel position on the QCustomPlot surface directly, use \ref setPixelPoint. This + works no matter what type this QCPItemPosition is or what parent-child situation it is in, as \ref + setPixelPoint transforms the coordinates appropriately, to make the position appear at the specified + pixel values. +*/ + +/* start documentation of inline functions */ + +/*! \fn QCPItemPosition::PositionType *QCPItemPosition::type() const + + Returns the current position type. + + If different types were set for X and Y (\ref setTypeX, \ref setTypeY), this method returns the + type of the X coordinate. In that case rather use \a typeX() and \a typeY(). + + \see setType +*/ + +/*! \fn QCPItemAnchor *QCPItemPosition::parentAnchor() const + + Returns the current parent anchor. + + If different parent anchors were set for X and Y (\ref setParentAnchorX, \ref setParentAnchorY), + this method returns the parent anchor of the Y coordinate. In that case rather use \a + parentAnchorX() and \a parentAnchorY(). + + \see setParentAnchor +*/ + +/* end documentation of inline functions */ + +/*! + Creates a new QCPItemPosition. You shouldn't create QCPItemPosition instances directly, even if + you want to make a new item subclass. Use \ref QCPAbstractItem::createPosition instead, as + explained in the subclassing section of the QCPAbstractItem documentation. +*/ +QCPItemPosition::QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name) : + QCPItemAnchor(parentPlot, parentItem, name), + mPositionTypeX(ptAbsolute), + mPositionTypeY(ptAbsolute), + mKey(0), + mValue(0), + mParentAnchorX(0), + mParentAnchorY(0) +{ +} + +QCPItemPosition::~QCPItemPosition() +{ + // unregister as parent at children: + // Note: this is done in ~QCPItemAnchor again, but it's important QCPItemPosition does it itself, because only then + // the setParentAnchor(0) call the correct QCPItemPosition::pixelPoint function instead of QCPItemAnchor::pixelPoint + foreach (QCPItemPosition *child, mChildrenX.toList()) + { + if (child->parentAnchorX() == this) + child->setParentAnchorX(0); // this acts back on this anchor and child removes itself from mChildrenX + } + foreach (QCPItemPosition *child, mChildrenY.toList()) + { + if (child->parentAnchorY() == this) + child->setParentAnchorY(0); // this acts back on this anchor and child removes itself from mChildrenY + } + // unregister as child in parent: + if (mParentAnchorX) + mParentAnchorX->removeChildX(this); + if (mParentAnchorY) + mParentAnchorY->removeChildY(this); +} + +/* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ +QCPAxisRect *QCPItemPosition::axisRect() const +{ + return mAxisRect.data(); +} + +/*! + Sets the type of the position. The type defines how the coordinates passed to \ref setCoords + should be handled and how the QCPItemPosition should behave in the plot. + + The possible values for \a type can be separated in two main categories: + + \li The position is regarded as a point in plot coordinates. This corresponds to \ref ptPlotCoords + and requires two axes that define the plot coordinate system. They can be specified with \ref setAxes. + By default, the QCustomPlot's x- and yAxis are used. + + \li The position is fixed on the QCustomPlot surface, i.e. independent of axis ranges. This + corresponds to all other types, i.e. \ref ptAbsolute, \ref ptViewportRatio and \ref + ptAxisRectRatio. They differ only in the way the absolute position is described, see the + documentation of \ref PositionType for details. For \ref ptAxisRectRatio, note that you can specify + the axis rect with \ref setAxisRect. By default this is set to the main axis rect. + + Note that the position type \ref ptPlotCoords is only available (and sensible) when the position + has no parent anchor (\ref setParentAnchor). + + If the type is changed, the apparent pixel position on the plot is preserved. This means + the coordinates as retrieved with coords() and set with \ref setCoords may change in the process. + + This method sets the type for both X and Y directions. It is also possible to set different types + for X and Y, see \ref setTypeX, \ref setTypeY. +*/ +void QCPItemPosition::setType(QCPItemPosition::PositionType type) +{ + setTypeX(type); + setTypeY(type); +} + +/*! + This method sets the position type of the X coordinate to \a type. + + For a detailed description of what a position type is, see the documentation of \ref setType. + + \see setType, setTypeY +*/ +void QCPItemPosition::setTypeX(QCPItemPosition::PositionType type) +{ + if (mPositionTypeX != type) + { + // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect + // were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning. + bool retainPixelPosition = true; + if ((mPositionTypeX == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) + retainPixelPosition = false; + if ((mPositionTypeX == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) + retainPixelPosition = false; + + QPointF pixel; + if (retainPixelPosition) + pixel = pixelPoint(); + + mPositionTypeX = type; + + if (retainPixelPosition) + setPixelPoint(pixel); + } +} + +/*! + This method sets the position type of the Y coordinate to \a type. + + For a detailed description of what a position type is, see the documentation of \ref setType. + + \see setType, setTypeX +*/ +void QCPItemPosition::setTypeY(QCPItemPosition::PositionType type) +{ + if (mPositionTypeY != type) + { + // if switching from or to coordinate type that isn't valid (e.g. because axes or axis rect + // were deleted), don't try to recover the pixelPoint() because it would output a qDebug warning. + bool retainPixelPosition = true; + if ((mPositionTypeY == ptPlotCoords || type == ptPlotCoords) && (!mKeyAxis || !mValueAxis)) + retainPixelPosition = false; + if ((mPositionTypeY == ptAxisRectRatio || type == ptAxisRectRatio) && (!mAxisRect)) + retainPixelPosition = false; + + QPointF pixel; + if (retainPixelPosition) + pixel = pixelPoint(); + + mPositionTypeY = type; + + if (retainPixelPosition) + setPixelPoint(pixel); + } +} + +/*! + Sets the parent of this QCPItemPosition to \a parentAnchor. This means the position will now + follow any position changes of the anchor. The local coordinate system of positions with a parent + anchor always is absolute pixels, with (0, 0) being exactly on top of the parent anchor. (Hence + the type shouldn't be set to \ref ptPlotCoords for positions with parent anchors.) + + if \a keepPixelPosition is true, the current pixel position of the QCPItemPosition is preserved + during reparenting. If it's set to false, the coordinates are set to (0, 0), i.e. the position + will be exactly on top of the parent anchor. + + To remove this QCPItemPosition from any parent anchor, set \a parentAnchor to 0. + + If the QCPItemPosition previously had no parent and the type is \ref ptPlotCoords, the type is + set to \ref ptAbsolute, to keep the position in a valid state. + + This method sets the parent anchor for both X and Y directions. It is also possible to set + different parents for X and Y, see \ref setParentAnchorX, \ref setParentAnchorY. +*/ +bool QCPItemPosition::setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition) +{ + bool successX = setParentAnchorX(parentAnchor, keepPixelPosition); + bool successY = setParentAnchorY(parentAnchor, keepPixelPosition); + return successX && successY; +} + +/*! + This method sets the parent anchor of the X coordinate to \a parentAnchor. + + For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. + + \see setParentAnchor, setParentAnchorY +*/ +bool QCPItemPosition::setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition) +{ + // make sure self is not assigned as parent: + if (parentAnchor == this) + { + qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); + return false; + } + // make sure no recursive parent-child-relationships are created: + QCPItemAnchor *currentParent = parentAnchor; + while (currentParent) + { + if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) + { + // is a QCPItemPosition, might have further parent, so keep iterating + if (currentParentPos == this) + { + qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + return false; + } + currentParent = currentParentPos->parentAnchorX(); + } else + { + // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the + // same, to prevent a position being child of an anchor which itself depends on the position, + // because they're both on the same item: + if (currentParent->mParentItem == mParentItem) + { + qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); + return false; + } + break; + } + } + + // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: + if (!mParentAnchorX && mPositionTypeX == ptPlotCoords) + setTypeX(ptAbsolute); + + // save pixel position: + QPointF pixelP; + if (keepPixelPosition) + pixelP = pixelPoint(); + // unregister at current parent anchor: + if (mParentAnchorX) + mParentAnchorX->removeChildX(this); + // register at new parent anchor: + if (parentAnchor) + parentAnchor->addChildX(this); + mParentAnchorX = parentAnchor; + // restore pixel position under new parent: + if (keepPixelPosition) + setPixelPoint(pixelP); + else + setCoords(0, coords().y()); + return true; +} + +/*! + This method sets the parent anchor of the Y coordinate to \a parentAnchor. + + For a detailed description of what a parent anchor is, see the documentation of \ref setParentAnchor. + + \see setParentAnchor, setParentAnchorX +*/ +bool QCPItemPosition::setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition) +{ + // make sure self is not assigned as parent: + if (parentAnchor == this) + { + qDebug() << Q_FUNC_INFO << "can't set self as parent anchor" << reinterpret_cast(parentAnchor); + return false; + } + // make sure no recursive parent-child-relationships are created: + QCPItemAnchor *currentParent = parentAnchor; + while (currentParent) + { + if (QCPItemPosition *currentParentPos = currentParent->toQCPItemPosition()) + { + // is a QCPItemPosition, might have further parent, so keep iterating + if (currentParentPos == this) + { + qDebug() << Q_FUNC_INFO << "can't create recursive parent-child-relationship" << reinterpret_cast(parentAnchor); + return false; + } + currentParent = currentParentPos->parentAnchorY(); + } else + { + // is a QCPItemAnchor, can't have further parent. Now make sure the parent items aren't the + // same, to prevent a position being child of an anchor which itself depends on the position, + // because they're both on the same item: + if (currentParent->mParentItem == mParentItem) + { + qDebug() << Q_FUNC_INFO << "can't set parent to be an anchor which itself depends on this position" << reinterpret_cast(parentAnchor); + return false; + } + break; + } + } + + // if previously no parent set and PosType is still ptPlotCoords, set to ptAbsolute: + if (!mParentAnchorY && mPositionTypeY == ptPlotCoords) + setTypeY(ptAbsolute); + + // save pixel position: + QPointF pixelP; + if (keepPixelPosition) + pixelP = pixelPoint(); + // unregister at current parent anchor: + if (mParentAnchorY) + mParentAnchorY->removeChildY(this); + // register at new parent anchor: + if (parentAnchor) + parentAnchor->addChildY(this); + mParentAnchorY = parentAnchor; + // restore pixel position under new parent: + if (keepPixelPosition) + setPixelPoint(pixelP); + else + setCoords(coords().x(), 0); + return true; +} + +/*! + Sets the coordinates of this QCPItemPosition. What the coordinates mean, is defined by the type + (\ref setType, \ref setTypeX, \ref setTypeY). + + For example, if the type is \ref ptAbsolute, \a key and \a value mean the x and y pixel position + on the QCustomPlot surface. In that case the origin (0, 0) is in the top left corner of the + QCustomPlot viewport. If the type is \ref ptPlotCoords, \a key and \a value mean a point in the + plot coordinate system defined by the axes set by \ref setAxes. By default those are the + QCustomPlot's xAxis and yAxis. See the documentation of \ref setType for other available + coordinate types and their meaning. + + If different types were configured for X and Y (\ref setTypeX, \ref setTypeY), \a key and \a + value must also be provided in the different coordinate systems. Here, the X type refers to \a + key, and the Y type refers to \a value. + + \see setPixelPoint +*/ +void QCPItemPosition::setCoords(double key, double value) +{ + mKey = key; + mValue = value; +} + +/*! \overload + + Sets the coordinates as a QPointF \a pos where pos.x has the meaning of \a key and pos.y the + meaning of \a value of the \ref setCoords(double key, double value) method. +*/ +void QCPItemPosition::setCoords(const QPointF &pos) +{ + setCoords(pos.x(), pos.y()); +} + +/*! + Returns the final absolute pixel position of the QCPItemPosition on the QCustomPlot surface. It + includes all effects of type (\ref setType) and possible parent anchors (\ref setParentAnchor). + + \see setPixelPoint +*/ +QPointF QCPItemPosition::pixelPoint() const +{ + QPointF result; + + // determine X: + switch (mPositionTypeX) + { + case ptAbsolute: + { + result.rx() = mKey; + if (mParentAnchorX) + result.rx() += mParentAnchorX->pixelPoint().x(); + break; + } + case ptViewportRatio: + { + result.rx() = mKey*mParentPlot->viewport().width(); + if (mParentAnchorX) + result.rx() += mParentAnchorX->pixelPoint().x(); + else + result.rx() += mParentPlot->viewport().left(); + break; + } + case ptAxisRectRatio: + { + if (mAxisRect) + { + result.rx() = mKey*mAxisRect.data()->width(); + if (mParentAnchorX) + result.rx() += mParentAnchorX->pixelPoint().x(); + else + result.rx() += mAxisRect.data()->left(); + } else + qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; + break; + } + case ptPlotCoords: + { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) + result.rx() = mKeyAxis.data()->coordToPixel(mKey); + else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) + result.rx() = mValueAxis.data()->coordToPixel(mValue); + else + qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; + break; + } + } + + // determine Y: + switch (mPositionTypeY) + { + case ptAbsolute: + { + result.ry() = mValue; + if (mParentAnchorY) + result.ry() += mParentAnchorY->pixelPoint().y(); + break; + } + case ptViewportRatio: + { + result.ry() = mValue*mParentPlot->viewport().height(); + if (mParentAnchorY) + result.ry() += mParentAnchorY->pixelPoint().y(); + else + result.ry() += mParentPlot->viewport().top(); + break; + } + case ptAxisRectRatio: + { + if (mAxisRect) + { + result.ry() = mValue*mAxisRect.data()->height(); + if (mParentAnchorY) + result.ry() += mParentAnchorY->pixelPoint().y(); + else + result.ry() += mAxisRect.data()->top(); + } else + qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; + break; + } + case ptPlotCoords: + { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) + result.ry() = mKeyAxis.data()->coordToPixel(mKey); + else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) + result.ry() = mValueAxis.data()->coordToPixel(mValue); + else + qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; + break; + } + } + + return result; +} + +/*! + When \ref setType is \ref ptPlotCoords, this function may be used to specify the axes the + coordinates set with \ref setCoords relate to. By default they are set to the initial xAxis and + yAxis of the QCustomPlot. +*/ +void QCPItemPosition::setAxes(QCPAxis *keyAxis, QCPAxis *valueAxis) +{ + mKeyAxis = keyAxis; + mValueAxis = valueAxis; +} + +/*! + When \ref setType is \ref ptAxisRectRatio, this function may be used to specify the axis rect the + coordinates set with \ref setCoords relate to. By default this is set to the main axis rect of + the QCustomPlot. +*/ +void QCPItemPosition::setAxisRect(QCPAxisRect *axisRect) +{ + mAxisRect = axisRect; +} + +/*! + Sets the apparent pixel position. This works no matter what type (\ref setType) this + QCPItemPosition is or what parent-child situation it is in, as coordinates are transformed + appropriately, to make the position finally appear at the specified pixel values. + + Only if the type is \ref ptAbsolute and no parent anchor is set, this function's effect is + identical to that of \ref setCoords. + + \see pixelPoint, setCoords +*/ +void QCPItemPosition::setPixelPoint(const QPointF &pixelPoint) +{ + double x = pixelPoint.x(); + double y = pixelPoint.y(); + + switch (mPositionTypeX) + { + case ptAbsolute: + { + if (mParentAnchorX) + x -= mParentAnchorX->pixelPoint().x(); + break; + } + case ptViewportRatio: + { + if (mParentAnchorX) + x -= mParentAnchorX->pixelPoint().x(); + else + x -= mParentPlot->viewport().left(); + x /= (double)mParentPlot->viewport().width(); + break; + } + case ptAxisRectRatio: + { + if (mAxisRect) + { + if (mParentAnchorX) + x -= mParentAnchorX->pixelPoint().x(); + else + x -= mAxisRect.data()->left(); + x /= (double)mAxisRect.data()->width(); + } else + qDebug() << Q_FUNC_INFO << "Item position type x is ptAxisRectRatio, but no axis rect was defined"; + break; + } + case ptPlotCoords: + { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Horizontal) + x = mKeyAxis.data()->pixelToCoord(x); + else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Horizontal) + y = mValueAxis.data()->pixelToCoord(x); + else + qDebug() << Q_FUNC_INFO << "Item position type x is ptPlotCoords, but no axes were defined"; + break; + } + } + + switch (mPositionTypeY) + { + case ptAbsolute: + { + if (mParentAnchorY) + y -= mParentAnchorY->pixelPoint().y(); + break; + } + case ptViewportRatio: + { + if (mParentAnchorY) + y -= mParentAnchorY->pixelPoint().y(); + else + y -= mParentPlot->viewport().top(); + y /= (double)mParentPlot->viewport().height(); + break; + } + case ptAxisRectRatio: + { + if (mAxisRect) + { + if (mParentAnchorY) + y -= mParentAnchorY->pixelPoint().y(); + else + y -= mAxisRect.data()->top(); + y /= (double)mAxisRect.data()->height(); + } else + qDebug() << Q_FUNC_INFO << "Item position type y is ptAxisRectRatio, but no axis rect was defined"; + break; + } + case ptPlotCoords: + { + if (mKeyAxis && mKeyAxis.data()->orientation() == Qt::Vertical) + x = mKeyAxis.data()->pixelToCoord(y); + else if (mValueAxis && mValueAxis.data()->orientation() == Qt::Vertical) + y = mValueAxis.data()->pixelToCoord(y); + else + qDebug() << Q_FUNC_INFO << "Item position type y is ptPlotCoords, but no axes were defined"; + break; + } + } + + setCoords(x, y); +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPAbstractItem +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPAbstractItem + \brief The abstract base class for all items in a plot. + + In QCustomPlot, items are supplemental graphical elements that are neither plottables + (QCPAbstractPlottable) nor axes (QCPAxis). While plottables are always tied to two axes and thus + plot coordinates, items can also be placed in absolute coordinates independent of any axes. Each + specific item has at least one QCPItemPosition member which controls the positioning. Some items + are defined by more than one coordinate and thus have two or more QCPItemPosition members (For + example, QCPItemRect has \a topLeft and \a bottomRight). + + This abstract base class defines a very basic interface like visibility and clipping. Since this + class is abstract, it can't be instantiated. Use one of the subclasses or create a subclass + yourself to create new items. + + The built-in items are: + + + + + + + + + + +
QCPItemLineA line defined by a start and an end point. May have different ending styles on each side (e.g. arrows).
QCPItemStraightLineA straight line defined by a start and a direction point. Unlike QCPItemLine, the straight line is infinitely long and has no endings.
QCPItemCurveA curve defined by start, end and two intermediate control points. May have different ending styles on each side (e.g. arrows).
QCPItemRectA rectangle
QCPItemEllipseAn ellipse
QCPItemPixmapAn arbitrary pixmap
QCPItemTextA text label
QCPItemBracketA bracket which may be used to reference/highlight certain parts in the plot.
QCPItemTracerAn item that can be attached to a QCPGraph and sticks to its data points, given a key coordinate.
+ + \section items-clipping Clipping + + Items are by default clipped to the main axis rect (they are only visible inside the axis rect). + To make an item visible outside that axis rect, disable clipping via \ref setClipToAxisRect + "setClipToAxisRect(false)". + + On the other hand if you want the item to be clipped to a different axis rect, specify it via + \ref setClipAxisRect. This clipAxisRect property of an item is only used for clipping behaviour, and + in principle is independent of the coordinate axes the item might be tied to via its position + members (\ref QCPItemPosition::setAxes). However, it is common that the axis rect for clipping + also contains the axes used for the item positions. + + \section items-using Using items + + First you instantiate the item you want to use and add it to the plot: + \code + QCPItemLine *line = new QCPItemLine(customPlot); + customPlot->addItem(line); + \endcode + by default, the positions of the item are bound to the x- and y-Axis of the plot. So we can just + set the plot coordinates where the line should start/end: + \code + line->start->setCoords(-0.1, 0.8); + line->end->setCoords(1.1, 0.2); + \endcode + If we don't want the line to be positioned in plot coordinates but a different coordinate system, + e.g. absolute pixel positions on the QCustomPlot surface, we need to change the position type like this: + \code + line->start->setType(QCPItemPosition::ptAbsolute); + line->end->setType(QCPItemPosition::ptAbsolute); + \endcode + Then we can set the coordinates, this time in pixels: + \code + line->start->setCoords(100, 200); + line->end->setCoords(450, 320); + \endcode + and make the line visible on the entire QCustomPlot, by disabling clipping to the axis rect: + \code + line->setClipToAxisRect(false); + \endcode + + For more advanced plots, it is even possible to set different types and parent anchors per X/Y + coordinate of an item position, using for example \ref QCPItemPosition::setTypeX or \ref + QCPItemPosition::setParentAnchorX. For details, see the documentation of \ref QCPItemPosition. + + \section items-subclassing Creating own items + + To create an own item, you implement a subclass of QCPAbstractItem. These are the pure + virtual functions, you must implement: + \li \ref selectTest + \li \ref draw + + See the documentation of those functions for what they need to do. + + \subsection items-positioning Allowing the item to be positioned + + As mentioned, item positions are represented by QCPItemPosition members. Let's assume the new item shall + have only one point as its position (as opposed to two like a rect or multiple like a polygon). You then add + a public member of type QCPItemPosition like so: + + \code QCPItemPosition * const myPosition;\endcode + + the const makes sure the pointer itself can't be modified from the user of your new item (the QCPItemPosition + instance it points to, can be modified, of course). + The initialization of this pointer is made easy with the \ref createPosition function. Just assign + the return value of this function to each QCPItemPosition in the constructor of your item. \ref createPosition + takes a string which is the name of the position, typically this is identical to the variable name. + For example, the constructor of QCPItemExample could look like this: + + \code + QCPItemExample::QCPItemExample(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + myPosition(createPosition("myPosition")) + { + // other constructor code + } + \endcode + + \subsection items-drawing The draw function + + To give your item a visual representation, reimplement the \ref draw function and use the passed + QCPPainter to draw the item. You can retrieve the item position in pixel coordinates from the + position member(s) via \ref QCPItemPosition::pixelPoint. + + To optimize performance you should calculate a bounding rect first (don't forget to take the pen + width into account), check whether it intersects the \ref clipRect, and only draw the item at all + if this is the case. + + \subsection items-selection The selectTest function + + Your implementation of the \ref selectTest function may use the helpers \ref distSqrToLine and + \ref rectSelectTest. With these, the implementation of the selection test becomes significantly + simpler for most items. See the documentation of \ref selectTest for what the function parameters + mean and what the function should return. + + \subsection anchors Providing anchors + + Providing anchors (QCPItemAnchor) starts off like adding a position. First you create a public + member, e.g. + + \code QCPItemAnchor * const bottom;\endcode + + and create it in the constructor with the \ref createAnchor function, assigning it a name and an + anchor id (an integer enumerating all anchors on the item, you may create an own enum for this). + Since anchors can be placed anywhere, relative to the item's position(s), your item needs to + provide the position of every anchor with the reimplementation of the \ref anchorPixelPoint(int + anchorId) function. + + In essence the QCPItemAnchor is merely an intermediary that itself asks your item for the pixel + position when anything attached to the anchor needs to know the coordinates. +*/ + +/* start of documentation of inline functions */ + +/*! \fn QList QCPAbstractItem::positions() const + + Returns all positions of the item in a list. + + \see anchors, position +*/ + +/*! \fn QList QCPAbstractItem::anchors() const + + Returns all anchors of the item in a list. Note that since a position (QCPItemPosition) is always + also an anchor, the list will also contain the positions of this item. + + \see positions, anchor +*/ + +/* end of documentation of inline functions */ +/* start documentation of pure virtual functions */ + +/*! \fn void QCPAbstractItem::draw(QCPPainter *painter) = 0 + \internal + + Draws this item with the provided \a painter. + + The cliprect of the provided painter is set to the rect returned by \ref clipRect before this + function is called. The clipRect depends on the clipping settings defined by \ref + setClipToAxisRect and \ref setClipAxisRect. +*/ + +/* end documentation of pure virtual functions */ +/* start documentation of signals */ + +/*! \fn void QCPAbstractItem::selectionChanged(bool selected) + This signal is emitted when the selection state of this item has changed, either by user interaction + or by a direct call to \ref setSelected. +*/ + +/* end documentation of signals */ + +/*! + Base class constructor which initializes base class members. +*/ +QCPAbstractItem::QCPAbstractItem(QCustomPlot *parentPlot) : + QCPLayerable(parentPlot), + mClipToAxisRect(false), + mSelectable(true), + mSelected(false) +{ + QList rects = parentPlot->axisRects(); + if (rects.size() > 0) + { + setClipToAxisRect(true); + setClipAxisRect(rects.first()); + } +} + +QCPAbstractItem::~QCPAbstractItem() +{ + // don't delete mPositions because every position is also an anchor and thus in mAnchors + qDeleteAll(mAnchors); +} + +/* can't make this a header inline function, because QPointer breaks with forward declared types, see QTBUG-29588 */ +QCPAxisRect *QCPAbstractItem::clipAxisRect() const +{ + return mClipAxisRect.data(); +} + +/*! + Sets whether the item shall be clipped to an axis rect or whether it shall be visible on the + entire QCustomPlot. The axis rect can be set with \ref setClipAxisRect. + + \see setClipAxisRect +*/ +void QCPAbstractItem::setClipToAxisRect(bool clip) +{ + mClipToAxisRect = clip; + if (mClipToAxisRect) + setParentLayerable(mClipAxisRect.data()); +} + +/*! + Sets the clip axis rect. It defines the rect that will be used to clip the item when \ref + setClipToAxisRect is set to true. + + \see setClipToAxisRect +*/ +void QCPAbstractItem::setClipAxisRect(QCPAxisRect *rect) +{ + mClipAxisRect = rect; + if (mClipToAxisRect) + setParentLayerable(mClipAxisRect.data()); +} + +/*! + Sets whether the user can (de-)select this item by clicking on the QCustomPlot surface. + (When \ref QCustomPlot::setInteractions contains QCustomPlot::iSelectItems.) + + However, even when \a selectable was set to false, it is possible to set the selection manually, + by calling \ref setSelected. + + \see QCustomPlot::setInteractions, setSelected +*/ +void QCPAbstractItem::setSelectable(bool selectable) +{ + if (mSelectable != selectable) + { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } +} + +/*! + Sets whether this item is selected or not. When selected, it might use a different visual + appearance (e.g. pen and brush), this depends on the specific item though. + + The entire selection mechanism for items is handled automatically when \ref + QCustomPlot::setInteractions contains QCustomPlot::iSelectItems. You only need to call this + function when you wish to change the selection state manually. + + This function can change the selection state even when \ref setSelectable was set to false. + + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. + + \see setSelectable, selectTest +*/ +void QCPAbstractItem::setSelected(bool selected) +{ + if (mSelected != selected) + { + mSelected = selected; + emit selectionChanged(mSelected); + } +} + +/*! + Returns the QCPItemPosition with the specified \a name. If this item doesn't have a position by + that name, returns 0. + + This function provides an alternative way to access item positions. Normally, you access + positions direcly by their member pointers (which typically have the same variable name as \a + name). + + \see positions, anchor +*/ +QCPItemPosition *QCPAbstractItem::position(const QString &name) const +{ + for (int i=0; iname() == name) + return mPositions.at(i); + } + qDebug() << Q_FUNC_INFO << "position with name not found:" << name; + return 0; +} + +/*! + Returns the QCPItemAnchor with the specified \a name. If this item doesn't have an anchor by + that name, returns 0. + + This function provides an alternative way to access item anchors. Normally, you access + anchors direcly by their member pointers (which typically have the same variable name as \a + name). + + \see anchors, position +*/ +QCPItemAnchor *QCPAbstractItem::anchor(const QString &name) const +{ + for (int i=0; iname() == name) + return mAnchors.at(i); + } + qDebug() << Q_FUNC_INFO << "anchor with name not found:" << name; + return 0; +} + +/*! + Returns whether this item has an anchor with the specified \a name. + + Note that you can check for positions with this function, too. This is because every position is + also an anchor (QCPItemPosition inherits from QCPItemAnchor). + + \see anchor, position +*/ +bool QCPAbstractItem::hasAnchor(const QString &name) const +{ + for (int i=0; iname() == name) + return true; + } + return false; +} + +/*! \internal + + Returns the rect the visual representation of this item is clipped to. This depends on the + current setting of \ref setClipToAxisRect as well as the axis rect set with \ref setClipAxisRect. + + If the item is not clipped to an axis rect, the \ref QCustomPlot::viewport rect is returned. + + \see draw +*/ +QRect QCPAbstractItem::clipRect() const +{ + if (mClipToAxisRect && mClipAxisRect) + return mClipAxisRect.data()->rect(); + else + return mParentPlot->viewport(); +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing item lines. + + This is the antialiasing state the painter passed to the \ref draw method is in by default. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased +*/ +void QCPAbstractItem::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiased, QCP::aeItems); +} + +/*! \internal + + Finds the shortest squared distance of \a point to the line segment defined by \a start and \a + end. + + This function may be used to help with the implementation of the \ref selectTest function for + specific items. + + \note This function is identical to QCPAbstractPlottable::distSqrToLine + + \see rectSelectTest +*/ +double QCPAbstractItem::distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const +{ + QVector2D a(start); + QVector2D b(end); + QVector2D p(point); + QVector2D v(b-a); + + double vLengthSqr = v.lengthSquared(); + if (!qFuzzyIsNull(vLengthSqr)) + { + double mu = QVector2D::dotProduct(p-a, v)/vLengthSqr; + if (mu < 0) + return (a-p).lengthSquared(); + else if (mu > 1) + return (b-p).lengthSquared(); + else + return ((a + mu*v)-p).lengthSquared(); + } else + return (a-p).lengthSquared(); +} + +/*! \internal + + A convenience function which returns the selectTest value for a specified \a rect and a specified + click position \a pos. \a filledRect defines whether a click inside the rect should also be + considered a hit or whether only the rect border is sensitive to hits. + + This function may be used to help with the implementation of the \ref selectTest function for + specific items. + + For example, if your item consists of four rects, call this function four times, once for each + rect, in your \ref selectTest reimplementation. Finally, return the minimum of all four returned + values which were greater or equal to zero. (Because this function may return -1.0 when \a pos + doesn't hit \a rect at all). If all calls returned -1.0, return -1.0, too, because your item + wasn't hit. + + \see distSqrToLine +*/ +double QCPAbstractItem::rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const +{ + double result = -1; + + // distance to border: + QList lines; + lines << QLineF(rect.topLeft(), rect.topRight()) << QLineF(rect.bottomLeft(), rect.bottomRight()) + << QLineF(rect.topLeft(), rect.bottomLeft()) << QLineF(rect.topRight(), rect.bottomRight()); + double minDistSqr = std::numeric_limits::max(); + for (int i=0; i mParentPlot->selectionTolerance()*0.99) + { + if (rect.contains(pos)) + result = mParentPlot->selectionTolerance()*0.99; + } + return result; +} + +/*! \internal + + Returns the pixel position of the anchor with Id \a anchorId. This function must be reimplemented in + item subclasses if they want to provide anchors (QCPItemAnchor). + + For example, if the item has two anchors with id 0 and 1, this function takes one of these anchor + ids and returns the respective pixel points of the specified anchor. + + \see createAnchor +*/ +QPointF QCPAbstractItem::anchorPixelPoint(int anchorId) const +{ + qDebug() << Q_FUNC_INFO << "called on item which shouldn't have any anchors (this method not reimplemented). anchorId" << anchorId; + return QPointF(); +} + +/*! \internal + + Creates a QCPItemPosition, registers it with this item and returns a pointer to it. The specified + \a name must be a unique string that is usually identical to the variable name of the position + member (This is needed to provide the name-based \ref position access to positions). + + Don't delete positions created by this function manually, as the item will take care of it. + + Use this function in the constructor (initialization list) of the specific item subclass to + create each position member. Don't create QCPItemPositions with \b new yourself, because they + won't be registered with the item properly. + + \see createAnchor +*/ +QCPItemPosition *QCPAbstractItem::createPosition(const QString &name) +{ + if (hasAnchor(name)) + qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; + QCPItemPosition *newPosition = new QCPItemPosition(mParentPlot, this, name); + mPositions.append(newPosition); + mAnchors.append(newPosition); // every position is also an anchor + newPosition->setAxes(mParentPlot->xAxis, mParentPlot->yAxis); + newPosition->setType(QCPItemPosition::ptPlotCoords); + if (mParentPlot->axisRect()) + newPosition->setAxisRect(mParentPlot->axisRect()); + newPosition->setCoords(0, 0); + return newPosition; +} + +/*! \internal + + Creates a QCPItemAnchor, registers it with this item and returns a pointer to it. The specified + \a name must be a unique string that is usually identical to the variable name of the anchor + member (This is needed to provide the name based \ref anchor access to anchors). + + The \a anchorId must be a number identifying the created anchor. It is recommended to create an + enum (e.g. "AnchorIndex") for this on each item that uses anchors. This id is used by the anchor + to identify itself when it calls QCPAbstractItem::anchorPixelPoint. That function then returns + the correct pixel coordinates for the passed anchor id. + + Don't delete anchors created by this function manually, as the item will take care of it. + + Use this function in the constructor (initialization list) of the specific item subclass to + create each anchor member. Don't create QCPItemAnchors with \b new yourself, because then they + won't be registered with the item properly. + + \see createPosition +*/ +QCPItemAnchor *QCPAbstractItem::createAnchor(const QString &name, int anchorId) +{ + if (hasAnchor(name)) + qDebug() << Q_FUNC_INFO << "anchor/position with name exists already:" << name; + QCPItemAnchor *newAnchor = new QCPItemAnchor(mParentPlot, this, name, anchorId); + mAnchors.append(newAnchor); + return newAnchor; +} + +/* inherits documentation from base class */ +void QCPAbstractItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +{ + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable) + { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + +/* inherits documentation from base class */ +void QCPAbstractItem::deselectEvent(bool *selectionStateChanged) +{ + if (mSelectable) + { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + +/* inherits documentation from base class */ +QCP::Interaction QCPAbstractItem::selectionCategory() const +{ + return QCP::iSelectItems; +} + + +/*! \file */ + + + +/*! \mainpage %QCustomPlot 1.3.0-beta Documentation + + \image html qcp-doc-logo.png + + Below is a brief overview of and guide to the classes and their relations. If you are new to + QCustomPlot and just want to start using it, it's recommended to look at the tutorials and + examples at + + http://www.qcustomplot.com/ + + This documentation is especially helpful as a reference, when you're familiar with the basic + concept of how to use %QCustomPlot and you wish to learn more about specific functionality. + See the \ref classoverview "class overview" for diagrams explaining the relationships between + the most important classes of the QCustomPlot library. + + The central widget which displays the plottables and axes on its surface is QCustomPlot. Every + QCustomPlot contains four axes by default. They can be accessed via the members \ref + QCustomPlot::xAxis "xAxis", \ref QCustomPlot::yAxis "yAxis", \ref QCustomPlot::xAxis2 "xAxis2" + and \ref QCustomPlot::yAxis2 "yAxis2", and are of type QCPAxis. QCustomPlot supports an arbitrary + number of axes and axis rects, see the documentation of QCPAxisRect for details. + + \section mainpage-plottables Plottables + + \a Plottables are classes that display any kind of data inside the QCustomPlot. They all derive + from QCPAbstractPlottable. For example, the QCPGraph class is a plottable that displays a graph + inside the plot with different line styles, scatter styles, filling etc. + + Since plotting graphs is such a dominant use case, QCustomPlot has a special interface for working + with QCPGraph plottables, that makes it very easy to handle them:\n + You create a new graph with QCustomPlot::addGraph and access them with QCustomPlot::graph. + + For all other plottables, you need to use the normal plottable interface:\n + First, you create an instance of the plottable you want, e.g. + \code + QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);\endcode + add it to the customPlot: + \code + customPlot->addPlottable(newCurve);\endcode + and then modify the properties of the newly created plottable via the newCurve pointer. + + Plottables (including graphs) can be retrieved via QCustomPlot::plottable. Since the return type + of that function is the abstract base class of all plottables, QCPAbstractPlottable, you will + probably want to qobject_cast the returned pointer to the respective plottable subclass. (As + usual, if the cast returns zero, the plottable wasn't of that specific subclass.) + + All further interfacing with plottables (e.g how to set data) is specific to the plottable type. + See the documentations of the subclasses: QCPGraph, QCPCurve, QCPBars, QCPStatisticalBox, + QCPColorMap, QCPFinancial. + + \section mainpage-axes Controlling the Axes + + As mentioned, QCustomPlot has four axes by default: \a xAxis (bottom), \a yAxis (left), \a xAxis2 + (top), \a yAxis2 (right). + + Their range is handled by the simple QCPRange class. You can set the range with the + QCPAxis::setRange function. By default, the axes represent a linear scale. To set a logarithmic + scale, set \ref QCPAxis::setScaleType to \ref QCPAxis::stLogarithmic. The logarithm base can be set freely + with \ref QCPAxis::setScaleLogBase. + + By default, an axis automatically creates and labels ticks in a sensible manner. See the + following functions for tick manipulation:\n QCPAxis::setTicks, QCPAxis::setAutoTicks, + QCPAxis::setAutoTickCount, QCPAxis::setAutoTickStep, QCPAxis::setTickLabels, + QCPAxis::setTickLabelType, QCPAxis::setTickLabelRotation, QCPAxis::setTickStep, + QCPAxis::setTickLength,... + + Each axis can be given an axis label (e.g. "Voltage (mV)") with QCPAxis::setLabel. + + The distance of an axis backbone to the respective viewport border is called its margin. + Normally, the margins are calculated automatically. To change this, set + \ref QCPAxisRect::setAutoMargins to exclude the respective margin sides, set the margins manually with + \ref QCPAxisRect::setMargins. The main axis rect can be reached with \ref QCustomPlot::axisRect(). + + \section mainpage-legend Plot Legend + + Every QCustomPlot has one QCPLegend (as \ref QCustomPlot::legend) by default. A legend is a small + layout element inside the plot which lists the plottables with an icon of the plottable + line/symbol and a name (QCPAbstractPlottable::setName). Plottables can be added and removed from + the main legend via \ref QCPAbstractPlottable::addToLegend and \ref + QCPAbstractPlottable::removeFromLegend. By default, adding a plottable to QCustomPlot + automatically adds it to the legend, too. This behaviour can be modified with the + QCustomPlot::setAutoAddPlottableToLegend property. + + The QCPLegend provides an interface to access, add and remove legend items directly, too. See + QCPLegend::item, QCPLegend::itemWithPlottable, QCPLegend::addItem, QCPLegend::removeItem for + example. + + Multiple legends are supported via the \link thelayoutsystem layout system\endlink (as a + QCPLegend simply is a normal layout element). + + \section mainpage-userinteraction User Interactions + + QCustomPlot supports dragging axis ranges with the mouse (\ref + QCPAxisRect::setRangeDrag), zooming axis ranges with the mouse wheel (\ref + QCPAxisRect::setRangeZoom) and a complete selection mechanism. + + The availability of these interactions is controlled with \ref QCustomPlot::setInteractions. For + details about the interaction system, see the documentation there. + + Further, QCustomPlot always emits corresponding signals, when objects are clicked or + doubleClicked. See \ref QCustomPlot::plottableClick, \ref QCustomPlot::plottableDoubleClick + and \ref QCustomPlot::axisClick for example. + + \section mainpage-items Items + + Apart from plottables there is another category of plot objects that are important: Items. The + base class of all items is QCPAbstractItem. An item sets itself apart from plottables in that + it's not necessarily bound to any axes. This means it may also be positioned in absolute pixel + coordinates or placed at a relative position on an axis rect. Further, it usually doesn't + represent data directly, but acts as decoration, emphasis, description etc. + + Multiple items can be arranged in a parent-child-hierarchy allowing for dynamical behaviour. For + example, you could place the head of an arrow at a fixed plot coordinate, so it always points to + some important area in the plot. The tail of the arrow can be anchored to a text item which + always resides in the top center of the axis rect, independent of where the user drags the axis + ranges. This way the arrow stretches and turns so it always points from the label to the + specified plot coordinate, without any further code necessary. + + For a more detailed introduction, see the QCPAbstractItem documentation, and from there the + documentations of the individual built-in items, to find out how to use them. + + \section mainpage-layoutelements Layout elements and layouts + + QCustomPlot uses an internal layout system to provide dynamic sizing and positioning of objects like + the axis rect(s), legends and the plot title. They are all based on \ref QCPLayoutElement and are arranged by + placing them inside a \ref QCPLayout. + + Details on this topic are given on the dedicated page about \link thelayoutsystem the layout system\endlink. + + \section mainpage-performancetweaks Performance Tweaks + + Although QCustomPlot is quite fast, some features like translucent fills, antialiasing and thick + lines can cause a significant slow down. If you notice this in your application, here are some + thoughts on how to increase performance. By far the most time is spent in the drawing functions, + specifically the drawing of graphs. For maximum performance, consider the following (most + recommended/effective measures first): + + \li use Qt 4.8.0 and up. Performance has doubled or tripled with respect to Qt 4.7.4. However + QPainter was broken and drawing pixel precise things, e.g. scatters, isn't possible with Qt >= + 4.8.0. So it's a performance vs. plot quality tradeoff when switching to Qt 4.8. + \li To increase responsiveness during dragging, consider setting \ref QCustomPlot::setNoAntialiasingOnDrag to true. + \li On X11 (GNU/Linux), avoid the slow native drawing system, use raster by supplying + "-graphicssystem raster" as command line argument or calling QApplication::setGraphicsSystem("raster") + before creating the QApplication object. (Only available for Qt versions before 5.0) + \li On all operating systems, use OpenGL hardware acceleration by supplying "-graphicssystem + opengl" as command line argument or calling QApplication::setGraphicsSystem("opengl") (Only + available for Qt versions before 5.0). If OpenGL is available, this will slightly decrease the + quality of antialiasing, but extremely increase performance especially with alpha + (semi-transparent) fills, much antialiasing and a large QCustomPlot drawing surface. Note + however, that the maximum frame rate might be constrained by the vertical sync frequency of your + monitor (VSync can be disabled in the graphics card driver configuration). So for simple plots + (where the potential framerate is far above 60 frames per second), OpenGL acceleration might + achieve numerically lower frame rates than the other graphics systems, because they are not + capped at the VSync frequency. + \li Avoid any kind of alpha (transparency), especially in fills + \li Avoid lines with a pen width greater than one + \li Avoid any kind of antialiasing, especially in graph lines (see \ref QCustomPlot::setNotAntialiasedElements) + \li Avoid repeatedly setting the complete data set with \ref QCPGraph::setData. Use \ref QCPGraph::addData instead, if most + data points stay unchanged, e.g. in a running measurement. + \li Set the \a copy parameter of the setData functions to false, so only pointers get + transferred. (Relevant only if preparing data maps with a large number of points, i.e. over 10000) + + \section mainpage-flags Preprocessor Define Flags + + QCustomPlot understands some preprocessor defines that are useful for debugging and compilation: +
+
\c QCUSTOMPLOT_COMPILE_LIBRARY +
Define this flag when you compile QCustomPlot as a shared library (.so/.dll) +
\c QCUSTOMPLOT_USE_LIBRARY +
Define this flag before including the header, when using QCustomPlot as a shared library +
\c QCUSTOMPLOT_CHECK_DATA +
If this flag is defined, the QCustomPlot plottables will perform data validity checks on every redraw. + This means they will give qDebug output when you plot \e inf or \e nan values, they will not + fix your data. +
+ +*/ + +/*! \page classoverview Class Overview + + The following diagrams may help to gain a deeper understanding of the relationships between classes that make up + the QCustomPlot library. The diagrams are not exhaustive, so only the classes deemed most relevant are shown. + + \section classoverview-relations Class Relationship Diagram + \image html RelationOverview.png "Overview of most important classes and their relations" + \section classoverview-inheritance Class Inheritance Tree + \image html InheritanceOverview.png "Inheritance tree of most important classes" + +*/ + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCustomPlot +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCustomPlot + + \brief The central class of the library. This is the QWidget which displays the plot and + interacts with the user. + + For tutorials on how to use QCustomPlot, see the website\n + http://www.qcustomplot.com/ +*/ + +/* start of documentation of inline functions */ + +/*! \fn QRect QCustomPlot::viewport() const + + Returns the viewport rect of this QCustomPlot instance. The viewport is the area the plot is + drawn in, all mechanisms, e.g. margin caluclation take the viewport to be the outer border of the + plot. The viewport normally is the rect() of the QCustomPlot widget, i.e. a rect with top left + (0, 0) and size of the QCustomPlot widget. + + Don't confuse the viewport with the axis rect (QCustomPlot::axisRect). An axis rect is typically + an area enclosed by four axes, where the graphs/plottables are drawn in. The viewport is larger + and contains also the axes themselves, their tick numbers, their labels, the plot title etc. + + Only when saving to a file (see \ref savePng, \ref savePdf etc.) the viewport is temporarily + modified to allow saving plots with sizes independent of the current widget size. +*/ + +/*! \fn QCPLayoutGrid *QCustomPlot::plotLayout() const + + Returns the top level layout of this QCustomPlot instance. It is a \ref QCPLayoutGrid, initially containing just + one cell with the main QCPAxisRect inside. +*/ + +/* end of documentation of inline functions */ +/* start of documentation of signals */ + +/*! \fn void QCustomPlot::mouseDoubleClick(QMouseEvent *event) + + This signal is emitted when the QCustomPlot receives a mouse double click event. +*/ + +/*! \fn void QCustomPlot::mousePress(QMouseEvent *event) + + This signal is emitted when the QCustomPlot receives a mouse press event. + + It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot + connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref + QCPAxisRect::setRangeDragAxes. +*/ + +/*! \fn void QCustomPlot::mouseMove(QMouseEvent *event) + + This signal is emitted when the QCustomPlot receives a mouse move event. + + It is emitted before QCustomPlot handles any other mechanism like range dragging. So a slot + connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeDrag or \ref + QCPAxisRect::setRangeDragAxes. + + \warning It is discouraged to change the drag-axes with \ref QCPAxisRect::setRangeDragAxes here, + because the dragging starting point was saved the moment the mouse was pressed. Thus it only has + a meaning for the range drag axes that were set at that moment. If you want to change the drag + axes, consider doing this in the \ref mousePress signal instead. +*/ + +/*! \fn void QCustomPlot::mouseRelease(QMouseEvent *event) + + This signal is emitted when the QCustomPlot receives a mouse release event. + + It is emitted before QCustomPlot handles any other mechanisms like object selection. So a + slot connected to this signal can still influence the behaviour e.g. with \ref setInteractions or + \ref QCPAbstractPlottable::setSelectable. +*/ + +/*! \fn void QCustomPlot::mouseWheel(QMouseEvent *event) + + This signal is emitted when the QCustomPlot receives a mouse wheel event. + + It is emitted before QCustomPlot handles any other mechanisms like range zooming. So a slot + connected to this signal can still influence the behaviour e.g. with \ref QCPAxisRect::setRangeZoom, \ref + QCPAxisRect::setRangeZoomAxes or \ref QCPAxisRect::setRangeZoomFactor. +*/ + +/*! \fn void QCustomPlot::plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event) + + This signal is emitted when a plottable is clicked. + + \a event is the mouse event that caused the click and \a plottable is the plottable that received + the click. + + \see plottableDoubleClick +*/ + +/*! \fn void QCustomPlot::plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event) + + This signal is emitted when a plottable is double clicked. + + \a event is the mouse event that caused the click and \a plottable is the plottable that received + the click. + + \see plottableClick +*/ + +/*! \fn void QCustomPlot::itemClick(QCPAbstractItem *item, QMouseEvent *event) + + This signal is emitted when an item is clicked. + + \a event is the mouse event that caused the click and \a item is the item that received the + click. + + \see itemDoubleClick +*/ + +/*! \fn void QCustomPlot::itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event) + + This signal is emitted when an item is double clicked. + + \a event is the mouse event that caused the click and \a item is the item that received the + click. + + \see itemClick +*/ + +/*! \fn void QCustomPlot::axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) + + This signal is emitted when an axis is clicked. + + \a event is the mouse event that caused the click, \a axis is the axis that received the click and + \a part indicates the part of the axis that was clicked. + + \see axisDoubleClick +*/ + +/*! \fn void QCustomPlot::axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event) + + This signal is emitted when an axis is double clicked. + + \a event is the mouse event that caused the click, \a axis is the axis that received the click and + \a part indicates the part of the axis that was clicked. + + \see axisClick +*/ + +/*! \fn void QCustomPlot::legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) + + This signal is emitted when a legend (item) is clicked. + + \a event is the mouse event that caused the click, \a legend is the legend that received the + click and \a item is the legend item that received the click. If only the legend and no item is + clicked, \a item is 0. This happens for a click inside the legend padding or the space between + two items. + + \see legendDoubleClick +*/ + +/*! \fn void QCustomPlot::legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event) + + This signal is emitted when a legend (item) is double clicked. + + \a event is the mouse event that caused the click, \a legend is the legend that received the + click and \a item is the legend item that received the click. If only the legend and no item is + clicked, \a item is 0. This happens for a click inside the legend padding or the space between + two items. + + \see legendClick +*/ + +/*! \fn void QCustomPlot:: titleClick(QMouseEvent *event, QCPPlotTitle *title) + + This signal is emitted when a plot title is clicked. + + \a event is the mouse event that caused the click and \a title is the plot title that received + the click. + + \see titleDoubleClick +*/ + +/*! \fn void QCustomPlot::titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title) + + This signal is emitted when a plot title is double clicked. + + \a event is the mouse event that caused the click and \a title is the plot title that received + the click. + + \see titleClick +*/ + +/*! \fn void QCustomPlot::selectionChangedByUser() + + This signal is emitted after the user has changed the selection in the QCustomPlot, e.g. by + clicking. It is not emitted when the selection state of an object has changed programmatically by + a direct call to setSelected() on an object or by calling \ref deselectAll. + + In addition to this signal, selectable objects also provide individual signals, for example + QCPAxis::selectionChanged or QCPAbstractPlottable::selectionChanged. Note that those signals are + emitted even if the selection state is changed programmatically. + + See the documentation of \ref setInteractions for details about the selection mechanism. + + \see selectedPlottables, selectedGraphs, selectedItems, selectedAxes, selectedLegends +*/ + +/*! \fn void QCustomPlot::beforeReplot() + + This signal is emitted immediately before a replot takes place (caused by a call to the slot \ref + replot). + + It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them + replot synchronously, it won't cause an infinite recursion. + + \see replot, afterReplot +*/ + +/*! \fn void QCustomPlot::afterReplot() + + This signal is emitted immediately after a replot has taken place (caused by a call to the slot \ref + replot). + + It is safe to mutually connect the replot slot with this signal on two QCustomPlots to make them + replot synchronously, it won't cause an infinite recursion. + + \see replot, beforeReplot +*/ + +/* end of documentation of signals */ +/* start of documentation of public members */ + +/*! \var QCPAxis *QCustomPlot::xAxis + + A pointer to the primary x Axis (bottom) of the main axis rect of the plot. + + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref + yAxis2) and the \ref legend. They make it very easy working with plots that only have a single + axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the + layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref + QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the + default legend is removed due to manipulation of the layout system (e.g. by removing the main + axis rect), the corresponding pointers become 0. +*/ + +/*! \var QCPAxis *QCustomPlot::yAxis + + A pointer to the primary y Axis (left) of the main axis rect of the plot. + + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref + yAxis2) and the \ref legend. They make it very easy working with plots that only have a single + axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the + layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref + QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the + default legend is removed due to manipulation of the layout system (e.g. by removing the main + axis rect), the corresponding pointers become 0. +*/ + +/*! \var QCPAxis *QCustomPlot::xAxis2 + + A pointer to the secondary x Axis (top) of the main axis rect of the plot. Secondary axes are + invisible by default. Use QCPAxis::setVisible to change this (or use \ref + QCPAxisRect::setupFullAxesBox). + + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref + yAxis2) and the \ref legend. They make it very easy working with plots that only have a single + axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the + layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref + QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the + default legend is removed due to manipulation of the layout system (e.g. by removing the main + axis rect), the corresponding pointers become 0. +*/ + +/*! \var QCPAxis *QCustomPlot::yAxis2 + + A pointer to the secondary y Axis (right) of the main axis rect of the plot. Secondary axes are + invisible by default. Use QCPAxis::setVisible to change this (or use \ref + QCPAxisRect::setupFullAxesBox). + + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref + yAxis2) and the \ref legend. They make it very easy working with plots that only have a single + axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the + layout system\endlink to add multiple axis rects or multiple axes to one side, use the \ref + QCPAxisRect::axis interface to access the new axes. If one of the four default axes or the + default legend is removed due to manipulation of the layout system (e.g. by removing the main + axis rect), the corresponding pointers become 0. +*/ + +/*! \var QCPLegend *QCustomPlot::legend + + A pointer to the default legend of the main axis rect. The legend is invisible by default. Use + QCPLegend::setVisible to change this. + + QCustomPlot offers convenient pointers to the axes (\ref xAxis, \ref yAxis, \ref xAxis2, \ref + yAxis2) and the \ref legend. They make it very easy working with plots that only have a single + axis rect and at most one axis at each axis rect side. If you use \link thelayoutsystem the + layout system\endlink to add multiple legends to the plot, use the layout system interface to + access the new legend. For example, legends can be placed inside an axis rect's \ref + QCPAxisRect::insetLayout "inset layout", and must then also be accessed via the inset layout. If + the default legend is removed due to manipulation of the layout system (e.g. by removing the main + axis rect), the corresponding pointer becomes 0. +*/ + +/* end of documentation of public members */ + +/*! + Constructs a QCustomPlot and sets reasonable default values. +*/ +QCustomPlot::QCustomPlot(QWidget *parent) : + QWidget(parent), + xAxis(0), + yAxis(0), + xAxis2(0), + yAxis2(0), + legend(0), + mPlotLayout(0), + mAutoAddPlottableToLegend(true), + mAntialiasedElements(QCP::aeNone), + mNotAntialiasedElements(QCP::aeNone), + mInteractions(0), + mSelectionTolerance(8), + mNoAntialiasingOnDrag(false), + mBackgroundBrush(Qt::white, Qt::SolidPattern), + mBackgroundScaled(true), + mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), + mCurrentLayer(0), + mPlottingHints(QCP::phCacheLabels|QCP::phForceRepaint), + mMultiSelectModifier(Qt::ControlModifier), + mPaintBuffer(size()), + mMouseEventElement(0), + mReplotting(false) +{ + setAttribute(Qt::WA_NoMousePropagation); + setAttribute(Qt::WA_OpaquePaintEvent); + setMouseTracking(true); + QLocale currentLocale = locale(); + currentLocale.setNumberOptions(QLocale::OmitGroupSeparator); + setLocale(currentLocale); + + // create initial layers: + mLayers.append(new QCPLayer(this, "background")); + mLayers.append(new QCPLayer(this, "grid")); + mLayers.append(new QCPLayer(this, "main")); + mLayers.append(new QCPLayer(this, "axes")); + mLayers.append(new QCPLayer(this, "legend")); + updateLayerIndices(); + setCurrentLayer("main"); + + // create initial layout, axis rect and legend: + mPlotLayout = new QCPLayoutGrid; + mPlotLayout->initializeParentPlot(this); + mPlotLayout->setParent(this); // important because if parent is QWidget, QCPLayout::sizeConstraintsChanged will call QWidget::updateGeometry + mPlotLayout->setLayer("main"); + QCPAxisRect *defaultAxisRect = new QCPAxisRect(this, true); + mPlotLayout->addElement(0, 0, defaultAxisRect); + xAxis = defaultAxisRect->axis(QCPAxis::atBottom); + yAxis = defaultAxisRect->axis(QCPAxis::atLeft); + xAxis2 = defaultAxisRect->axis(QCPAxis::atTop); + yAxis2 = defaultAxisRect->axis(QCPAxis::atRight); + legend = new QCPLegend; + legend->setVisible(false); + defaultAxisRect->insetLayout()->addElement(legend, Qt::AlignRight|Qt::AlignTop); + defaultAxisRect->insetLayout()->setMargins(QMargins(12, 12, 12, 12)); + + defaultAxisRect->setLayer("background"); + xAxis->setLayer("axes"); + yAxis->setLayer("axes"); + xAxis2->setLayer("axes"); + yAxis2->setLayer("axes"); + xAxis->grid()->setLayer("grid"); + yAxis->grid()->setLayer("grid"); + xAxis2->grid()->setLayer("grid"); + yAxis2->grid()->setLayer("grid"); + legend->setLayer("legend"); + + setViewport(rect()); // needs to be called after mPlotLayout has been created + + replot(); +} + +QCustomPlot::~QCustomPlot() +{ + try + { + + clearPlottables(); + clearItems(); + + if (mPlotLayout) + { + delete mPlotLayout; + mPlotLayout = 0; + } + + mCurrentLayer = 0; + qDeleteAll(mLayers); // don't use removeLayer, because it would prevent the last layer to be removed + mLayers.clear(); + } + catch(std::exception& e) + { + } +} + +/*! + Sets which elements are forcibly drawn antialiased as an \a or combination of QCP::AntialiasedElement. + + This overrides the antialiasing settings for whole element groups, normally controlled with the + \a setAntialiasing function on the individual elements. If an element is neither specified in + \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on + each individual element instance is used. + + For example, if \a antialiasedElements contains \ref QCP::aePlottables, all plottables will be + drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set + to. + + if an element in \a antialiasedElements is already set in \ref setNotAntialiasedElements, it is + removed from there. + + \see setNotAntialiasedElements +*/ +void QCustomPlot::setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements) +{ + mAntialiasedElements = antialiasedElements; + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) + mNotAntialiasedElements |= ~mAntialiasedElements; +} + +/*! + Sets whether the specified \a antialiasedElement is forcibly drawn antialiased. + + See \ref setAntialiasedElements for details. + + \see setNotAntialiasedElement +*/ +void QCustomPlot::setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled) +{ + if (!enabled && mAntialiasedElements.testFlag(antialiasedElement)) + mAntialiasedElements &= ~antialiasedElement; + else if (enabled && !mAntialiasedElements.testFlag(antialiasedElement)) + mAntialiasedElements |= antialiasedElement; + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) + mNotAntialiasedElements |= ~mAntialiasedElements; +} + +/*! + Sets which elements are forcibly drawn not antialiased as an \a or combination of + QCP::AntialiasedElement. + + This overrides the antialiasing settings for whole element groups, normally controlled with the + \a setAntialiasing function on the individual elements. If an element is neither specified in + \ref setAntialiasedElements nor in \ref setNotAntialiasedElements, the antialiasing setting on + each individual element instance is used. + + For example, if \a notAntialiasedElements contains \ref QCP::aePlottables, no plottables will be + drawn antialiased, no matter what the specific QCPAbstractPlottable::setAntialiased value was set + to. + + if an element in \a notAntialiasedElements is already set in \ref setAntialiasedElements, it is + removed from there. + + \see setAntialiasedElements +*/ +void QCustomPlot::setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements) +{ + mNotAntialiasedElements = notAntialiasedElements; + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) + mAntialiasedElements |= ~mNotAntialiasedElements; +} + +/*! + Sets whether the specified \a notAntialiasedElement is forcibly drawn not antialiased. + + See \ref setNotAntialiasedElements for details. + + \see setAntialiasedElement +*/ +void QCustomPlot::setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled) +{ + if (!enabled && mNotAntialiasedElements.testFlag(notAntialiasedElement)) + mNotAntialiasedElements &= ~notAntialiasedElement; + else if (enabled && !mNotAntialiasedElements.testFlag(notAntialiasedElement)) + mNotAntialiasedElements |= notAntialiasedElement; + + // make sure elements aren't in mNotAntialiasedElements and mAntialiasedElements simultaneously: + if ((mNotAntialiasedElements & mAntialiasedElements) != 0) + mAntialiasedElements |= ~mNotAntialiasedElements; +} + +/*! + If set to true, adding a plottable (e.g. a graph) to the QCustomPlot automatically also adds the + plottable to the legend (QCustomPlot::legend). + + \see addPlottable, addGraph, QCPLegend::addItem +*/ +void QCustomPlot::setAutoAddPlottableToLegend(bool on) +{ + mAutoAddPlottableToLegend = on; +} + +/*! + Sets the possible interactions of this QCustomPlot as an or-combination of \ref QCP::Interaction + enums. There are the following types of interactions: + + Axis range manipulation is controlled via \ref QCP::iRangeDrag and \ref QCP::iRangeZoom. When the + respective interaction is enabled, the user may drag axes ranges and zoom with the mouse wheel. + For details how to control which axes the user may drag/zoom and in what orientations, see \ref + QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeDragAxes, + \ref QCPAxisRect::setRangeZoomAxes. + + Plottable selection is controlled by \ref QCP::iSelectPlottables. If \ref QCP::iSelectPlottables is + set, the user may select plottables (graphs, curves, bars,...) by clicking on them or in their + vicinity (\ref setSelectionTolerance). Whether the user can actually select a plottable can + further be restricted with the \ref QCPAbstractPlottable::setSelectable function on the specific + plottable. To find out whether a specific plottable is selected, call + QCPAbstractPlottable::selected(). To retrieve a list of all currently selected plottables, call + \ref selectedPlottables. If you're only interested in QCPGraphs, you may use the convenience + function \ref selectedGraphs. + + Item selection is controlled by \ref QCP::iSelectItems. If \ref QCP::iSelectItems is set, the user + may select items (QCPItemLine, QCPItemText,...) by clicking on them or in their vicinity. To find + out whether a specific item is selected, call QCPAbstractItem::selected(). To retrieve a list of + all currently selected items, call \ref selectedItems. + + Axis selection is controlled with \ref QCP::iSelectAxes. If \ref QCP::iSelectAxes is set, the user + may select parts of the axes by clicking on them. What parts exactly (e.g. Axis base line, tick + labels, axis label) are selectable can be controlled via \ref QCPAxis::setSelectableParts for + each axis. To retrieve a list of all axes that currently contain selected parts, call \ref + selectedAxes. Which parts of an axis are selected, can be retrieved with QCPAxis::selectedParts(). + + Legend selection is controlled with \ref QCP::iSelectLegend. If this is set, the user may + select the legend itself or individual items by clicking on them. What parts exactly are + selectable can be controlled via \ref QCPLegend::setSelectableParts. To find out whether the + legend or any of its child items are selected, check the value of QCPLegend::selectedParts. To + find out which child items are selected, call \ref QCPLegend::selectedItems. + + All other selectable elements The selection of all other selectable objects (e.g. + QCPPlotTitle, or your own layerable subclasses) is controlled with \ref QCP::iSelectOther. If set, the + user may select those objects by clicking on them. To find out which are currently selected, you + need to check their selected state explicitly. + + If the selection state has changed by user interaction, the \ref selectionChangedByUser signal is + emitted. Each selectable object additionally emits an individual selectionChanged signal whenever + their selection state has changed, i.e. not only by user interaction. + + To allow multiple objects to be selected by holding the selection modifier (\ref + setMultiSelectModifier), set the flag \ref QCP::iMultiSelect. + + \note In addition to the selection mechanism presented here, QCustomPlot always emits + corresponding signals, when an object is clicked or double clicked. see \ref plottableClick and + \ref plottableDoubleClick for example. + + \see setInteraction, setSelectionTolerance +*/ +void QCustomPlot::setInteractions(const QCP::Interactions &interactions) +{ + mInteractions = interactions; +} + +/*! + Sets the single \a interaction of this QCustomPlot to \a enabled. + + For details about the interaction system, see \ref setInteractions. + + \see setInteractions +*/ +void QCustomPlot::setInteraction(const QCP::Interaction &interaction, bool enabled) +{ + if (!enabled && mInteractions.testFlag(interaction)) + mInteractions &= ~interaction; + else if (enabled && !mInteractions.testFlag(interaction)) + mInteractions |= interaction; +} + +/*! + Sets the tolerance that is used to decide whether a click selects an object (e.g. a plottable) or + not. + + If the user clicks in the vicinity of the line of e.g. a QCPGraph, it's only regarded as a + potential selection when the minimum distance between the click position and the graph line is + smaller than \a pixels. Objects that are defined by an area (e.g. QCPBars) only react to clicks + directly inside the area and ignore this selection tolerance. In other words, it only has meaning + for parts of objects that are too thin to exactly hit with a click and thus need such a + tolerance. + + \see setInteractions, QCPLayerable::selectTest +*/ +void QCustomPlot::setSelectionTolerance(int pixels) +{ + mSelectionTolerance = pixels; +} + +/*! + Sets whether antialiasing is disabled for this QCustomPlot while the user is dragging axes + ranges. If many objects, especially plottables, are drawn antialiased, this greatly improves + performance during dragging. Thus it creates a more responsive user experience. As soon as the + user stops dragging, the last replot is done with normal antialiasing, to restore high image + quality. + + \see setAntialiasedElements, setNotAntialiasedElements +*/ +void QCustomPlot::setNoAntialiasingOnDrag(bool enabled) +{ + mNoAntialiasingOnDrag = enabled; +} + +/*! + Sets the plotting hints for this QCustomPlot instance as an \a or combination of QCP::PlottingHint. + + \see setPlottingHint +*/ +void QCustomPlot::setPlottingHints(const QCP::PlottingHints &hints) +{ + mPlottingHints = hints; +} + +/*! + Sets the specified plotting \a hint to \a enabled. + + \see setPlottingHints +*/ +void QCustomPlot::setPlottingHint(QCP::PlottingHint hint, bool enabled) +{ + QCP::PlottingHints newHints = mPlottingHints; + if (!enabled) + newHints &= ~hint; + else + newHints |= hint; + + if (newHints != mPlottingHints) + setPlottingHints(newHints); +} + +/*! + Sets the keyboard modifier that will be recognized as multi-select-modifier. + + If \ref QCP::iMultiSelect is specified in \ref setInteractions, the user may select multiple objects + by clicking on them one after the other while holding down \a modifier. + + By default the multi-select-modifier is set to Qt::ControlModifier. + + \see setInteractions +*/ +void QCustomPlot::setMultiSelectModifier(Qt::KeyboardModifier modifier) +{ + mMultiSelectModifier = modifier; +} + +/*! + Sets the viewport of this QCustomPlot. The Viewport is the area that the top level layout + (QCustomPlot::plotLayout()) uses as its rect. Normally, the viewport is the entire widget rect. + + This function is used to allow arbitrary size exports with \ref toPixmap, \ref savePng, \ref + savePdf, etc. by temporarily changing the viewport size. +*/ +void QCustomPlot::setViewport(const QRect &rect) +{ + mViewport = rect; + if (mPlotLayout) + mPlotLayout->setOuterRect(mViewport); +} + +/*! + Sets \a pm as the viewport background pixmap (see \ref setViewport). The pixmap is always drawn + below all other objects in the plot. + + For cases where the provided pixmap doesn't have the same size as the viewport, scaling can be + enabled with \ref setBackgroundScaled and the scaling mode (whether and how the aspect ratio is + preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, + consider using the overloaded version of this function. + + If a background brush was set with \ref setBackground(const QBrush &brush), the viewport will + first be filled with that brush, before drawing the background pixmap. This can be useful for + background pixmaps with translucent areas. + + \see setBackgroundScaled, setBackgroundScaledMode +*/ +void QCustomPlot::setBackground(const QPixmap &pm) +{ + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); +} + +/*! + Sets the background brush of the viewport (see \ref setViewport). + + Before drawing everything else, the background is filled with \a brush. If a background pixmap + was set with \ref setBackground(const QPixmap &pm), this brush will be used to fill the viewport + before the background pixmap is drawn. This can be useful for background pixmaps with translucent + areas. + + Set \a brush to Qt::NoBrush or Qt::Transparent to leave background transparent. This can be + useful for exporting to image formats which support transparency, e.g. \ref savePng. + + \see setBackgroundScaled, setBackgroundScaledMode +*/ +void QCustomPlot::setBackground(const QBrush &brush) +{ + mBackgroundBrush = brush; +} + +/*! \overload + + Allows setting the background pixmap of the viewport, whether it shall be scaled and how it + shall be scaled in one call. + + \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode +*/ +void QCustomPlot::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) +{ + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); + mBackgroundScaled = scaled; + mBackgroundScaledMode = mode; +} + +/*! + Sets whether the viewport background pixmap shall be scaled to fit the viewport. If \a scaled is + set to true, control whether and how the aspect ratio of the original pixmap is preserved with + \ref setBackgroundScaledMode. + + Note that the scaled version of the original pixmap is buffered, so there is no performance + penalty on replots. (Except when the viewport dimensions are changed continuously.) + + \see setBackground, setBackgroundScaledMode +*/ +void QCustomPlot::setBackgroundScaled(bool scaled) +{ + mBackgroundScaled = scaled; +} + +/*! + If scaling of the viewport background pixmap is enabled (\ref setBackgroundScaled), use this + function to define whether and how the aspect ratio of the original pixmap is preserved. + + \see setBackground, setBackgroundScaled +*/ +void QCustomPlot::setBackgroundScaledMode(Qt::AspectRatioMode mode) +{ + mBackgroundScaledMode = mode; +} + +/*! + Returns the plottable with \a index. If the index is invalid, returns 0. + + There is an overloaded version of this function with no parameter which returns the last added + plottable, see QCustomPlot::plottable() + + \see plottableCount, addPlottable +*/ +QCPAbstractPlottable *QCustomPlot::plottable(int index) +{ + if (index >= 0 && index < mPlottables.size()) + { + return mPlottables.at(index); + } else + { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } +} + +/*! \overload + + Returns the last plottable that was added with \ref addPlottable. If there are no plottables in + the plot, returns 0. + + \see plottableCount, addPlottable +*/ +QCPAbstractPlottable *QCustomPlot::plottable() +{ + if (!mPlottables.isEmpty()) + { + return mPlottables.last(); + } else + return 0; +} + +/*! + Adds the specified plottable to the plot and, if \ref setAutoAddPlottableToLegend is enabled, to + the legend (QCustomPlot::legend). QCustomPlot takes ownership of the plottable. + + Returns true on success, i.e. when \a plottable isn't already in the plot and the parent plot of + \a plottable is this QCustomPlot (the latter is controlled by what axes were passed in the + plottable's constructor). + + \see plottable, plottableCount, removePlottable, clearPlottables +*/ +bool QCustomPlot::addPlottable(QCPAbstractPlottable *plottable) +{ + if (mPlottables.contains(plottable)) + { + qDebug() << Q_FUNC_INFO << "plottable already added to this QCustomPlot:" << reinterpret_cast(plottable); + return false; + } + if (plottable->parentPlot() != this) + { + qDebug() << Q_FUNC_INFO << "plottable not created with this QCustomPlot as parent:" << reinterpret_cast(plottable); + return false; + } + + mPlottables.append(plottable); + // possibly add plottable to legend: + if (mAutoAddPlottableToLegend) + plottable->addToLegend(); + // special handling for QCPGraphs to maintain the simple graph interface: + if (QCPGraph *graph = qobject_cast(plottable)) + mGraphs.append(graph); + if (!plottable->layer()) // usually the layer is already set in the constructor of the plottable (via QCPLayerable constructor) + plottable->setLayer(currentLayer()); + return true; +} + +/*! + Removes the specified plottable from the plot and, if necessary, from the legend (QCustomPlot::legend). + + Returns true on success. + + \see addPlottable, clearPlottables +*/ +bool QCustomPlot::removePlottable(QCPAbstractPlottable *plottable) +{ + if (!mPlottables.contains(plottable)) + { + qDebug() << Q_FUNC_INFO << "plottable not in list:" << reinterpret_cast(plottable); + return false; + } + + // remove plottable from legend: + plottable->removeFromLegend(); + // special handling for QCPGraphs to maintain the simple graph interface: + if (QCPGraph *graph = qobject_cast(plottable)) + mGraphs.removeOne(graph); + // remove plottable: + delete plottable; + mPlottables.removeOne(plottable); + return true; +} + +/*! \overload + + Removes the plottable by its \a index. +*/ +bool QCustomPlot::removePlottable(int index) +{ + if (index >= 0 && index < mPlottables.size()) + return removePlottable(mPlottables[index]); + else + { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return false; + } +} + +/*! + Removes all plottables from the plot (and the QCustomPlot::legend, if necessary). + + Returns the number of plottables removed. + + \see removePlottable +*/ +int QCustomPlot::clearPlottables() +{ + int c = mPlottables.size(); + for (int i=c-1; i >= 0; --i) + removePlottable(mPlottables[i]); + return c; +} + +/*! + Returns the number of currently existing plottables in the plot + + \see plottable, addPlottable +*/ +int QCustomPlot::plottableCount() const +{ + return mPlottables.size(); +} + +/*! + Returns a list of the selected plottables. If no plottables are currently selected, the list is empty. + + There is a convenience function if you're only interested in selected graphs, see \ref selectedGraphs. + + \see setInteractions, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected +*/ +QList QCustomPlot::selectedPlottables() const +{ + QList result; + foreach (QCPAbstractPlottable *plottable, mPlottables) + { + if (plottable->selected()) + result.append(plottable); + } + return result; +} + +/*! + Returns the plottable at the pixel position \a pos. Plottables that only consist of single lines + (like graphs) have a tolerance band around them, see \ref setSelectionTolerance. If multiple + plottables come into consideration, the one closest to \a pos is returned. + + If \a onlySelectable is true, only plottables that are selectable + (QCPAbstractPlottable::setSelectable) are considered. + + If there is no plottable at \a pos, the return value is 0. + + \see itemAt, layoutElementAt +*/ +QCPAbstractPlottable *QCustomPlot::plottableAt(const QPointF &pos, bool onlySelectable) const +{ + QCPAbstractPlottable *resultPlottable = 0; + double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value + + foreach (QCPAbstractPlottable *plottable, mPlottables) + { + if (onlySelectable && !plottable->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPabstractPlottable::selectable + continue; + if ((plottable->keyAxis()->axisRect()->rect() & plottable->valueAxis()->axisRect()->rect()).contains(pos.toPoint())) // only consider clicks inside the rect that is spanned by the plottable's key/value axes + { + double currentDistance = plottable->selectTest(pos, false); + if (currentDistance >= 0 && currentDistance < resultDistance) + { + resultPlottable = plottable; + resultDistance = currentDistance; + } + } + } + + return resultPlottable; +} + +/*! + Returns whether this QCustomPlot instance contains the \a plottable. + + \see addPlottable +*/ +bool QCustomPlot::hasPlottable(QCPAbstractPlottable *plottable) const +{ + return mPlottables.contains(plottable); +} + +/*! + Returns the graph with \a index. If the index is invalid, returns 0. + + There is an overloaded version of this function with no parameter which returns the last created + graph, see QCustomPlot::graph() + + \see graphCount, addGraph +*/ +QCPGraph *QCustomPlot::graph(int index) const +{ + if (index >= 0 && index < mGraphs.size()) + { + return mGraphs.at(index); + } else + { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } +} + +/*! \overload + + Returns the last graph, that was created with \ref addGraph. If there are no graphs in the plot, + returns 0. + + \see graphCount, addGraph +*/ +QCPGraph *QCustomPlot::graph() const +{ + if (!mGraphs.isEmpty()) + { + return mGraphs.last(); + } else + return 0; +} + +/*! + Creates a new graph inside the plot. If \a keyAxis and \a valueAxis are left unspecified (0), the + bottom (xAxis) is used as key and the left (yAxis) is used as value axis. If specified, \a + keyAxis and \a valueAxis must reside in this QCustomPlot. + + \a keyAxis will be used as key axis (typically "x") and \a valueAxis as value axis (typically + "y") for the graph. + + Returns a pointer to the newly created graph, or 0 if adding the graph failed. + + \see graph, graphCount, removeGraph, clearGraphs +*/ +QCPGraph *QCustomPlot::addGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) +{ + if (!keyAxis) keyAxis = xAxis; + if (!valueAxis) valueAxis = yAxis; + if (!keyAxis || !valueAxis) + { + qDebug() << Q_FUNC_INFO << "can't use default QCustomPlot xAxis or yAxis, because at least one is invalid (has been deleted)"; + return 0; + } + if (keyAxis->parentPlot() != this || valueAxis->parentPlot() != this) + { + qDebug() << Q_FUNC_INFO << "passed keyAxis or valueAxis doesn't have this QCustomPlot as parent"; + return 0; + } + + QCPGraph *newGraph = new QCPGraph(keyAxis, valueAxis); + if (addPlottable(newGraph)) + { + newGraph->setName("Graph "+QString::number(mGraphs.size())); + return newGraph; + } else + { + delete newGraph; + return 0; + } +} + +/*! + Removes the specified \a graph from the plot and, if necessary, from the QCustomPlot::legend. If + any other graphs in the plot have a channel fill set towards the removed graph, the channel fill + property of those graphs is reset to zero (no channel fill). + + Returns true on success. + + \see clearGraphs +*/ +bool QCustomPlot::removeGraph(QCPGraph *graph) +{ + return removePlottable(graph); +} + +/*! \overload + + Removes the graph by its \a index. +*/ +bool QCustomPlot::removeGraph(int index) +{ + if (index >= 0 && index < mGraphs.size()) + return removeGraph(mGraphs[index]); + else + return false; +} + +/*! + Removes all graphs from the plot (and the QCustomPlot::legend, if necessary). + + Returns the number of graphs removed. + + \see removeGraph +*/ +int QCustomPlot::clearGraphs() +{ + int c = mGraphs.size(); + for (int i=c-1; i >= 0; --i) + removeGraph(mGraphs[i]); + return c; +} + +/*! + Returns the number of currently existing graphs in the plot + + \see graph, addGraph +*/ +int QCustomPlot::graphCount() const +{ + return mGraphs.size(); +} + +/*! + Returns a list of the selected graphs. If no graphs are currently selected, the list is empty. + + If you are not only interested in selected graphs but other plottables like QCPCurve, QCPBars, + etc., use \ref selectedPlottables. + + \see setInteractions, selectedPlottables, QCPAbstractPlottable::setSelectable, QCPAbstractPlottable::setSelected +*/ +QList QCustomPlot::selectedGraphs() const +{ + QList result; + foreach (QCPGraph *graph, mGraphs) + { + if (graph->selected()) + result.append(graph); + } + return result; +} + +/*! + Returns the item with \a index. If the index is invalid, returns 0. + + There is an overloaded version of this function with no parameter which returns the last added + item, see QCustomPlot::item() + + \see itemCount, addItem +*/ +QCPAbstractItem *QCustomPlot::item(int index) const +{ + if (index >= 0 && index < mItems.size()) + { + return mItems.at(index); + } else + { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } +} + +/*! \overload + + Returns the last item, that was added with \ref addItem. If there are no items in the plot, + returns 0. + + \see itemCount, addItem +*/ +QCPAbstractItem *QCustomPlot::item() const +{ + if (!mItems.isEmpty()) + { + return mItems.last(); + } else + return 0; +} + +/*! + Adds the specified item to the plot. QCustomPlot takes ownership of the item. + + Returns true on success, i.e. when \a item wasn't already in the plot and the parent plot of \a + item is this QCustomPlot. + + \see item, itemCount, removeItem, clearItems +*/ +bool QCustomPlot::addItem(QCPAbstractItem *item) +{ + if (!mItems.contains(item) && item->parentPlot() == this) + { + mItems.append(item); + return true; + } else + { + qDebug() << Q_FUNC_INFO << "item either already in list or not created with this QCustomPlot as parent:" << reinterpret_cast(item); + return false; + } +} + +/*! + Removes the specified item from the plot. + + Returns true on success. + + \see addItem, clearItems +*/ +bool QCustomPlot::removeItem(QCPAbstractItem *item) +{ + if (mItems.contains(item)) + { + delete item; + mItems.removeOne(item); + return true; + } else + { + qDebug() << Q_FUNC_INFO << "item not in list:" << reinterpret_cast(item); + return false; + } +} + +/*! \overload + + Removes the item by its \a index. +*/ +bool QCustomPlot::removeItem(int index) +{ + if (index >= 0 && index < mItems.size()) + return removeItem(mItems[index]); + else + { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return false; + } +} + +/*! + Removes all items from the plot. + + Returns the number of items removed. + + \see removeItem +*/ +int QCustomPlot::clearItems() +{ + int c = mItems.size(); + for (int i=c-1; i >= 0; --i) + removeItem(mItems[i]); + return c; +} + +/*! + Returns the number of currently existing items in the plot + + \see item, addItem +*/ +int QCustomPlot::itemCount() const +{ + return mItems.size(); +} + +/*! + Returns a list of the selected items. If no items are currently selected, the list is empty. + + \see setInteractions, QCPAbstractItem::setSelectable, QCPAbstractItem::setSelected +*/ +QList QCustomPlot::selectedItems() const +{ + QList result; + foreach (QCPAbstractItem *item, mItems) + { + if (item->selected()) + result.append(item); + } + return result; +} + +/*! + Returns the item at the pixel position \a pos. Items that only consist of single lines (e.g. \ref + QCPItemLine or \ref QCPItemCurve) have a tolerance band around them, see \ref + setSelectionTolerance. If multiple items come into consideration, the one closest to \a pos is + returned. + + If \a onlySelectable is true, only items that are selectable (QCPAbstractItem::setSelectable) are + considered. + + If there is no item at \a pos, the return value is 0. + + \see plottableAt, layoutElementAt +*/ +QCPAbstractItem *QCustomPlot::itemAt(const QPointF &pos, bool onlySelectable) const +{ + QCPAbstractItem *resultItem = 0; + double resultDistance = mSelectionTolerance; // only regard clicks with distances smaller than mSelectionTolerance as selections, so initialize with that value + + foreach (QCPAbstractItem *item, mItems) + { + if (onlySelectable && !item->selectable()) // we could have also passed onlySelectable to the selectTest function, but checking here is faster, because we have access to QCPAbstractItem::selectable + continue; + if (!item->clipToAxisRect() || item->clipRect().contains(pos.toPoint())) // only consider clicks inside axis cliprect of the item if actually clipped to it + { + double currentDistance = item->selectTest(pos, false); + if (currentDistance >= 0 && currentDistance < resultDistance) + { + resultItem = item; + resultDistance = currentDistance; + } + } + } + + return resultItem; +} + +/*! + Returns whether this QCustomPlot contains the \a item. + + \see addItem +*/ +bool QCustomPlot::hasItem(QCPAbstractItem *item) const +{ + return mItems.contains(item); +} + +/*! + Returns the layer with the specified \a name. If there is no layer with the specified name, 0 is + returned. + + Layer names are case-sensitive. + + \see addLayer, moveLayer, removeLayer +*/ +QCPLayer *QCustomPlot::layer(const QString &name) const +{ + foreach (QCPLayer *layer, mLayers) + { + if (layer->name() == name) + return layer; + } + return 0; +} + +/*! \overload + + Returns the layer by \a index. If the index is invalid, 0 is returned. + + \see addLayer, moveLayer, removeLayer +*/ +QCPLayer *QCustomPlot::layer(int index) const +{ + if (index >= 0 && index < mLayers.size()) + { + return mLayers.at(index); + } else + { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } +} + +/*! + Returns the layer that is set as current layer (see \ref setCurrentLayer). +*/ +QCPLayer *QCustomPlot::currentLayer() const +{ + return mCurrentLayer; +} + +/*! + Sets the layer with the specified \a name to be the current layer. All layerables (\ref + QCPLayerable), e.g. plottables and items, are created on the current layer. + + Returns true on success, i.e. if there is a layer with the specified \a name in the QCustomPlot. + + Layer names are case-sensitive. + + \see addLayer, moveLayer, removeLayer, QCPLayerable::setLayer +*/ +bool QCustomPlot::setCurrentLayer(const QString &name) +{ + if (QCPLayer *newCurrentLayer = layer(name)) + { + return setCurrentLayer(newCurrentLayer); + } else + { + qDebug() << Q_FUNC_INFO << "layer with name doesn't exist:" << name; + return false; + } +} + +/*! \overload + + Sets the provided \a layer to be the current layer. + + Returns true on success, i.e. when \a layer is a valid layer in the QCustomPlot. + + \see addLayer, moveLayer, removeLayer +*/ +bool QCustomPlot::setCurrentLayer(QCPLayer *layer) +{ + if (!mLayers.contains(layer)) + { + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + return false; + } + + mCurrentLayer = layer; + return true; +} + +/*! + Returns the number of currently existing layers in the plot + + \see layer, addLayer +*/ +int QCustomPlot::layerCount() const +{ + return mLayers.size(); +} + +/*! + Adds a new layer to this QCustomPlot instance. The new layer will have the name \a name, which + must be unique. Depending on \a insertMode, it is positioned either below or above \a otherLayer. + + Returns true on success, i.e. if there is no other layer named \a name and \a otherLayer is a + valid layer inside this QCustomPlot. + + If \a otherLayer is 0, the highest layer in the QCustomPlot will be used. + + For an explanation of what layers are in QCustomPlot, see the documentation of \ref QCPLayer. + + \see layer, moveLayer, removeLayer +*/ +bool QCustomPlot::addLayer(const QString &name, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) +{ + if (!otherLayer) + otherLayer = mLayers.last(); + if (!mLayers.contains(otherLayer)) + { + qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); + return false; + } + if (layer(name)) + { + qDebug() << Q_FUNC_INFO << "A layer exists already with the name" << name; + return false; + } + + QCPLayer *newLayer = new QCPLayer(this, name); + mLayers.insert(otherLayer->index() + (insertMode==limAbove ? 1:0), newLayer); + updateLayerIndices(); + return true; +} + +/*! + Removes the specified \a layer and returns true on success. + + All layerables (e.g. plottables and items) on the removed layer will be moved to the layer below + \a layer. If \a layer is the bottom layer, the layerables are moved to the layer above. In both + cases, the total rendering order of all layerables in the QCustomPlot is preserved. + + If \a layer is the current layer (\ref setCurrentLayer), the layer below (or above, if bottom + layer) becomes the new current layer. + + It is not possible to remove the last layer of the plot. + + \see layer, addLayer, moveLayer +*/ +bool QCustomPlot::removeLayer(QCPLayer *layer) +{ + if (!mLayers.contains(layer)) + { + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + return false; + } + if (mLayers.size() < 2) + { + qDebug() << Q_FUNC_INFO << "can't remove last layer"; + return false; + } + + // append all children of this layer to layer below (if this is lowest layer, prepend to layer above) + int removedIndex = layer->index(); + bool isFirstLayer = removedIndex==0; + QCPLayer *targetLayer = isFirstLayer ? mLayers.at(removedIndex+1) : mLayers.at(removedIndex-1); + QList children = layer->children(); + if (isFirstLayer) // prepend in reverse order (so order relative to each other stays the same) + { + for (int i=children.size()-1; i>=0; --i) + children.at(i)->moveToLayer(targetLayer, true); + } else // append normally + { + for (int i=0; imoveToLayer(targetLayer, false); + } + // if removed layer is current layer, change current layer to layer below/above: + if (layer == mCurrentLayer) + setCurrentLayer(targetLayer); + // remove layer: + delete layer; + mLayers.removeOne(layer); + updateLayerIndices(); + return true; +} + +/*! + Moves the specified \a layer either above or below \a otherLayer. Whether it's placed above or + below is controlled with \a insertMode. + + Returns true on success, i.e. when both \a layer and \a otherLayer are valid layers in the + QCustomPlot. + + \see layer, addLayer, moveLayer +*/ +bool QCustomPlot::moveLayer(QCPLayer *layer, QCPLayer *otherLayer, QCustomPlot::LayerInsertMode insertMode) +{ + if (!mLayers.contains(layer)) + { + qDebug() << Q_FUNC_INFO << "layer not a layer of this QCustomPlot:" << reinterpret_cast(layer); + return false; + } + if (!mLayers.contains(otherLayer)) + { + qDebug() << Q_FUNC_INFO << "otherLayer not a layer of this QCustomPlot:" << reinterpret_cast(otherLayer); + return false; + } + + mLayers.move(layer->index(), otherLayer->index() + (insertMode==limAbove ? 1:0)); + updateLayerIndices(); + return true; +} + +/*! + Returns the number of axis rects in the plot. + + All axis rects can be accessed via QCustomPlot::axisRect(). + + Initially, only one axis rect exists in the plot. + + \see axisRect, axisRects +*/ +int QCustomPlot::axisRectCount() const +{ + return axisRects().size(); +} + +/*! + Returns the axis rect with \a index. + + Initially, only one axis rect (with index 0) exists in the plot. If multiple axis rects were + added, all of them may be accessed with this function in a linear fashion (even when they are + nested in a layout hierarchy or inside other axis rects via QCPAxisRect::insetLayout). + + \see axisRectCount, axisRects +*/ +QCPAxisRect *QCustomPlot::axisRect(int index) const +{ + const QList rectList = axisRects(); + if (index >= 0 && index < rectList.size()) + { + return rectList.at(index); + } else + { + qDebug() << Q_FUNC_INFO << "invalid axis rect index" << index; + return 0; + } +} + +/*! + Returns all axis rects in the plot. + + \see axisRectCount, axisRect +*/ +QList QCustomPlot::axisRects() const +{ + QList result; + QStack elementStack; + if (mPlotLayout) + elementStack.push(mPlotLayout); + + while (!elementStack.isEmpty()) + { + foreach (QCPLayoutElement *element, elementStack.pop()->elements(false)) + { + if (element) + { + elementStack.push(element); + if (QCPAxisRect *ar = qobject_cast(element)) + result.append(ar); + } + } + } + + return result; +} + +/*! + Returns the layout element at pixel position \a pos. If there is no element at that position, + returns 0. + + Only visible elements are used. If \ref QCPLayoutElement::setVisible on the element itself or on + any of its parent elements is set to false, it will not be considered. + + \see itemAt, plottableAt +*/ +QCPLayoutElement *QCustomPlot::layoutElementAt(const QPointF &pos) const +{ + QCPLayoutElement *currentElement = mPlotLayout; + bool searchSubElements = true; + while (searchSubElements && currentElement) + { + searchSubElements = false; + foreach (QCPLayoutElement *subElement, currentElement->elements(false)) + { + if (subElement && subElement->realVisibility() && subElement->selectTest(pos, false) >= 0) + { + currentElement = subElement; + searchSubElements = true; + break; + } + } + } + return currentElement; +} + +/*! + Returns the axes that currently have selected parts, i.e. whose selection state is not \ref + QCPAxis::spNone. + + \see selectedPlottables, selectedLegends, setInteractions, QCPAxis::setSelectedParts, + QCPAxis::setSelectableParts +*/ +QList QCustomPlot::selectedAxes() const +{ + QList result, allAxes; + foreach (QCPAxisRect *rect, axisRects()) + allAxes << rect->axes(); + + foreach (QCPAxis *axis, allAxes) + { + if (axis->selectedParts() != QCPAxis::spNone) + result.append(axis); + } + + return result; +} + +/*! + Returns the legends that currently have selected parts, i.e. whose selection state is not \ref + QCPLegend::spNone. + + \see selectedPlottables, selectedAxes, setInteractions, QCPLegend::setSelectedParts, + QCPLegend::setSelectableParts, QCPLegend::selectedItems +*/ +QList QCustomPlot::selectedLegends() const +{ + QList result; + + QStack elementStack; + if (mPlotLayout) + elementStack.push(mPlotLayout); + + while (!elementStack.isEmpty()) + { + foreach (QCPLayoutElement *subElement, elementStack.pop()->elements(false)) + { + if (subElement) + { + elementStack.push(subElement); + if (QCPLegend *leg = qobject_cast(subElement)) + { + if (leg->selectedParts() != QCPLegend::spNone) + result.append(leg); + } + } + } + } + + return result; +} + +/*! + Deselects all layerables (plottables, items, axes, legends,...) of the QCustomPlot. + + Since calling this function is not a user interaction, this does not emit the \ref + selectionChangedByUser signal. The individual selectionChanged signals are emitted though, if the + objects were previously selected. + + \see setInteractions, selectedPlottables, selectedItems, selectedAxes, selectedLegends +*/ +void QCustomPlot::deselectAll() +{ + foreach (QCPLayer *layer, mLayers) + { + foreach (QCPLayerable *layerable, layer->children()) + layerable->deselectEvent(0); + } +} + +/*! + Causes a complete replot into the internal buffer. Finally, update() is called, to redraw the + buffer on the QCustomPlot widget surface. This is the method that must be called to make changes, + for example on the axis ranges or data points of graphs, visible. + + Under a few circumstances, QCustomPlot causes a replot by itself. Those are resize events of the + QCustomPlot widget and user interactions (object selection and range dragging/zooming). + + Before the replot happens, the signal \ref beforeReplot is emitted. After the replot, \ref + afterReplot is emitted. It is safe to mutually connect the replot slot with any of those two + signals on two QCustomPlots to make them replot synchronously, it won't cause an infinite + recursion. +*/ +void QCustomPlot::replot(QCustomPlot::RefreshPriority refreshPriority) +{ + if (mReplotting) // incase signals loop back to replot slot + return; + mReplotting = true; + emit beforeReplot(); + + mPaintBuffer.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); + QCPPainter painter; + painter.begin(&mPaintBuffer); + if (painter.isActive()) + { + painter.setRenderHint(QPainter::HighQualityAntialiasing); // to make Antialiasing look good if using the OpenGL graphicssystem + if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) + painter.fillRect(mViewport, mBackgroundBrush); + draw(&painter); + painter.end(); + if ((refreshPriority == rpHint && mPlottingHints.testFlag(QCP::phForceRepaint)) || refreshPriority==rpImmediate) + repaint(); + else + update(); + } else // might happen if QCustomPlot has width or height zero + qDebug() << Q_FUNC_INFO << "Couldn't activate painter on buffer. This usually happens because QCustomPlot has width or height zero."; + + emit afterReplot(); + mReplotting = false; +} + +/*! + Rescales the axes such that all plottables (like graphs) in the plot are fully visible. + + if \a onlyVisiblePlottables is set to true, only the plottables that have their visibility set to true + (QCPLayerable::setVisible), will be used to rescale the axes. + + \see QCPAbstractPlottable::rescaleAxes, QCPAxis::rescale +*/ +void QCustomPlot::rescaleAxes(bool onlyVisiblePlottables) +{ + QList allAxes; + foreach (QCPAxisRect *rect, axisRects()) + allAxes << rect->axes(); + + foreach (QCPAxis *axis, allAxes) + axis->rescale(onlyVisiblePlottables); +} + +/*! + Saves a PDF with the vectorized plot to the file \a fileName. The axis ratio as well as the scale + of texts and lines will be derived from the specified \a width and \a height. This means, the + output will look like the normal on-screen output of a QCustomPlot widget with the corresponding + pixel width and height. If either \a width or \a height is zero, the exported image will have the + same dimensions as the QCustomPlot widget currently has. + + \a noCosmeticPen disables the use of cosmetic pens when drawing to the PDF file. Cosmetic pens + are pens with numerical width 0, which are always drawn as a one pixel wide line, no matter what + zoom factor is set in the PDF-Viewer. For more information about cosmetic pens, see the QPainter + and QPen documentation. + + The objects of the plot will appear in the current selection state. If you don't want any + selected objects to be painted in their selected look, deselect everything with \ref deselectAll + before calling this function. + + Returns true on success. + + \warning + \li If you plan on editing the exported PDF file with a vector graphics editor like + Inkscape, it is advised to set \a noCosmeticPen to true to avoid losing those cosmetic lines + (which might be quite many, because cosmetic pens are the default for e.g. axes and tick marks). + \li If calling this function inside the constructor of the parent of the QCustomPlot widget + (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide + explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this + function uses the current width and height of the QCustomPlot widget. However, in Qt, these + aren't defined yet inside the constructor, so you would get an image that has strange + widths/heights. + + \a pdfCreator and \a pdfTitle may be used to set the according metadata fields in the resulting + PDF file. + + \note On Android systems, this method does nothing and issues an according qDebug warning + message. This is also the case if for other reasons the define flag QT_NO_PRINTER is set. + + \see savePng, saveBmp, saveJpg, saveRastered +*/ +bool QCustomPlot::savePdf(const QString &fileName, bool noCosmeticPen, int width, int height, const QString &pdfCreator, const QString &pdfTitle) +{ + bool success = false; +#ifdef QT_NO_PRINTER + Q_UNUSED(fileName) + Q_UNUSED(noCosmeticPen) + Q_UNUSED(width) + Q_UNUSED(height) + qDebug() << Q_FUNC_INFO << "Qt was built without printer support (QT_NO_PRINTER). PDF not created."; +#else + int newWidth, newHeight; + if (width == 0 || height == 0) + { + newWidth = this->width(); + newHeight = this->height(); + } else + { + newWidth = width; + newHeight = height; + } + + QPrinter printer(QPrinter::ScreenResolution); + printer.setOutputFileName(fileName); + printer.setOutputFormat(QPrinter::PdfFormat); + printer.setColorMode(QPrinter::Color); + printer.printEngine()->setProperty(QPrintEngine::PPK_Creator, pdfCreator); + printer.printEngine()->setProperty(QPrintEngine::PPK_DocumentName, pdfTitle); + QRect oldViewport = viewport(); + setViewport(QRect(0, 0, newWidth, newHeight)); +#if QT_VERSION < QT_VERSION_CHECK(5, 3, 0) + printer.setFullPage(true); + printer.setPaperSize(viewport().size(), QPrinter::DevicePixel); +#else + QPageLayout pageLayout; + pageLayout.setMode(QPageLayout::FullPageMode); + pageLayout.setOrientation(QPageLayout::Portrait); + pageLayout.setMargins(QMarginsF(0, 0, 0, 0)); + pageLayout.setPageSize(QPageSize(viewport().size(), QPageSize::Point, QString(), QPageSize::ExactMatch)); + printer.setPageLayout(pageLayout); +#endif + QCPPainter printpainter; + if (printpainter.begin(&printer)) + { + printpainter.setMode(QCPPainter::pmVectorized); + printpainter.setMode(QCPPainter::pmNoCaching); + printpainter.setMode(QCPPainter::pmNonCosmetic, noCosmeticPen); + printpainter.setWindow(mViewport); + if (mBackgroundBrush.style() != Qt::NoBrush && + mBackgroundBrush.color() != Qt::white && + mBackgroundBrush.color() != Qt::transparent && + mBackgroundBrush.color().alpha() > 0) // draw pdf background color if not white/transparent + printpainter.fillRect(viewport(), mBackgroundBrush); + draw(&printpainter); + printpainter.end(); + success = true; + } + setViewport(oldViewport); +#endif // QT_NO_PRINTER + return success; +} + +/*! + Saves a PNG image file to \a fileName on disc. The output plot will have the dimensions \a width + and \a height in pixels. If either \a width or \a height is zero, the exported image will have + the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not + scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. + + For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an + image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, + texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full + 200*200 pixel resolution. + + If you use a high scaling factor, it is recommended to enable antialiasing for all elements via + temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows + QCustomPlot to place objects with sub-pixel accuracy. + + \warning If calling this function inside the constructor of the parent of the QCustomPlot widget + (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide + explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this + function uses the current width and height of the QCustomPlot widget. However, in Qt, these + aren't defined yet inside the constructor, so you would get an image that has strange + widths/heights. + + The objects of the plot will appear in the current selection state. If you don't want any selected + objects to be painted in their selected look, deselect everything with \ref deselectAll before calling + this function. + + If you want the PNG to have a transparent background, call \ref setBackground(const QBrush + &brush) with no brush (Qt::NoBrush) or a transparent color (Qt::transparent), before saving. + + PNG compression can be controlled with the \a quality parameter which must be between 0 and 100 or + -1 to use the default setting. + + Returns true on success. If this function fails, most likely the PNG format isn't supported by + the system, see Qt docs about QImageWriter::supportedImageFormats(). + + \see savePdf, saveBmp, saveJpg, saveRastered +*/ +bool QCustomPlot::savePng(const QString &fileName, int width, int height, double scale, int quality) +{ + return saveRastered(fileName, width, height, scale, "PNG", quality); +} + +/*! + Saves a JPG image file to \a fileName on disc. The output plot will have the dimensions \a width + and \a height in pixels. If either \a width or \a height is zero, the exported image will have + the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not + scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. + + For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an + image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, + texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full + 200*200 pixel resolution. + + If you use a high scaling factor, it is recommended to enable antialiasing for all elements via + temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows + QCustomPlot to place objects with sub-pixel accuracy. + + \warning If calling this function inside the constructor of the parent of the QCustomPlot widget + (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide + explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this + function uses the current width and height of the QCustomPlot widget. However, in Qt, these + aren't defined yet inside the constructor, so you would get an image that has strange + widths/heights. + + The objects of the plot will appear in the current selection state. If you don't want any selected + objects to be painted in their selected look, deselect everything with \ref deselectAll before calling + this function. + + JPG compression can be controlled with the \a quality parameter which must be between 0 and 100 or + -1 to use the default setting. + + Returns true on success. If this function fails, most likely the JPG format isn't supported by + the system, see Qt docs about QImageWriter::supportedImageFormats(). + + \see savePdf, savePng, saveBmp, saveRastered +*/ +bool QCustomPlot::saveJpg(const QString &fileName, int width, int height, double scale, int quality) +{ + return saveRastered(fileName, width, height, scale, "JPG", quality); +} + +/*! + Saves a BMP image file to \a fileName on disc. The output plot will have the dimensions \a width + and \a height in pixels. If either \a width or \a height is zero, the exported image will have + the same dimensions as the QCustomPlot widget currently has. Line widths and texts etc. are not + scaled up when larger widths/heights are used. If you want that effect, use the \a scale parameter. + + For example, if you set both \a width and \a height to 100 and \a scale to 2, you will end up with an + image file of size 200*200 in which all graphical elements are scaled up by factor 2 (line widths, + texts, etc.). This scaling is not done by stretching a 100*100 image, the result will have full + 200*200 pixel resolution. + + If you use a high scaling factor, it is recommended to enable antialiasing for all elements via + temporarily setting \ref QCustomPlot::setAntialiasedElements to \ref QCP::aeAll as this allows + QCustomPlot to place objects with sub-pixel accuracy. + + \warning If calling this function inside the constructor of the parent of the QCustomPlot widget + (i.e. the MainWindow constructor, if QCustomPlot is inside the MainWindow), always provide + explicit non-zero widths and heights. If you leave \a width or \a height as 0 (default), this + function uses the current width and height of the QCustomPlot widget. However, in Qt, these + aren't defined yet inside the constructor, so you would get an image that has strange + widths/heights. + + The objects of the plot will appear in the current selection state. If you don't want any selected + objects to be painted in their selected look, deselect everything with \ref deselectAll before calling + this function. + + Returns true on success. If this function fails, most likely the BMP format isn't supported by + the system, see Qt docs about QImageWriter::supportedImageFormats(). + + \see savePdf, savePng, saveJpg, saveRastered +*/ +bool QCustomPlot::saveBmp(const QString &fileName, int width, int height, double scale) +{ + return saveRastered(fileName, width, height, scale, "BMP"); +} + +/*! \internal + + Returns a minimum size hint that corresponds to the minimum size of the top level layout + (\ref plotLayout). To prevent QCustomPlot from being collapsed to size/width zero, set a minimum + size (setMinimumSize) either on the whole QCustomPlot or on any layout elements inside the plot. + This is especially important, when placed in a QLayout where other components try to take in as + much space as possible (e.g. QMdiArea). +*/ +QSize QCustomPlot::minimumSizeHint() const +{ + return mPlotLayout->minimumSizeHint(); +} + +/*! \internal + + Returns a size hint that is the same as \ref minimumSizeHint. + +*/ +QSize QCustomPlot::sizeHint() const +{ + return mPlotLayout->minimumSizeHint(); +} + +/*! \internal + + Event handler for when the QCustomPlot widget needs repainting. This does not cause a \ref replot, but + draws the internal buffer on the widget surface. +*/ +void QCustomPlot::paintEvent(QPaintEvent *event) +{ + Q_UNUSED(event); + QPainter painter(this); + painter.drawPixmap(0, 0, mPaintBuffer); +} + +/*! \internal + + Event handler for a resize of the QCustomPlot widget. Causes the internal buffer to be resized to + the new size. The viewport (which becomes the outer rect of mPlotLayout) is resized + appropriately. Finally a \ref replot is performed. +*/ +void QCustomPlot::resizeEvent(QResizeEvent *event) +{ + // resize and repaint the buffer: + mPaintBuffer = QPixmap(event->size()); + setViewport(rect()); + replot(rpQueued); // queued update is important here, to prevent painting issues in some contexts +} + +/*! \internal + + Event handler for when a double click occurs. Emits the \ref mouseDoubleClick signal, then emits + the specialized signals when certain objecs are clicked (e.g. \ref plottableDoubleClick, \ref + axisDoubleClick, etc.). Finally determines the affected layout element and forwards the event to + it. + + \see mousePressEvent, mouseReleaseEvent +*/ +void QCustomPlot::mouseDoubleClickEvent(QMouseEvent *event) +{ + emit mouseDoubleClick(event); + + QVariant details; + QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); + + // emit specialized object double click signals: + if (QCPAbstractPlottable *ap = qobject_cast(clickedLayerable)) + emit plottableDoubleClick(ap, event); + else if (QCPAxis *ax = qobject_cast(clickedLayerable)) + emit axisDoubleClick(ax, details.value(), event); + else if (QCPAbstractItem *ai = qobject_cast(clickedLayerable)) + emit itemDoubleClick(ai, event); + else if (QCPLegend *lg = qobject_cast(clickedLayerable)) + emit legendDoubleClick(lg, 0, event); + else if (QCPAbstractLegendItem *li = qobject_cast(clickedLayerable)) + emit legendDoubleClick(li->parentLegend(), li, event); + else if (QCPPlotTitle *pt = qobject_cast(clickedLayerable)) + emit titleDoubleClick(event, pt); + + // call double click event of affected layout element: + if (QCPLayoutElement *el = layoutElementAt(event->pos())) + el->mouseDoubleClickEvent(event); + + // call release event of affected layout element (as in mouseReleaseEvent, since the mouseDoubleClick replaces the second release event in double click case): + if (mMouseEventElement) + { + mMouseEventElement->mouseReleaseEvent(event); + mMouseEventElement = 0; + } + + //QWidget::mouseDoubleClickEvent(event); don't call base class implementation because it would just cause a mousePress/ReleaseEvent, which we don't want. +} + +/*! \internal + + Event handler for when a mouse button is pressed. Emits the mousePress signal. Then determines + the affected layout element and forwards the event to it. + + \see mouseMoveEvent, mouseReleaseEvent +*/ +void QCustomPlot::mousePressEvent(QMouseEvent *event) +{ + emit mousePress(event); + mMousePressPos = event->pos(); // need this to determine in releaseEvent whether it was a click (no position change between press and release) + + // call event of affected layout element: + mMouseEventElement = layoutElementAt(event->pos()); + if (mMouseEventElement) + mMouseEventElement->mousePressEvent(event); + + QWidget::mousePressEvent(event); +} + +/*! \internal + + Event handler for when the cursor is moved. Emits the \ref mouseMove signal. + + If a layout element has mouse capture focus (a mousePressEvent happened on top of the layout + element before), the mouseMoveEvent is forwarded to that element. + + \see mousePressEvent, mouseReleaseEvent +*/ +void QCustomPlot::mouseMoveEvent(QMouseEvent *event) +{ + emit mouseMove(event); + + // call event of affected layout element: + if (mMouseEventElement) + mMouseEventElement->mouseMoveEvent(event); + + QWidget::mouseMoveEvent(event); +} + +/*! \internal + + Event handler for when a mouse button is released. Emits the \ref mouseRelease signal. + + If the mouse was moved less than a certain threshold in any direction since the \ref + mousePressEvent, it is considered a click which causes the selection mechanism (if activated via + \ref setInteractions) to possibly change selection states accordingly. Further, specialized mouse + click signals are emitted (e.g. \ref plottableClick, \ref axisClick, etc.) + + If a layout element has mouse capture focus (a \ref mousePressEvent happened on top of the layout + element before), the \ref mouseReleaseEvent is forwarded to that element. + + \see mousePressEvent, mouseMoveEvent +*/ +void QCustomPlot::mouseReleaseEvent(QMouseEvent *event) +{ + emit mouseRelease(event); + bool doReplot = false; + + if ((mMousePressPos-event->pos()).manhattanLength() < 5) // determine whether it was a click operation + { + if (event->button() == Qt::LeftButton) + { + // handle selection mechanism: + QVariant details; + QCPLayerable *clickedLayerable = layerableAt(event->pos(), true, &details); + bool selectionStateChanged = false; + bool additive = mInteractions.testFlag(QCP::iMultiSelect) && event->modifiers().testFlag(mMultiSelectModifier); + // deselect all other layerables if not additive selection: + if (!additive) + { + foreach (QCPLayer *layer, mLayers) + { + foreach (QCPLayerable *layerable, layer->children()) + { + if (layerable != clickedLayerable && mInteractions.testFlag(layerable->selectionCategory())) + { + bool selChanged = false; + layerable->deselectEvent(&selChanged); + selectionStateChanged |= selChanged; + } + } + } + } + if (clickedLayerable && mInteractions.testFlag(clickedLayerable->selectionCategory())) + { + // a layerable was actually clicked, call its selectEvent: + bool selChanged = false; + clickedLayerable->selectEvent(event, additive, details, &selChanged); + selectionStateChanged |= selChanged; + } + doReplot = true; + if (selectionStateChanged) + emit selectionChangedByUser(); + } + + // emit specialized object click signals: + QVariant details; + QCPLayerable *clickedLayerable = layerableAt(event->pos(), false, &details); // for these signals, selectability is ignored, that's why we call this again with onlySelectable set to false + if (QCPAbstractPlottable *ap = qobject_cast(clickedLayerable)) + emit plottableClick(ap, event); + else if (QCPAxis *ax = qobject_cast(clickedLayerable)) + emit axisClick(ax, details.value(), event); + else if (QCPAbstractItem *ai = qobject_cast(clickedLayerable)) + emit itemClick(ai, event); + else if (QCPLegend *lg = qobject_cast(clickedLayerable)) + emit legendClick(lg, 0, event); + else if (QCPAbstractLegendItem *li = qobject_cast(clickedLayerable)) + emit legendClick(li->parentLegend(), li, event); + else if (QCPPlotTitle *pt = qobject_cast(clickedLayerable)) + emit titleClick(event, pt); + } + + // call event of affected layout element: + if (mMouseEventElement) + { + mMouseEventElement->mouseReleaseEvent(event); + mMouseEventElement = 0; + } + + if (doReplot || noAntialiasingOnDrag()) + replot(); + + QWidget::mouseReleaseEvent(event); +} + +/*! \internal + + Event handler for mouse wheel events. First, the \ref mouseWheel signal is emitted. Then + determines the affected layout element and forwards the event to it. + +*/ +void QCustomPlot::wheelEvent(QWheelEvent *event) +{ + emit mouseWheel(event); + + // call event of affected layout element: + if (QCPLayoutElement *el = layoutElementAt(event->pos())) + el->wheelEvent(event); + + QWidget::wheelEvent(event); +} + +/*! \internal + + This is the main draw function. It draws the entire plot, including background pixmap, with the + specified \a painter. Note that it does not fill the background with the background brush (as the + user may specify with \ref setBackground(const QBrush &brush)), this is up to the respective + functions calling this method (e.g. \ref replot, \ref toPixmap and \ref toPainter). +*/ +void QCustomPlot::draw(QCPPainter *painter) +{ + // run through layout phases: + mPlotLayout->update(QCPLayoutElement::upPreparation); + mPlotLayout->update(QCPLayoutElement::upMargins); + mPlotLayout->update(QCPLayoutElement::upLayout); + + // draw viewport background pixmap: + drawBackground(painter); + + // draw all layered objects (grid, axes, plottables, items, legend,...): + foreach (QCPLayer *layer, mLayers) + { + foreach (QCPLayerable *child, layer->children()) + { + if (child->realVisibility()) + { + painter->save(); + painter->setClipRect(child->clipRect().translated(0, -1)); + child->applyDefaultAntialiasingHint(painter); + child->draw(painter); + painter->restore(); + } + } + } + + /* Debug code to draw all layout element rects + foreach (QCPLayoutElement* el, findChildren()) + { + painter->setBrush(Qt::NoBrush); + painter->setPen(QPen(QColor(0, 0, 0, 100), 0, Qt::DashLine)); + painter->drawRect(el->rect()); + painter->setPen(QPen(QColor(255, 0, 0, 100), 0, Qt::DashLine)); + painter->drawRect(el->outerRect()); + } + */ +} + +/*! \internal + + Draws the viewport background pixmap of the plot. + + If a pixmap was provided via \ref setBackground, this function buffers the scaled version + depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside + the viewport with the provided \a painter. The scaled version is buffered in + mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when + the axis rect has changed in a way that requires a rescale of the background pixmap (this is + dependent on the \ref setBackgroundScaledMode), or when a differend axis background pixmap was + set. + + Note that this function does not draw a fill with the background brush (\ref setBackground(const + QBrush &brush)) beneath the pixmap. + + \see setBackground, setBackgroundScaled, setBackgroundScaledMode +*/ +void QCustomPlot::drawBackground(QCPPainter *painter) +{ + // Note: background color is handled in individual replot/save functions + + // draw background pixmap (on top of fill, if brush specified): + if (!mBackgroundPixmap.isNull()) + { + if (mBackgroundScaled) + { + // check whether mScaledBackground needs to be updated: + QSize scaledSize(mBackgroundPixmap.size()); + scaledSize.scale(mViewport.size(), mBackgroundScaledMode); + if (mScaledBackgroundPixmap.size() != scaledSize) + mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mViewport.size(), mBackgroundScaledMode, Qt::SmoothTransformation); + painter->drawPixmap(mViewport.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height()) & mScaledBackgroundPixmap.rect()); + } else + { + painter->drawPixmap(mViewport.topLeft(), mBackgroundPixmap, QRect(0, 0, mViewport.width(), mViewport.height())); + } + } +} + + +/*! \internal + + This method is used by \ref QCPAxisRect::removeAxis to report removed axes to the QCustomPlot + so it may clear its QCustomPlot::xAxis, yAxis, xAxis2 and yAxis2 members accordingly. +*/ +void QCustomPlot::axisRemoved(QCPAxis *axis) +{ + if (xAxis == axis) + xAxis = 0; + if (xAxis2 == axis) + xAxis2 = 0; + if (yAxis == axis) + yAxis = 0; + if (yAxis2 == axis) + yAxis2 = 0; + + // Note: No need to take care of range drag axes and range zoom axes, because they are stored in smart pointers +} + +/*! \internal + + This method is used by the QCPLegend destructor to report legend removal to the QCustomPlot so + it may clear its QCustomPlot::legend member accordingly. +*/ +void QCustomPlot::legendRemoved(QCPLegend *legend) +{ + if (this->legend == legend) + this->legend = 0; +} + +/*! \internal + + Assigns all layers their index (QCPLayer::mIndex) in the mLayers list. This method is thus called + after every operation that changes the layer indices, like layer removal, layer creation, layer + moving. +*/ +void QCustomPlot::updateLayerIndices() const +{ + for (int i=0; imIndex = i; +} + +/*! \internal + + Returns the layerable at pixel position \a pos. If \a onlySelectable is set to true, only those + layerables that are selectable will be considered. (Layerable subclasses communicate their + selectability via the QCPLayerable::selectTest method, by returning -1.) + + \a selectionDetails is an output parameter that contains selection specifics of the affected + layerable. This is useful if the respective layerable shall be given a subsequent + QCPLayerable::selectEvent (like in \ref mouseReleaseEvent). \a selectionDetails usually contains + information about which part of the layerable was hit, in multi-part layerables (e.g. + QCPAxis::SelectablePart). +*/ +QCPLayerable *QCustomPlot::layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails) const +{ + for (int layerIndex=mLayers.size()-1; layerIndex>=0; --layerIndex) + { + const QList layerables = mLayers.at(layerIndex)->children(); + double minimumDistance = selectionTolerance()*1.1; + QCPLayerable *minimumDistanceLayerable = 0; + for (int i=layerables.size()-1; i>=0; --i) + { + if (!layerables.at(i)->realVisibility()) + continue; + QVariant details; + double dist = layerables.at(i)->selectTest(pos, onlySelectable, &details); + if (dist >= 0 && dist < minimumDistance) + { + minimumDistance = dist; + minimumDistanceLayerable = layerables.at(i); + if (selectionDetails) *selectionDetails = details; + } + } + if (minimumDistance < selectionTolerance()) + return minimumDistanceLayerable; + } + return 0; +} + +/*! + Saves the plot to a rastered image file \a fileName in the image format \a format. The plot is + sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and scale 2.0 lead + to a full resolution file with width 200.) If the \a format supports compression, \a quality may + be between 0 and 100 to control it. + + Returns true on success. If this function fails, most likely the given \a format isn't supported + by the system, see Qt docs about QImageWriter::supportedImageFormats(). + + \see saveBmp, saveJpg, savePng, savePdf +*/ +bool QCustomPlot::saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality) +{ + QPixmap buffer = toPixmap(width, height, scale); + if (!buffer.isNull()) + return buffer.save(fileName, format, quality); + else + return false; +} + +/*! + Renders the plot to a pixmap and returns it. + + The plot is sized to \a width and \a height in pixels and scaled with \a scale. (width 100 and + scale 2.0 lead to a full resolution pixmap with width 200.) + + \see toPainter, saveRastered, saveBmp, savePng, saveJpg, savePdf +*/ +QPixmap QCustomPlot::toPixmap(int width, int height, double scale) +{ + // this method is somewhat similar to toPainter. Change something here, and a change in toPainter might be necessary, too. + int newWidth, newHeight; + if (width == 0 || height == 0) + { + newWidth = this->width(); + newHeight = this->height(); + } else + { + newWidth = width; + newHeight = height; + } + int scaledWidth = qRound(scale*newWidth); + int scaledHeight = qRound(scale*newHeight); + + QPixmap result(scaledWidth, scaledHeight); + result.fill(mBackgroundBrush.style() == Qt::SolidPattern ? mBackgroundBrush.color() : Qt::transparent); // if using non-solid pattern, make transparent now and draw brush pattern later + QCPPainter painter; + painter.begin(&result); + if (painter.isActive()) + { + QRect oldViewport = viewport(); + setViewport(QRect(0, 0, newWidth, newHeight)); + painter.setMode(QCPPainter::pmNoCaching); + if (!qFuzzyCompare(scale, 1.0)) + { + if (scale > 1.0) // for scale < 1 we always want cosmetic pens where possible, because else lines might disappear for very small scales + painter.setMode(QCPPainter::pmNonCosmetic); + painter.scale(scale, scale); + } + if (mBackgroundBrush.style() != Qt::SolidPattern && mBackgroundBrush.style() != Qt::NoBrush) + painter.fillRect(mViewport, mBackgroundBrush); + draw(&painter); + setViewport(oldViewport); + painter.end(); + } else // might happen if pixmap has width or height zero + { + qDebug() << Q_FUNC_INFO << "Couldn't activate painter on pixmap"; + return QPixmap(); + } + return result; +} + +/*! + Renders the plot using the passed \a painter. + + The plot is sized to \a width and \a height in pixels. If the \a painter's scale is not 1.0, the resulting plot will + appear scaled accordingly. + + \note If you are restricted to using a QPainter (instead of QCPPainter), create a temporary QPicture and open a QCPPainter + on it. Then call \ref toPainter with this QCPPainter. After ending the paint operation on the picture, draw it with + the QPainter. This will reproduce the painter actions the QCPPainter took, with a QPainter. + + \see toPixmap +*/ +void QCustomPlot::toPainter(QCPPainter *painter, int width, int height) +{ + // this method is somewhat similar to toPixmap. Change something here, and a change in toPixmap might be necessary, too. + int newWidth, newHeight; + if (width == 0 || height == 0) + { + newWidth = this->width(); + newHeight = this->height(); + } else + { + newWidth = width; + newHeight = height; + } + + if (painter->isActive()) + { + QRect oldViewport = viewport(); + setViewport(QRect(0, 0, newWidth, newHeight)); + painter->setMode(QCPPainter::pmNoCaching); + // warning: the following is different in toPixmap, because a solid background color is applied there via QPixmap::fill + // here, we need to do this via QPainter::fillRect. + if (mBackgroundBrush.style() != Qt::NoBrush) + painter->fillRect(mViewport, mBackgroundBrush); + draw(painter); + setViewport(oldViewport); + } else + qDebug() << Q_FUNC_INFO << "Passed painter is not active"; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPColorGradient +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPColorGradient + \brief Defines a color gradient for use with e.g. \ref QCPColorMap + + This class describes a color gradient which can be used to encode data with color. For example, + QCPColorMap and QCPColorScale have \ref QCPColorMap::setGradient "setGradient" methods which + take an instance of this class. Colors are set with \ref setColorStopAt(double position, const QColor &color) + with a \a position from 0 to 1. In between these defined color positions, the + color will be interpolated linearly either in RGB or HSV space, see \ref setColorInterpolation. + + Alternatively, load one of the preset color gradients shown in the image below, with \ref + loadPreset, or by directly specifying the preset in the constructor. + + \image html QCPColorGradient.png + + The fact that the \ref QCPColorGradient(GradientPreset preset) constructor allows directly + converting a \ref GradientPreset to a QCPColorGradient, you can also directly pass \ref + GradientPreset to all the \a setGradient methods, e.g.: + \code + colorMap->setGradient(QCPColorGradient::gpHot); + \endcode + + The total number of levels used in the gradient can be set with \ref setLevelCount. Whether the + color gradient shall be applied periodically (wrapping around) to data values that lie outside + the data range specified on the plottable instance can be controlled with \ref setPeriodic. +*/ + +/*! + Constructs a new QCPColorGradient initialized with the colors and color interpolation according + to \a preset. + + The color level count is initialized to 350. +*/ +QCPColorGradient::QCPColorGradient(GradientPreset preset) : + mLevelCount(350), + mColorInterpolation(ciRGB), + mPeriodic(false), + mColorBufferInvalidated(true) +{ + mColorBuffer.fill(qRgb(0, 0, 0), mLevelCount); + loadPreset(preset); +} + +/* undocumented operator */ +bool QCPColorGradient::operator==(const QCPColorGradient &other) const +{ + return ((other.mLevelCount == this->mLevelCount) && + (other.mColorInterpolation == this->mColorInterpolation) && + (other.mPeriodic == this->mPeriodic) && + (other.mColorStops == this->mColorStops)); +} + +/*! + Sets the number of discretization levels of the color gradient to \a n. The default is 350 which + is typically enough to create a smooth appearance. + + \image html QCPColorGradient-levelcount.png +*/ +void QCPColorGradient::setLevelCount(int n) +{ + if (n < 2) + { + qDebug() << Q_FUNC_INFO << "n must be greater or equal 2 but was" << n; + n = 2; + } + if (n != mLevelCount) + { + mLevelCount = n; + mColorBufferInvalidated = true; + } +} + +/*! + Sets at which positions from 0 to 1 which color shall occur. The positions are the keys, the + colors are the values of the passed QMap \a colorStops. In between these color stops, the color + is interpolated according to \ref setColorInterpolation. + + A more convenient way to create a custom gradient may be to clear all color stops with \ref + clearColorStops and then adding them one by one with \ref setColorStopAt. + + \see clearColorStops +*/ +void QCPColorGradient::setColorStops(const QMap &colorStops) +{ + mColorStops = colorStops; + mColorBufferInvalidated = true; +} + +/*! + Sets the \a color the gradient will have at the specified \a position (from 0 to 1). In between + these color stops, the color is interpolated according to \ref setColorInterpolation. + + \see setColorStops, clearColorStops +*/ +void QCPColorGradient::setColorStopAt(double position, const QColor &color) +{ + mColorStops.insert(position, color); + mColorBufferInvalidated = true; +} + +/*! + Sets whether the colors in between the configured color stops (see \ref setColorStopAt) shall be + interpolated linearly in RGB or in HSV color space. + + For example, a sweep in RGB space from red to green will have a muddy brown intermediate color, + whereas in HSV space the intermediate color is yellow. +*/ +void QCPColorGradient::setColorInterpolation(QCPColorGradient::ColorInterpolation interpolation) +{ + if (interpolation != mColorInterpolation) + { + mColorInterpolation = interpolation; + mColorBufferInvalidated = true; + } +} + +/*! + Sets whether data points that are outside the configured data range (e.g. \ref + QCPColorMap::setDataRange) are colored by periodically repeating the color gradient or whether + they all have the same color, corresponding to the respective gradient boundary color. + + \image html QCPColorGradient-periodic.png + + As shown in the image above, gradients that have the same start and end color are especially + suitable for a periodic gradient mapping, since they produce smooth color transitions throughout + the color map. A preset that has this property is \ref gpHues. + + In practice, using periodic color gradients makes sense when the data corresponds to a periodic + dimension, such as an angle or a phase. If this is not the case, the color encoding might become + ambiguous, because multiple different data values are shown as the same color. +*/ +void QCPColorGradient::setPeriodic(bool enabled) +{ + mPeriodic = enabled; +} + +/*! + This method is used to quickly convert a \a data array to colors. The colors will be output in + the array \a scanLine. Both \a data and \a scanLine must have the length \a n when passed to this + function. The data range that shall be used for mapping the data value to the gradient is passed + in \a range. \a logarithmic indicates whether the data values shall be mapped to colors + logarithmically. + + if \a data actually contains 2D-data linearized via [row*columnCount + column], you can + set \a dataIndexFactor to columnCount to convert a column instead of a row of the data + array, in \a scanLine. \a scanLine will remain a regular (1D) array. This works because \a data + is addressed data[i*dataIndexFactor]. +*/ +void QCPColorGradient::colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor, bool logarithmic) +{ + // If you change something here, make sure to also adapt ::color() + if (!data) + { + qDebug() << Q_FUNC_INFO << "null pointer given as data"; + return; + } + if (!scanLine) + { + qDebug() << Q_FUNC_INFO << "null pointer given as scanLine"; + return; + } + if (mColorBufferInvalidated) + updateColorBuffer(); + + if (!logarithmic) + { + const double posToIndexFactor = mLevelCount/range.size(); + if (mPeriodic) + { + for (int i=0; i= mLevelCount) + index = mLevelCount-1; + scanLine[i] = mColorBuffer.at(index); + } + } + } else // logarithmic == true + { + if (mPeriodic) + { + for (int i=0; i= mLevelCount) + index = mLevelCount-1; + scanLine[i] = mColorBuffer.at(index); + } + } + } +} + +/*! \internal + + This method is used to colorize a single data value given in \a position, to colors. The data + range that shall be used for mapping the data value to the gradient is passed in \a range. \a + logarithmic indicates whether the data value shall be mapped to a color logarithmically. + + If an entire array of data values shall be converted, rather use \ref colorize, for better + performance. +*/ +QRgb QCPColorGradient::color(double position, const QCPRange &range, bool logarithmic) +{ + // If you change something here, make sure to also adapt ::colorize() + if (mColorBufferInvalidated) + updateColorBuffer(); + int index = 0; + if (!logarithmic) + index = (position-range.lower)*mLevelCount/range.size(); + else + index = qLn(position/range.lower)/qLn(range.upper/range.lower)*mLevelCount; + if (mPeriodic) + { + index = index % mLevelCount; + if (index < 0) + index += mLevelCount; + } else + { + if (index < 0) + index = 0; + else if (index >= mLevelCount) + index = mLevelCount-1; + } + return mColorBuffer.at(index); +} + +/*! + Clears the current color stops and loads the specified \a preset. A preset consists of predefined + color stops and the corresponding color interpolation method. + + The available presets are: + \image html QCPColorGradient.png +*/ +void QCPColorGradient::loadPreset(GradientPreset preset) +{ + clearColorStops(); + switch (preset) + { + case gpGrayscale: + setColorInterpolation(ciRGB); + setColorStopAt(0, Qt::black); + setColorStopAt(1, Qt::white); + break; + case gpHot: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(50, 0, 0)); + setColorStopAt(0.2, QColor(180, 10, 0)); + setColorStopAt(0.4, QColor(245, 50, 0)); + setColorStopAt(0.6, QColor(255, 150, 10)); + setColorStopAt(0.8, QColor(255, 255, 50)); + setColorStopAt(1, QColor(255, 255, 255)); + break; + case gpCold: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(0, 0, 50)); + setColorStopAt(0.2, QColor(0, 10, 180)); + setColorStopAt(0.4, QColor(0, 50, 245)); + setColorStopAt(0.6, QColor(10, 150, 255)); + setColorStopAt(0.8, QColor(50, 255, 255)); + setColorStopAt(1, QColor(255, 255, 255)); + break; + case gpNight: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(10, 20, 30)); + setColorStopAt(1, QColor(250, 255, 250)); + break; + case gpCandy: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(0, 0, 255)); + setColorStopAt(1, QColor(255, 250, 250)); + break; + case gpGeography: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(70, 170, 210)); + setColorStopAt(0.20, QColor(90, 160, 180)); + setColorStopAt(0.25, QColor(45, 130, 175)); + setColorStopAt(0.30, QColor(100, 140, 125)); + setColorStopAt(0.5, QColor(100, 140, 100)); + setColorStopAt(0.6, QColor(130, 145, 120)); + setColorStopAt(0.7, QColor(140, 130, 120)); + setColorStopAt(0.9, QColor(180, 190, 190)); + setColorStopAt(1, QColor(210, 210, 230)); + break; + case gpIon: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(50, 10, 10)); + setColorStopAt(0.45, QColor(0, 0, 255)); + setColorStopAt(0.8, QColor(0, 255, 255)); + setColorStopAt(1, QColor(0, 255, 0)); + break; + case gpThermal: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(0, 0, 50)); + setColorStopAt(0.15, QColor(20, 0, 120)); + setColorStopAt(0.33, QColor(200, 30, 140)); + setColorStopAt(0.6, QColor(255, 100, 0)); + setColorStopAt(0.85, QColor(255, 255, 40)); + setColorStopAt(1, QColor(255, 255, 255)); + break; + case gpPolar: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(50, 255, 255)); + setColorStopAt(0.18, QColor(10, 70, 255)); + setColorStopAt(0.28, QColor(10, 10, 190)); + setColorStopAt(0.5, QColor(0, 0, 0)); + setColorStopAt(0.72, QColor(190, 10, 10)); + setColorStopAt(0.82, QColor(255, 70, 10)); + setColorStopAt(1, QColor(255, 255, 50)); + break; + case gpSpectrum: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(50, 0, 50)); + setColorStopAt(0.15, QColor(0, 0, 255)); + setColorStopAt(0.35, QColor(0, 255, 255)); + setColorStopAt(0.6, QColor(255, 255, 0)); + setColorStopAt(0.75, QColor(255, 30, 0)); + setColorStopAt(1, QColor(50, 0, 0)); + break; + case gpJet: + setColorInterpolation(ciRGB); + setColorStopAt(0, QColor(0, 0, 100)); + setColorStopAt(0.15, QColor(0, 50, 255)); + setColorStopAt(0.35, QColor(0, 255, 255)); + setColorStopAt(0.65, QColor(255, 255, 0)); + setColorStopAt(0.85, QColor(255, 30, 0)); + setColorStopAt(1, QColor(100, 0, 0)); + break; + case gpHues: + setColorInterpolation(ciHSV); + setColorStopAt(0, QColor(255, 0, 0)); + setColorStopAt(1.0/3.0, QColor(0, 0, 255)); + setColorStopAt(2.0/3.0, QColor(0, 255, 0)); + setColorStopAt(1, QColor(255, 0, 0)); + break; + } +} + +/*! + Clears all color stops. + + \see setColorStops, setColorStopAt +*/ +void QCPColorGradient::clearColorStops() +{ + mColorStops.clear(); + mColorBufferInvalidated = true; +} + +/*! + Returns an inverted gradient. The inverted gradient has all properties as this \ref + QCPColorGradient, but the order of the color stops is inverted. + + \see setColorStops, setColorStopAt +*/ +QCPColorGradient QCPColorGradient::inverted() const +{ + QCPColorGradient result(*this); + result.clearColorStops(); + for (QMap::const_iterator it=mColorStops.constBegin(); it!=mColorStops.constEnd(); ++it) + result.setColorStopAt(1.0-it.key(), it.value()); + return result; +} + +/*! \internal + + Updates the internal color buffer which will be used by \ref colorize and \ref color, to quickly + convert positions to colors. This is where the interpolation between color stops is calculated. +*/ +void QCPColorGradient::updateColorBuffer() +{ + if (mColorBuffer.size() != mLevelCount) + mColorBuffer.resize(mLevelCount); + if (mColorStops.size() > 1) + { + double indexToPosFactor = 1.0/(double)(mLevelCount-1); + for (int i=0; i::const_iterator it = mColorStops.lowerBound(position); + if (it == mColorStops.constEnd()) // position is on or after last stop, use color of last stop + { + mColorBuffer[i] = (it-1).value().rgb(); + } else if (it == mColorStops.constBegin()) // position is on or before first stop, use color of first stop + { + mColorBuffer[i] = it.value().rgb(); + } else // position is in between stops (or on an intermediate stop), interpolate color + { + QMap::const_iterator high = it; + QMap::const_iterator low = it-1; + double t = (position-low.key())/(high.key()-low.key()); // interpolation factor 0..1 + switch (mColorInterpolation) + { + case ciRGB: + { + mColorBuffer[i] = qRgb((1-t)*low.value().red() + t*high.value().red(), + (1-t)*low.value().green() + t*high.value().green(), + (1-t)*low.value().blue() + t*high.value().blue()); + break; + } + case ciHSV: + { + QColor lowHsv = low.value().toHsv(); + QColor highHsv = high.value().toHsv(); + double hue = 0; + double hueDiff = highHsv.hueF()-lowHsv.hueF(); + if (hueDiff > 0.5) + hue = lowHsv.hueF() - t*(1.0-hueDiff); + else if (hueDiff < -0.5) + hue = lowHsv.hueF() + t*(1.0+hueDiff); + else + hue = lowHsv.hueF() + t*hueDiff; + if (hue < 0) hue += 1.0; + else if (hue >= 1.0) hue -= 1.0; + mColorBuffer[i] = QColor::fromHsvF(hue, (1-t)*lowHsv.saturationF() + t*highHsv.saturationF(), (1-t)*lowHsv.valueF() + t*highHsv.valueF()).rgb(); + break; + } + } + } + } + } else if (mColorStops.size() == 1) + { + mColorBuffer.fill(mColorStops.constBegin().value().rgb()); + } else // mColorStops is empty, fill color buffer with black + { + mColorBuffer.fill(qRgb(0, 0, 0)); + } + mColorBufferInvalidated = false; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPAxisRect +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPAxisRect + \brief Holds multiple axes and arranges them in a rectangular shape. + + This class represents an axis rect, a rectangular area that is bounded on all sides with an + arbitrary number of axes. + + Initially QCustomPlot has one axis rect, accessible via QCustomPlot::axisRect(). However, the + layout system allows to have multiple axis rects, e.g. arranged in a grid layout + (QCustomPlot::plotLayout). + + By default, QCPAxisRect comes with four axes, at bottom, top, left and right. They can be + accessed via \ref axis by providing the respective axis type (\ref QCPAxis::AxisType) and index. + If you need all axes in the axis rect, use \ref axes. The top and right axes are set to be + invisible initially (QCPAxis::setVisible). To add more axes to a side, use \ref addAxis or \ref + addAxes. To remove an axis, use \ref removeAxis. + + The axis rect layerable itself only draws a background pixmap or color, if specified (\ref + setBackground). It is placed on the "background" layer initially (see \ref QCPLayer for an + explanation of the QCustomPlot layer system). The axes that are held by the axis rect can be + placed on other layers, independently of the axis rect. + + Every axis rect has a child layout of type \ref QCPLayoutInset. It is accessible via \ref + insetLayout and can be used to have other layout elements (or even other layouts with multiple + elements) hovering inside the axis rect. + + If an axis rect is clicked and dragged, it processes this by moving certain axis ranges. The + behaviour can be controlled with \ref setRangeDrag and \ref setRangeDragAxes. If the mouse wheel + is scrolled while the cursor is on the axis rect, certain axes are scaled. This is controllable + via \ref setRangeZoom, \ref setRangeZoomAxes and \ref setRangeZoomFactor. These interactions are + only enabled if \ref QCustomPlot::setInteractions contains \ref QCP::iRangeDrag and \ref + QCP::iRangeZoom. + + \image html AxisRectSpacingOverview.png +
Overview of the spacings and paddings that define the geometry of an axis. The dashed + line on the far left indicates the viewport/widget border.
+*/ + +/* start documentation of inline functions */ + +/*! \fn QCPLayoutInset *QCPAxisRect::insetLayout() const + + Returns the inset layout of this axis rect. It can be used to place other layout elements (or + even layouts with multiple other elements) inside/on top of an axis rect. + + \see QCPLayoutInset +*/ + +/*! \fn int QCPAxisRect::left() const + + Returns the pixel position of the left border of this axis rect. Margins are not taken into + account here, so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn int QCPAxisRect::right() const + + Returns the pixel position of the right border of this axis rect. Margins are not taken into + account here, so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn int QCPAxisRect::top() const + + Returns the pixel position of the top border of this axis rect. Margins are not taken into + account here, so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn int QCPAxisRect::bottom() const + + Returns the pixel position of the bottom border of this axis rect. Margins are not taken into + account here, so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn int QCPAxisRect::width() const + + Returns the pixel width of this axis rect. Margins are not taken into account here, so the + returned value is with respect to the inner \ref rect. +*/ + +/*! \fn int QCPAxisRect::height() const + + Returns the pixel height of this axis rect. Margins are not taken into account here, so the + returned value is with respect to the inner \ref rect. +*/ + +/*! \fn QSize QCPAxisRect::size() const + + Returns the pixel size of this axis rect. Margins are not taken into account here, so the + returned value is with respect to the inner \ref rect. +*/ + +/*! \fn QPoint QCPAxisRect::topLeft() const + + Returns the top left corner of this axis rect in pixels. Margins are not taken into account here, + so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn QPoint QCPAxisRect::topRight() const + + Returns the top right corner of this axis rect in pixels. Margins are not taken into account + here, so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn QPoint QCPAxisRect::bottomLeft() const + + Returns the bottom left corner of this axis rect in pixels. Margins are not taken into account + here, so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn QPoint QCPAxisRect::bottomRight() const + + Returns the bottom right corner of this axis rect in pixels. Margins are not taken into account + here, so the returned value is with respect to the inner \ref rect. +*/ + +/*! \fn QPoint QCPAxisRect::center() const + + Returns the center of this axis rect in pixels. Margins are not taken into account here, so the + returned value is with respect to the inner \ref rect. +*/ + +/* end documentation of inline functions */ + +/*! + Creates a QCPAxisRect instance and sets default values. An axis is added for each of the four + sides, the top and right axes are set invisible initially. +*/ +QCPAxisRect::QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes) : + QCPLayoutElement(parentPlot), + mBackgroundBrush(Qt::NoBrush), + mBackgroundScaled(true), + mBackgroundScaledMode(Qt::KeepAspectRatioByExpanding), + mInsetLayout(new QCPLayoutInset), + mRangeDrag(Qt::Horizontal|Qt::Vertical), + mRangeZoom(Qt::Horizontal|Qt::Vertical), + mRangeZoomFactorHorz(0.85), + mRangeZoomFactorVert(0.85), + mDragging(false) +{ + mInsetLayout->initializeParentPlot(mParentPlot); + mInsetLayout->setParentLayerable(this); + mInsetLayout->setParent(this); + + setMinimumSize(50, 50); + setMinimumMargins(QMargins(15, 15, 15, 15)); + mAxes.insert(QCPAxis::atLeft, QList()); + mAxes.insert(QCPAxis::atRight, QList()); + mAxes.insert(QCPAxis::atTop, QList()); + mAxes.insert(QCPAxis::atBottom, QList()); + + if (setupDefaultAxes) + { + QCPAxis *xAxis = addAxis(QCPAxis::atBottom); + QCPAxis *yAxis = addAxis(QCPAxis::atLeft); + QCPAxis *xAxis2 = addAxis(QCPAxis::atTop); + QCPAxis *yAxis2 = addAxis(QCPAxis::atRight); + setRangeDragAxes(xAxis, yAxis); + setRangeZoomAxes(xAxis, yAxis); + xAxis2->setVisible(false); + yAxis2->setVisible(false); + xAxis->grid()->setVisible(true); + yAxis->grid()->setVisible(true); + xAxis2->grid()->setVisible(false); + yAxis2->grid()->setVisible(false); + xAxis2->grid()->setZeroLinePen(Qt::NoPen); + yAxis2->grid()->setZeroLinePen(Qt::NoPen); + xAxis2->grid()->setVisible(false); + yAxis2->grid()->setVisible(false); + } +} + +QCPAxisRect::~QCPAxisRect() +{ +// delete mInsetLayout; +// mInsetLayout = 0; + +// QList axesList = axes(); +// for (int i=0; i ax(mAxes.value(type)); + if (index >= 0 && index < ax.size()) + { + return ax.at(index); + } else + { + qDebug() << Q_FUNC_INFO << "Axis index out of bounds:" << index; + return 0; + } +} + +/*! + Returns all axes on the axis rect sides specified with \a types. + + \a types may be a single \ref QCPAxis::AxisType or an or-combination, to get the axes of + multiple sides. + + \see axis +*/ +QList QCPAxisRect::axes(QCPAxis::AxisTypes types) const +{ + QList result; + if (types.testFlag(QCPAxis::atLeft)) + result << mAxes.value(QCPAxis::atLeft); + if (types.testFlag(QCPAxis::atRight)) + result << mAxes.value(QCPAxis::atRight); + if (types.testFlag(QCPAxis::atTop)) + result << mAxes.value(QCPAxis::atTop); + if (types.testFlag(QCPAxis::atBottom)) + result << mAxes.value(QCPAxis::atBottom); + return result; +} + +/*! \overload + + Returns all axes of this axis rect. +*/ +QList QCPAxisRect::axes() const +{ + QList result; + QHashIterator > it(mAxes); + while (it.hasNext()) + { + it.next(); + result << it.value(); + } + return result; +} + +/*! + Adds a new axis to the axis rect side specified with \a type, and returns it. + + If an axis rect side already contains one or more axes, the lower and upper endings of the new + axis (\ref QCPAxis::setLowerEnding, \ref QCPAxis::setUpperEnding) are initialized to \ref + QCPLineEnding::esHalfBar. + + \see addAxes, setupFullAxesBox +*/ +QCPAxis *QCPAxisRect::addAxis(QCPAxis::AxisType type) +{ + QCPAxis *newAxis = new QCPAxis(this, type); + if (mAxes[type].size() > 0) // multiple axes on one side, add half-bar axis ending to additional axes with offset + { + bool invert = (type == QCPAxis::atRight) || (type == QCPAxis::atBottom); + newAxis->setLowerEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, !invert)); + newAxis->setUpperEnding(QCPLineEnding(QCPLineEnding::esHalfBar, 6, 10, invert)); + } + mAxes[type].append(newAxis); + return newAxis; +} + +/*! + Adds a new axis with \ref addAxis to each axis rect side specified in \a types. This may be an + or-combination of QCPAxis::AxisType, so axes can be added to multiple sides at once. + + Returns a list of the added axes. + + \see addAxis, setupFullAxesBox +*/ +QList QCPAxisRect::addAxes(QCPAxis::AxisTypes types) +{ + QList result; + if (types.testFlag(QCPAxis::atLeft)) + result << addAxis(QCPAxis::atLeft); + if (types.testFlag(QCPAxis::atRight)) + result << addAxis(QCPAxis::atRight); + if (types.testFlag(QCPAxis::atTop)) + result << addAxis(QCPAxis::atTop); + if (types.testFlag(QCPAxis::atBottom)) + result << addAxis(QCPAxis::atBottom); + return result; +} + +/*! + Removes the specified \a axis from the axis rect and deletes it. + + Returns true on success, i.e. if \a axis was a valid axis in this axis rect. + + \see addAxis +*/ +bool QCPAxisRect::removeAxis(QCPAxis *axis) +{ + // don't access axis->axisType() to provide safety when axis is an invalid pointer, rather go through all axis containers: + QHashIterator > it(mAxes); + while (it.hasNext()) + { + it.next(); + if (it.value().contains(axis)) + { + mAxes[it.key()].removeOne(axis); + if (qobject_cast(parentPlot())) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the axis rect is not in any layout and thus QObject-child of QCustomPlot) + parentPlot()->axisRemoved(axis); + delete axis; + return true; + } + } + qDebug() << Q_FUNC_INFO << "Axis isn't in axis rect:" << reinterpret_cast(axis); + return false; +} + +/*! + Convenience function to create an axis on each side that doesn't have any axes yet and set their + visibility to true. Further, the top/right axes are assigned the following properties of the + bottom/left axes: + + \li range (\ref QCPAxis::setRange) + \li range reversed (\ref QCPAxis::setRangeReversed) + \li scale type (\ref QCPAxis::setScaleType) + \li scale log base (\ref QCPAxis::setScaleLogBase) + \li ticks (\ref QCPAxis::setTicks) + \li auto (major) tick count (\ref QCPAxis::setAutoTickCount) + \li sub tick count (\ref QCPAxis::setSubTickCount) + \li auto sub ticks (\ref QCPAxis::setAutoSubTicks) + \li tick step (\ref QCPAxis::setTickStep) + \li auto tick step (\ref QCPAxis::setAutoTickStep) + \li number format (\ref QCPAxis::setNumberFormat) + \li number precision (\ref QCPAxis::setNumberPrecision) + \li tick label type (\ref QCPAxis::setTickLabelType) + \li date time format (\ref QCPAxis::setDateTimeFormat) + \li date time spec (\ref QCPAxis::setDateTimeSpec) + + Tick labels (\ref QCPAxis::setTickLabels) of the right and top axes are set to false. + + If \a connectRanges is true, the \ref QCPAxis::rangeChanged "rangeChanged" signals of the bottom + and left axes are connected to the \ref QCPAxis::setRange slots of the top and right axes. +*/ +void QCPAxisRect::setupFullAxesBox(bool connectRanges) +{ + QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; + if (axisCount(QCPAxis::atBottom) == 0) + xAxis = addAxis(QCPAxis::atBottom); + else + xAxis = axis(QCPAxis::atBottom); + + if (axisCount(QCPAxis::atLeft) == 0) + yAxis = addAxis(QCPAxis::atLeft); + else + yAxis = axis(QCPAxis::atLeft); + + if (axisCount(QCPAxis::atTop) == 0) + xAxis2 = addAxis(QCPAxis::atTop); + else + xAxis2 = axis(QCPAxis::atTop); + + if (axisCount(QCPAxis::atRight) == 0) + yAxis2 = addAxis(QCPAxis::atRight); + else + yAxis2 = axis(QCPAxis::atRight); + + xAxis->setVisible(true); + yAxis->setVisible(true); + xAxis2->setVisible(true); + yAxis2->setVisible(true); + xAxis2->setTickLabels(false); + yAxis2->setTickLabels(false); + + xAxis2->setRange(xAxis->range()); + xAxis2->setRangeReversed(xAxis->rangeReversed()); + xAxis2->setScaleType(xAxis->scaleType()); + xAxis2->setScaleLogBase(xAxis->scaleLogBase()); + xAxis2->setTicks(xAxis->ticks()); + xAxis2->setAutoTickCount(xAxis->autoTickCount()); + xAxis2->setSubTickCount(xAxis->subTickCount()); + xAxis2->setAutoSubTicks(xAxis->autoSubTicks()); + xAxis2->setTickStep(xAxis->tickStep()); + xAxis2->setAutoTickStep(xAxis->autoTickStep()); + xAxis2->setNumberFormat(xAxis->numberFormat()); + xAxis2->setNumberPrecision(xAxis->numberPrecision()); + xAxis2->setTickLabelType(xAxis->tickLabelType()); + xAxis2->setDateTimeFormat(xAxis->dateTimeFormat()); + xAxis2->setDateTimeSpec(xAxis->dateTimeSpec()); + + yAxis2->setRange(yAxis->range()); + yAxis2->setRangeReversed(yAxis->rangeReversed()); + yAxis2->setScaleType(yAxis->scaleType()); + yAxis2->setScaleLogBase(yAxis->scaleLogBase()); + yAxis2->setTicks(yAxis->ticks()); + yAxis2->setAutoTickCount(yAxis->autoTickCount()); + yAxis2->setSubTickCount(yAxis->subTickCount()); + yAxis2->setAutoSubTicks(yAxis->autoSubTicks()); + yAxis2->setTickStep(yAxis->tickStep()); + yAxis2->setAutoTickStep(yAxis->autoTickStep()); + yAxis2->setNumberFormat(yAxis->numberFormat()); + yAxis2->setNumberPrecision(yAxis->numberPrecision()); + yAxis2->setTickLabelType(yAxis->tickLabelType()); + yAxis2->setDateTimeFormat(yAxis->dateTimeFormat()); + yAxis2->setDateTimeSpec(yAxis->dateTimeSpec()); + + if (connectRanges) + { + connect(xAxis, SIGNAL(rangeChanged(QCPRange)), xAxis2, SLOT(setRange(QCPRange))); + connect(yAxis, SIGNAL(rangeChanged(QCPRange)), yAxis2, SLOT(setRange(QCPRange))); + } +} + +/*! + Returns a list of all the plottables that are associated with this axis rect. + + A plottable is considered associated with an axis rect if its key or value axis (or both) is in + this axis rect. + + \see graphs, items +*/ +QList QCPAxisRect::plottables() const +{ + // Note: don't append all QCPAxis::plottables() into a list, because we might get duplicate entries + QList result; + for (int i=0; imPlottables.size(); ++i) + { + if (mParentPlot->mPlottables.at(i)->keyAxis()->axisRect() == this ||mParentPlot->mPlottables.at(i)->valueAxis()->axisRect() == this) + result.append(mParentPlot->mPlottables.at(i)); + } + return result; +} + +/*! + Returns a list of all the graphs that are associated with this axis rect. + + A graph is considered associated with an axis rect if its key or value axis (or both) is in + this axis rect. + + \see plottables, items +*/ +QList QCPAxisRect::graphs() const +{ + // Note: don't append all QCPAxis::graphs() into a list, because we might get duplicate entries + QList result; + for (int i=0; imGraphs.size(); ++i) + { + if (mParentPlot->mGraphs.at(i)->keyAxis()->axisRect() == this || mParentPlot->mGraphs.at(i)->valueAxis()->axisRect() == this) + result.append(mParentPlot->mGraphs.at(i)); + } + return result; +} + +/*! + Returns a list of all the items that are associated with this axis rect. + + An item is considered associated with an axis rect if any of its positions has key or value axis + set to an axis that is in this axis rect, or if any of its positions has \ref + QCPItemPosition::setAxisRect set to the axis rect, or if the clip axis rect (\ref + QCPAbstractItem::setClipAxisRect) is set to this axis rect. + + \see plottables, graphs +*/ +QList QCPAxisRect::items() const +{ + // Note: don't just append all QCPAxis::items() into a list, because we might get duplicate entries + // and miss those items that have this axis rect as clipAxisRect. + QList result; + for (int itemId=0; itemIdmItems.size(); ++itemId) + { + if (mParentPlot->mItems.at(itemId)->clipAxisRect() == this) + { + result.append(mParentPlot->mItems.at(itemId)); + continue; + } + QList positions = mParentPlot->mItems.at(itemId)->positions(); + for (int posId=0; posIdaxisRect() == this || + positions.at(posId)->keyAxis()->axisRect() == this || + positions.at(posId)->valueAxis()->axisRect() == this) + { + result.append(mParentPlot->mItems.at(itemId)); + break; + } + } + } + return result; +} + +/*! + This method is called automatically upon replot and doesn't need to be called by users of + QCPAxisRect. + + Calls the base class implementation to update the margins (see \ref QCPLayoutElement::update), + and finally passes the \ref rect to the inset layout (\ref insetLayout) and calls its + QCPInsetLayout::update function. +*/ +void QCPAxisRect::update(UpdatePhase phase) +{ + QCPLayoutElement::update(phase); + + switch (phase) + { + case upPreparation: + { + QList allAxes = axes(); + for (int i=0; isetupTickVectors(); + break; + } + case upLayout: + { + mInsetLayout->setOuterRect(rect()); + break; + } + default: break; + } + + // pass update call on to inset layout (doesn't happen automatically, because QCPAxisRect doesn't derive from QCPLayout): + mInsetLayout->update(phase); +} + +/* inherits documentation from base class */ +QList QCPAxisRect::elements(bool recursive) const +{ + QList result; + if (mInsetLayout) + { + result << mInsetLayout; + if (recursive) + result << mInsetLayout->elements(recursive); + } + return result; +} + +/* inherits documentation from base class */ +void QCPAxisRect::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + painter->setAntialiasing(false); +} + +/* inherits documentation from base class */ +void QCPAxisRect::draw(QCPPainter *painter) +{ + drawBackground(painter); +} + +/*! + Sets \a pm as the axis background pixmap. The axis background pixmap will be drawn inside the + axis rect. Since axis rects place themselves on the "background" layer by default, the axis rect + backgrounds are usually drawn below everything else. + + For cases where the provided pixmap doesn't have the same size as the axis rect, scaling can be + enabled with \ref setBackgroundScaled and the scaling mode (i.e. whether and how the aspect ratio + is preserved) can be set with \ref setBackgroundScaledMode. To set all these options in one call, + consider using the overloaded version of this function. + + Below the pixmap, the axis rect may be optionally filled with a brush, if specified with \ref + setBackground(const QBrush &brush). + + \see setBackgroundScaled, setBackgroundScaledMode, setBackground(const QBrush &brush) +*/ +void QCPAxisRect::setBackground(const QPixmap &pm) +{ + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); +} + +/*! \overload + + Sets \a brush as the background brush. The axis rect background will be filled with this brush. + Since axis rects place themselves on the "background" layer by default, the axis rect backgrounds + are usually drawn below everything else. + + The brush will be drawn before (under) any background pixmap, which may be specified with \ref + setBackground(const QPixmap &pm). + + To disable drawing of a background brush, set \a brush to Qt::NoBrush. + + \see setBackground(const QPixmap &pm) +*/ +void QCPAxisRect::setBackground(const QBrush &brush) +{ + mBackgroundBrush = brush; +} + +/*! \overload + + Allows setting the background pixmap of the axis rect, whether it shall be scaled and how it + shall be scaled in one call. + + \see setBackground(const QPixmap &pm), setBackgroundScaled, setBackgroundScaledMode +*/ +void QCPAxisRect::setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode) +{ + mBackgroundPixmap = pm; + mScaledBackgroundPixmap = QPixmap(); + mBackgroundScaled = scaled; + mBackgroundScaledMode = mode; +} + +/*! + Sets whether the axis background pixmap shall be scaled to fit the axis rect or not. If \a scaled + is set to true, you may control whether and how the aspect ratio of the original pixmap is + preserved with \ref setBackgroundScaledMode. + + Note that the scaled version of the original pixmap is buffered, so there is no performance + penalty on replots. (Except when the axis rect dimensions are changed continuously.) + + \see setBackground, setBackgroundScaledMode +*/ +void QCPAxisRect::setBackgroundScaled(bool scaled) +{ + mBackgroundScaled = scaled; +} + +/*! + If scaling of the axis background pixmap is enabled (\ref setBackgroundScaled), use this function to + define whether and how the aspect ratio of the original pixmap passed to \ref setBackground is preserved. + \see setBackground, setBackgroundScaled +*/ +void QCPAxisRect::setBackgroundScaledMode(Qt::AspectRatioMode mode) +{ + mBackgroundScaledMode = mode; +} + +/*! + Returns the range drag axis of the \a orientation provided. + + \see setRangeDragAxes +*/ +QCPAxis *QCPAxisRect::rangeDragAxis(Qt::Orientation orientation) +{ + return (orientation == Qt::Horizontal ? mRangeDragHorzAxis.data() : mRangeDragVertAxis.data()); +} + +/*! + Returns the range zoom axis of the \a orientation provided. + + \see setRangeZoomAxes +*/ +QCPAxis *QCPAxisRect::rangeZoomAxis(Qt::Orientation orientation) +{ + return (orientation == Qt::Horizontal ? mRangeZoomHorzAxis.data() : mRangeZoomVertAxis.data()); +} + +/*! + Returns the range zoom factor of the \a orientation provided. + + \see setRangeZoomFactor +*/ +double QCPAxisRect::rangeZoomFactor(Qt::Orientation orientation) +{ + return (orientation == Qt::Horizontal ? mRangeZoomFactorHorz : mRangeZoomFactorVert); +} + +/*! + Sets which axis orientation may be range dragged by the user with mouse interaction. + What orientation corresponds to which specific axis can be set with + \ref setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical). By + default, the horizontal axis is the bottom axis (xAxis) and the vertical axis + is the left axis (yAxis). + + To disable range dragging entirely, pass 0 as \a orientations or remove \ref QCP::iRangeDrag from \ref + QCustomPlot::setInteractions. To enable range dragging for both directions, pass Qt::Horizontal | + Qt::Vertical as \a orientations. + + In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions + contains \ref QCP::iRangeDrag to enable the range dragging interaction. + + \see setRangeZoom, setRangeDragAxes, setNoAntialiasingOnDrag +*/ +void QCPAxisRect::setRangeDrag(Qt::Orientations orientations) +{ + mRangeDrag = orientations; +} + +/*! + Sets which axis orientation may be zoomed by the user with the mouse wheel. What orientation + corresponds to which specific axis can be set with \ref setRangeZoomAxes(QCPAxis *horizontal, + QCPAxis *vertical). By default, the horizontal axis is the bottom axis (xAxis) and the vertical + axis is the left axis (yAxis). + + To disable range zooming entirely, pass 0 as \a orientations or remove \ref QCP::iRangeZoom from \ref + QCustomPlot::setInteractions. To enable range zooming for both directions, pass Qt::Horizontal | + Qt::Vertical as \a orientations. + + In addition to setting \a orientations to a non-zero value, make sure \ref QCustomPlot::setInteractions + contains \ref QCP::iRangeZoom to enable the range zooming interaction. + + \see setRangeZoomFactor, setRangeZoomAxes, setRangeDrag +*/ +void QCPAxisRect::setRangeZoom(Qt::Orientations orientations) +{ + mRangeZoom = orientations; +} + +/*! + Sets the axes whose range will be dragged when \ref setRangeDrag enables mouse range dragging + on the QCustomPlot widget. + + \see setRangeZoomAxes +*/ +void QCPAxisRect::setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical) +{ + mRangeDragHorzAxis = horizontal; + mRangeDragVertAxis = vertical; +} + +/*! + Sets the axes whose range will be zoomed when \ref setRangeZoom enables mouse wheel zooming on the + QCustomPlot widget. The two axes can be zoomed with different strengths, when different factors + are passed to \ref setRangeZoomFactor(double horizontalFactor, double verticalFactor). + + \see setRangeDragAxes +*/ +void QCPAxisRect::setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical) +{ + mRangeZoomHorzAxis = horizontal; + mRangeZoomVertAxis = vertical; +} + +/*! + Sets how strong one rotation step of the mouse wheel zooms, when range zoom was activated with + \ref setRangeZoom. The two parameters \a horizontalFactor and \a verticalFactor provide a way to + let the horizontal axis zoom at different rates than the vertical axis. Which axis is horizontal + and which is vertical, can be set with \ref setRangeZoomAxes. + + When the zoom factor is greater than one, scrolling the mouse wheel backwards (towards the user) + will zoom in (make the currently visible range smaller). For zoom factors smaller than one, the + same scrolling direction will zoom out. +*/ +void QCPAxisRect::setRangeZoomFactor(double horizontalFactor, double verticalFactor) +{ + mRangeZoomFactorHorz = horizontalFactor; + mRangeZoomFactorVert = verticalFactor; +} + +/*! \overload + + Sets both the horizontal and vertical zoom \a factor. +*/ +void QCPAxisRect::setRangeZoomFactor(double factor) +{ + mRangeZoomFactorHorz = factor; + mRangeZoomFactorVert = factor; +} + +/*! \internal + + Draws the background of this axis rect. It may consist of a background fill (a QBrush) and a + pixmap. + + If a brush was given via \ref setBackground(const QBrush &brush), this function first draws an + according filling inside the axis rect with the provided \a painter. + + Then, if a pixmap was provided via \ref setBackground, this function buffers the scaled version + depending on \ref setBackgroundScaled and \ref setBackgroundScaledMode and then draws it inside + the axis rect with the provided \a painter. The scaled version is buffered in + mScaledBackgroundPixmap to prevent expensive rescaling at every redraw. It is only updated, when + the axis rect has changed in a way that requires a rescale of the background pixmap (this is + dependant on the \ref setBackgroundScaledMode), or when a differend axis backgroud pixmap was + set. + + \see setBackground, setBackgroundScaled, setBackgroundScaledMode +*/ +void QCPAxisRect::drawBackground(QCPPainter *painter) +{ + // draw background fill: + if (mBackgroundBrush != Qt::NoBrush) + painter->fillRect(mRect, mBackgroundBrush); + + // draw background pixmap (on top of fill, if brush specified): + if (!mBackgroundPixmap.isNull()) + { + if (mBackgroundScaled) + { + // check whether mScaledBackground needs to be updated: + QSize scaledSize(mBackgroundPixmap.size()); + scaledSize.scale(mRect.size(), mBackgroundScaledMode); + if (mScaledBackgroundPixmap.size() != scaledSize) + mScaledBackgroundPixmap = mBackgroundPixmap.scaled(mRect.size(), mBackgroundScaledMode, Qt::SmoothTransformation); + painter->drawPixmap(mRect.topLeft(), mScaledBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height()) & mScaledBackgroundPixmap.rect()); + } else + { + painter->drawPixmap(mRect.topLeft(), mBackgroundPixmap, QRect(0, 0, mRect.width(), mRect.height())); + } + } +} + +/*! \internal + + This function makes sure multiple axes on the side specified with \a type don't collide, but are + distributed according to their respective space requirement (QCPAxis::calculateMargin). + + It does this by setting an appropriate offset (\ref QCPAxis::setOffset) on all axes except the + one with index zero. + + This function is called by \ref calculateAutoMargin. +*/ +void QCPAxisRect::updateAxesOffset(QCPAxis::AxisType type) +{ + const QList axesList = mAxes.value(type); + if (axesList.isEmpty()) + return; + + bool isFirstVisible = !axesList.first()->visible(); // if the first axis is visible, the second axis (which is where the loop starts) isn't the first visible axis, so initialize with false + for (int i=1; ioffset() + axesList.at(i-1)->calculateMargin(); + if (axesList.at(i)->visible()) // only add inner tick length to offset if this axis is visible and it's not the first visible one (might happen if true first axis is invisible) + { + if (!isFirstVisible) + offset += axesList.at(i)->tickLengthIn(); + isFirstVisible = false; + } + axesList.at(i)->setOffset(offset); + } +} + +/* inherits documentation from base class */ +int QCPAxisRect::calculateAutoMargin(QCP::MarginSide side) +{ + if (!mAutoMargins.testFlag(side)) + qDebug() << Q_FUNC_INFO << "Called with side that isn't specified as auto margin"; + + updateAxesOffset(QCPAxis::marginSideToAxisType(side)); + + // note: only need to look at the last (outer most) axis to determine the total margin, due to updateAxisOffset call + const QList axesList = mAxes.value(QCPAxis::marginSideToAxisType(side)); + if (axesList.size() > 0) + return axesList.last()->offset() + axesList.last()->calculateMargin(); + else + return 0; +} + +/*! \internal + + Event handler for when a mouse button is pressed on the axis rect. If the left mouse button is + pressed, the range dragging interaction is initialized (the actual range manipulation happens in + the \ref mouseMoveEvent). + + The mDragging flag is set to true and some anchor points are set that are needed to determine the + distance the mouse was dragged in the mouse move/release events later. + + \see mouseMoveEvent, mouseReleaseEvent +*/ +void QCPAxisRect::mousePressEvent(QMouseEvent *event) +{ + mDragStart = event->pos(); // need this even when not LeftButton is pressed, to determine in releaseEvent whether it was a full click (no position change between press and release) + if (event->buttons() & Qt::LeftButton) + { + mDragging = true; + // initialize antialiasing backup in case we start dragging: + if (mParentPlot->noAntialiasingOnDrag()) + { + mAADragBackup = mParentPlot->antialiasedElements(); + mNotAADragBackup = mParentPlot->notAntialiasedElements(); + } + // Mouse range dragging interaction: + if (mParentPlot->interactions().testFlag(QCP::iRangeDrag)) + { + if (mRangeDragHorzAxis) + mDragStartHorzRange = mRangeDragHorzAxis.data()->range(); + if (mRangeDragVertAxis) + mDragStartVertRange = mRangeDragVertAxis.data()->range(); + } + } +} + +/*! \internal + + Event handler for when the mouse is moved on the axis rect. If range dragging was activated in a + preceding \ref mousePressEvent, the range is moved accordingly. + + \see mousePressEvent, mouseReleaseEvent +*/ +void QCPAxisRect::mouseMoveEvent(QMouseEvent *event) +{ + // Mouse range dragging interaction: + if (mDragging && mParentPlot->interactions().testFlag(QCP::iRangeDrag)) + { + if (mRangeDrag.testFlag(Qt::Horizontal)) + { + if (QCPAxis *rangeDragHorzAxis = mRangeDragHorzAxis.data()) + { + if (rangeDragHorzAxis->mScaleType == QCPAxis::stLinear) + { + double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) - rangeDragHorzAxis->pixelToCoord(event->pos().x()); + rangeDragHorzAxis->setRange(mDragStartHorzRange.lower+diff, mDragStartHorzRange.upper+diff); + } else if (rangeDragHorzAxis->mScaleType == QCPAxis::stLogarithmic) + { + double diff = rangeDragHorzAxis->pixelToCoord(mDragStart.x()) / rangeDragHorzAxis->pixelToCoord(event->pos().x()); + rangeDragHorzAxis->setRange(mDragStartHorzRange.lower*diff, mDragStartHorzRange.upper*diff); + } + } + } + if (mRangeDrag.testFlag(Qt::Vertical)) + { + if (QCPAxis *rangeDragVertAxis = mRangeDragVertAxis.data()) + { + if (rangeDragVertAxis->mScaleType == QCPAxis::stLinear) + { + double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) - rangeDragVertAxis->pixelToCoord(event->pos().y()); + rangeDragVertAxis->setRange(mDragStartVertRange.lower+diff, mDragStartVertRange.upper+diff); + } else if (rangeDragVertAxis->mScaleType == QCPAxis::stLogarithmic) + { + double diff = rangeDragVertAxis->pixelToCoord(mDragStart.y()) / rangeDragVertAxis->pixelToCoord(event->pos().y()); + rangeDragVertAxis->setRange(mDragStartVertRange.lower*diff, mDragStartVertRange.upper*diff); + } + } + } + if (mRangeDrag != 0) // if either vertical or horizontal drag was enabled, do a replot + { + if (mParentPlot->noAntialiasingOnDrag()) + mParentPlot->setNotAntialiasedElements(QCP::aeAll); + mParentPlot->replot(); + } + } +} + +/* inherits documentation from base class */ +void QCPAxisRect::mouseReleaseEvent(QMouseEvent *event) +{ + Q_UNUSED(event) + mDragging = false; + if (mParentPlot->noAntialiasingOnDrag()) + { + mParentPlot->setAntialiasedElements(mAADragBackup); + mParentPlot->setNotAntialiasedElements(mNotAADragBackup); + } +} + +/*! \internal + + Event handler for mouse wheel events. If rangeZoom is Qt::Horizontal, Qt::Vertical or both, the + ranges of the axes defined as rangeZoomHorzAxis and rangeZoomVertAxis are scaled. The center of + the scaling operation is the current cursor position inside the axis rect. The scaling factor is + dependant on the mouse wheel delta (which direction the wheel was rotated) to provide a natural + zooming feel. The Strength of the zoom can be controlled via \ref setRangeZoomFactor. + + Note, that event->delta() is usually +/-120 for single rotation steps. However, if the mouse + wheel is turned rapidly, many steps may bunch up to one event, so the event->delta() may then be + multiples of 120. This is taken into account here, by calculating \a wheelSteps and using it as + exponent of the range zoom factor. This takes care of the wheel direction automatically, by + inverting the factor, when the wheel step is negative (f^-1 = 1/f). +*/ +void QCPAxisRect::wheelEvent(QWheelEvent *event) +{ + // Mouse range zooming interaction: + if (mParentPlot->interactions().testFlag(QCP::iRangeZoom)) + { + if (mRangeZoom != 0) + { + double factor; + double wheelSteps = event->delta()/120.0; // a single step delta is +/-120 usually + if (mRangeZoom.testFlag(Qt::Horizontal)) + { + factor = qPow(mRangeZoomFactorHorz, wheelSteps); + if (mRangeZoomHorzAxis.data()) + mRangeZoomHorzAxis.data()->scaleRange(factor, mRangeZoomHorzAxis.data()->pixelToCoord(event->pos().x())); + } + if (mRangeZoom.testFlag(Qt::Vertical)) + { + factor = qPow(mRangeZoomFactorVert, wheelSteps); + if (mRangeZoomVertAxis.data()) + mRangeZoomVertAxis.data()->scaleRange(factor, mRangeZoomVertAxis.data()->pixelToCoord(event->pos().y())); + } + mParentPlot->replot(); + } + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPAbstractLegendItem +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPAbstractLegendItem + \brief The abstract base class for all entries in a QCPLegend. + + It defines a very basic interface for entries in a QCPLegend. For representing plottables in the + legend, the subclass \ref QCPPlottableLegendItem is more suitable. + + Only derive directly from this class when you need absolute freedom (e.g. a custom legend entry + that's not even associated with a plottable). + + You must implement the following pure virtual functions: + \li \ref draw (from QCPLayerable) + + You inherit the following members you may use: + + + + + + + + +
QCPLegend *\b mParentLegendA pointer to the parent QCPLegend.
QFont \b mFontThe generic font of the item. You should use this font for all or at least the most prominent text of the item.
+*/ + +/* start of documentation of signals */ + +/*! \fn void QCPAbstractLegendItem::selectionChanged(bool selected) + + This signal is emitted when the selection state of this legend item has changed, either by user + interaction or by a direct call to \ref setSelected. +*/ + +/* end of documentation of signals */ + +/*! + Constructs a QCPAbstractLegendItem and associates it with the QCPLegend \a parent. This does not + cause the item to be added to \a parent, so \ref QCPLegend::addItem must be called separately. +*/ +QCPAbstractLegendItem::QCPAbstractLegendItem(QCPLegend *parent) : + QCPLayoutElement(parent->parentPlot()), + mParentLegend(parent), + mFont(parent->font()), + mTextColor(parent->textColor()), + mSelectedFont(parent->selectedFont()), + mSelectedTextColor(parent->selectedTextColor()), + mSelectable(true), + mSelected(false) +{ + setLayer("legend"); + setMargins(QMargins(8, 2, 8, 2)); +} + +/*! + Sets the default font of this specific legend item to \a font. + + \see setTextColor, QCPLegend::setFont +*/ +void QCPAbstractLegendItem::setFont(const QFont &font) +{ + mFont = font; +} + +/*! + Sets the default text color of this specific legend item to \a color. + + \see setFont, QCPLegend::setTextColor +*/ +void QCPAbstractLegendItem::setTextColor(const QColor &color) +{ + mTextColor = color; +} + +/*! + When this legend item is selected, \a font is used to draw generic text, instead of the normal + font set with \ref setFont. + + \see setFont, QCPLegend::setSelectedFont +*/ +void QCPAbstractLegendItem::setSelectedFont(const QFont &font) +{ + mSelectedFont = font; +} + +/*! + When this legend item is selected, \a color is used to draw generic text, instead of the normal + color set with \ref setTextColor. + + \see setTextColor, QCPLegend::setSelectedTextColor +*/ +void QCPAbstractLegendItem::setSelectedTextColor(const QColor &color) +{ + mSelectedTextColor = color; +} + +/*! + Sets whether this specific legend item is selectable. + + \see setSelectedParts, QCustomPlot::setInteractions +*/ +void QCPAbstractLegendItem::setSelectable(bool selectable) +{ + if (mSelectable != selectable) + { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } +} + +/*! + Sets whether this specific legend item is selected. + + It is possible to set the selection state of this item by calling this function directly, even if + setSelectable is set to false. + + \see setSelectableParts, QCustomPlot::setInteractions +*/ +void QCPAbstractLegendItem::setSelected(bool selected) +{ + if (mSelected != selected) + { + mSelected = selected; + emit selectionChanged(mSelected); + } +} + +/* inherits documentation from base class */ +double QCPAbstractLegendItem::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (!mParentPlot) return -1; + if (onlySelectable && (!mSelectable || !mParentLegend->selectableParts().testFlag(QCPLegend::spItems))) + return -1; + + if (mRect.contains(pos.toPoint())) + return mParentPlot->selectionTolerance()*0.99; + else + return -1; +} + +/* inherits documentation from base class */ +void QCPAbstractLegendItem::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiased, QCP::aeLegendItems); +} + +/* inherits documentation from base class */ +QRect QCPAbstractLegendItem::clipRect() const +{ + return mOuterRect; +} + +/* inherits documentation from base class */ +void QCPAbstractLegendItem::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +{ + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) + { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + +/* inherits documentation from base class */ +void QCPAbstractLegendItem::deselectEvent(bool *selectionStateChanged) +{ + if (mSelectable && mParentLegend->selectableParts().testFlag(QCPLegend::spItems)) + { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPPlottableLegendItem +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPPlottableLegendItem + \brief A legend item representing a plottable with an icon and the plottable name. + + This is the standard legend item for plottables. It displays an icon of the plottable next to the + plottable name. The icon is drawn by the respective plottable itself (\ref + QCPAbstractPlottable::drawLegendIcon), and tries to give an intuitive symbol for the plottable. + For example, the QCPGraph draws a centered horizontal line and/or a single scatter point in the + middle. + + Legend items of this type are always associated with one plottable (retrievable via the + plottable() function and settable with the constructor). You may change the font of the plottable + name with \ref setFont. Icon padding and border pen is taken from the parent QCPLegend, see \ref + QCPLegend::setIconBorderPen and \ref QCPLegend::setIconTextPadding. + + The function \ref QCPAbstractPlottable::addToLegend/\ref QCPAbstractPlottable::removeFromLegend + creates/removes legend items of this type in the default implementation. However, these functions + may be reimplemented such that a different kind of legend item (e.g a direct subclass of + QCPAbstractLegendItem) is used for that plottable. + + Since QCPLegend is based on QCPLayoutGrid, a legend item itself is just a subclass of + QCPLayoutElement. While it could be added to a legend (or any other layout) via the normal layout + interface, QCPLegend has specialized functions for handling legend items conveniently, see the + documentation of \ref QCPLegend. +*/ + +/*! + Creates a new legend item associated with \a plottable. + + Once it's created, it can be added to the legend via \ref QCPLegend::addItem. + + A more convenient way of adding/removing a plottable to/from the legend is via the functions \ref + QCPAbstractPlottable::addToLegend and \ref QCPAbstractPlottable::removeFromLegend. +*/ +QCPPlottableLegendItem::QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable) : + QCPAbstractLegendItem(parent), + mPlottable(plottable) +{ +} + +/*! \internal + + Returns the pen that shall be used to draw the icon border, taking into account the selection + state of this item. +*/ +QPen QCPPlottableLegendItem::getIconBorderPen() const +{ + return mSelected ? mParentLegend->selectedIconBorderPen() : mParentLegend->iconBorderPen(); +} + +/*! \internal + + Returns the text color that shall be used to draw text, taking into account the selection state + of this item. +*/ +QColor QCPPlottableLegendItem::getTextColor() const +{ + return mSelected ? mSelectedTextColor : mTextColor; +} + +/*! \internal + + Returns the font that shall be used to draw text, taking into account the selection state of this + item. +*/ +QFont QCPPlottableLegendItem::getFont() const +{ + return mSelected ? mSelectedFont : mFont; +} + +/*! \internal + + Draws the item with \a painter. The size and position of the drawn legend item is defined by the + parent layout (typically a \ref QCPLegend) and the \ref minimumSizeHint and \ref maximumSizeHint + of this legend item. +*/ +void QCPPlottableLegendItem::draw(QCPPainter *painter) +{ + if (!mPlottable) return; + painter->setFont(getFont()); + painter->setPen(QPen(getTextColor())); + QSizeF iconSize = mParentLegend->iconSize(); + QRectF textRect = painter->fontMetrics().boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); + QRectF iconRect(mRect.topLeft(), iconSize); + int textHeight = qMax(textRect.height(), iconSize.height()); // if text has smaller height than icon, center text vertically in icon height, else align tops + painter->drawText(mRect.x()+iconSize.width()+mParentLegend->iconTextPadding(), mRect.y(), textRect.width(), textHeight, Qt::TextDontClip, mPlottable->name()); + // draw icon: + painter->save(); + painter->setClipRect(iconRect, Qt::IntersectClip); + mPlottable->drawLegendIcon(painter, iconRect); + painter->restore(); + // draw icon border: + if (getIconBorderPen().style() != Qt::NoPen) + { + painter->setPen(getIconBorderPen()); + painter->setBrush(Qt::NoBrush); + painter->drawRect(iconRect); + } +} + +/*! \internal + + Calculates and returns the size of this item. This includes the icon, the text and the padding in + between. +*/ +QSize QCPPlottableLegendItem::minimumSizeHint() const +{ + if (!mPlottable) return QSize(); + QSize result(0, 0); + QRect textRect; + QFontMetrics fontMetrics(getFont()); + QSize iconSize = mParentLegend->iconSize(); + textRect = fontMetrics.boundingRect(0, 0, 0, iconSize.height(), Qt::TextDontClip, mPlottable->name()); + result.setWidth(iconSize.width() + mParentLegend->iconTextPadding() + textRect.width() + mMargins.left() + mMargins.right()); + result.setHeight(qMax(textRect.height(), iconSize.height()) + mMargins.top() + mMargins.bottom()); + return result; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPLegend +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPLegend + \brief Manages a legend inside a QCustomPlot. + + A legend is a small box somewhere in the plot which lists plottables with their name and icon. + + Normally, the legend is populated by calling \ref QCPAbstractPlottable::addToLegend. The + respective legend item can be removed with \ref QCPAbstractPlottable::removeFromLegend. However, + QCPLegend also offers an interface to add and manipulate legend items directly: \ref item, \ref + itemWithPlottable, \ref itemCount, \ref addItem, \ref removeItem, etc. + + The QCPLegend derives from QCPLayoutGrid and as such can be placed in any position a + QCPLayoutElement may be positioned. The legend items are themselves QCPLayoutElements which are + placed in the grid layout of the legend. QCPLegend only adds an interface specialized for + handling child elements of type QCPAbstractLegendItem, as mentioned above. In principle, any + other layout elements may also be added to a legend via the normal \ref QCPLayoutGrid interface. + However, the QCPAbstractLegendItem-Interface will ignore those elements (e.g. \ref itemCount will + only return the number of items with QCPAbstractLegendItems type). + + By default, every QCustomPlot has one legend (QCustomPlot::legend) which is placed in the inset + layout of the main axis rect (\ref QCPAxisRect::insetLayout). To move the legend to another + position inside the axis rect, use the methods of the \ref QCPLayoutInset. To move the legend + outside of the axis rect, place it anywhere else with the QCPLayout/QCPLayoutElement interface. +*/ + +/* start of documentation of signals */ + +/*! \fn void QCPLegend::selectionChanged(QCPLegend::SelectableParts selection); + + This signal is emitted when the selection state of this legend has changed. + + \see setSelectedParts, setSelectableParts +*/ + +/* end of documentation of signals */ + +/*! + Constructs a new QCPLegend instance with \a parentPlot as the containing plot and default values. + + Note that by default, QCustomPlot already contains a legend ready to be used as + QCustomPlot::legend +*/ +QCPLegend::QCPLegend() +{ + setRowSpacing(0); + setColumnSpacing(10); + setMargins(QMargins(2, 3, 2, 2)); + setAntialiased(false); + setIconSize(32, 18); + + setIconTextPadding(7); + + setSelectableParts(spLegendBox | spItems); + setSelectedParts(spNone); + + setBorderPen(QPen(Qt::black)); + setSelectedBorderPen(QPen(Qt::blue, 2)); + setIconBorderPen(Qt::NoPen); + setSelectedIconBorderPen(QPen(Qt::blue, 2)); + setBrush(Qt::white); + setSelectedBrush(Qt::white); + setTextColor(Qt::black); + setSelectedTextColor(Qt::blue); +} + +QCPLegend::~QCPLegend() +{ + clearItems(); + if (qobject_cast(mParentPlot)) // make sure this isn't called from QObject dtor when QCustomPlot is already destructed (happens when the legend is not in any layout and thus QObject-child of QCustomPlot) + mParentPlot->legendRemoved(this); +} + +/* no doc for getter, see setSelectedParts */ +QCPLegend::SelectableParts QCPLegend::selectedParts() const +{ + // check whether any legend elements selected, if yes, add spItems to return value + bool hasSelectedItems = false; + for (int i=0; iselected()) + { + hasSelectedItems = true; + break; + } + } + if (hasSelectedItems) + return mSelectedParts | spItems; + else + return mSelectedParts & ~spItems; +} + +/*! + Sets the pen, the border of the entire legend is drawn with. +*/ +void QCPLegend::setBorderPen(const QPen &pen) +{ + mBorderPen = pen; +} + +/*! + Sets the brush of the legend background. +*/ +void QCPLegend::setBrush(const QBrush &brush) +{ + mBrush = brush; +} + +/*! + Sets the default font of legend text. Legend items that draw text (e.g. the name of a graph) will + use this font by default. However, a different font can be specified on a per-item-basis by + accessing the specific legend item. + + This function will also set \a font on all already existing legend items. + + \see QCPAbstractLegendItem::setFont +*/ +void QCPLegend::setFont(const QFont &font) +{ + mFont = font; + for (int i=0; isetFont(mFont); + } +} + +/*! + Sets the default color of legend text. Legend items that draw text (e.g. the name of a graph) + will use this color by default. However, a different colors can be specified on a per-item-basis + by accessing the specific legend item. + + This function will also set \a color on all already existing legend items. + + \see QCPAbstractLegendItem::setTextColor +*/ +void QCPLegend::setTextColor(const QColor &color) +{ + mTextColor = color; + for (int i=0; isetTextColor(color); + } +} + +/*! + Sets the size of legend icons. Legend items that draw an icon (e.g. a visual + representation of the graph) will use this size by default. +*/ +void QCPLegend::setIconSize(const QSize &size) +{ + mIconSize = size; +} + +/*! \overload +*/ +void QCPLegend::setIconSize(int width, int height) +{ + mIconSize.setWidth(width); + mIconSize.setHeight(height); +} + +/*! + Sets the horizontal space in pixels between the legend icon and the text next to it. + Legend items that draw an icon (e.g. a visual representation of the graph) and text (e.g. the + name of the graph) will use this space by default. +*/ +void QCPLegend::setIconTextPadding(int padding) +{ + mIconTextPadding = padding; +} + +/*! + Sets the pen used to draw a border around each legend icon. Legend items that draw an + icon (e.g. a visual representation of the graph) will use this pen by default. + + If no border is wanted, set this to \a Qt::NoPen. +*/ +void QCPLegend::setIconBorderPen(const QPen &pen) +{ + mIconBorderPen = pen; +} + +/*! + Sets whether the user can (de-)select the parts in \a selectable by clicking on the QCustomPlot surface. + (When \ref QCustomPlot::setInteractions contains \ref QCP::iSelectLegend.) + + However, even when \a selectable is set to a value not allowing the selection of a specific part, + it is still possible to set the selection of this part manually, by calling \ref setSelectedParts + directly. + + \see SelectablePart, setSelectedParts +*/ +void QCPLegend::setSelectableParts(const SelectableParts &selectable) +{ + if (mSelectableParts != selectable) + { + mSelectableParts = selectable; + emit selectableChanged(mSelectableParts); + } +} + +/*! + Sets the selected state of the respective legend parts described by \ref SelectablePart. When a part + is selected, it uses a different pen/font and brush. If some legend items are selected and \a selected + doesn't contain \ref spItems, those items become deselected. + + The entire selection mechanism is handled automatically when \ref QCustomPlot::setInteractions + contains iSelectLegend. You only need to call this function when you wish to change the selection + state manually. + + This function can change the selection state of a part even when \ref setSelectableParts was set to a + value that actually excludes the part. + + emits the \ref selectionChanged signal when \a selected is different from the previous selection state. + + Note that it doesn't make sense to set the selected state \ref spItems here when it wasn't set + before, because there's no way to specify which exact items to newly select. Do this by calling + \ref QCPAbstractLegendItem::setSelected directly on the legend item you wish to select. + + \see SelectablePart, setSelectableParts, selectTest, setSelectedBorderPen, setSelectedIconBorderPen, setSelectedBrush, + setSelectedFont +*/ +void QCPLegend::setSelectedParts(const SelectableParts &selected) +{ + SelectableParts newSelected = selected; + mSelectedParts = this->selectedParts(); // update mSelectedParts in case item selection changed + + if (mSelectedParts != newSelected) + { + if (!mSelectedParts.testFlag(spItems) && newSelected.testFlag(spItems)) // attempt to set spItems flag (can't do that) + { + qDebug() << Q_FUNC_INFO << "spItems flag can not be set, it can only be unset with this function"; + newSelected &= ~spItems; + } + if (mSelectedParts.testFlag(spItems) && !newSelected.testFlag(spItems)) // spItems flag was unset, so clear item selection + { + for (int i=0; isetSelected(false); + } + } + mSelectedParts = newSelected; + emit selectionChanged(mSelectedParts); + } +} + +/*! + When the legend box is selected, this pen is used to draw the border instead of the normal pen + set via \ref setBorderPen. + + \see setSelectedParts, setSelectableParts, setSelectedBrush +*/ +void QCPLegend::setSelectedBorderPen(const QPen &pen) +{ + mSelectedBorderPen = pen; +} + +/*! + Sets the pen legend items will use to draw their icon borders, when they are selected. + + \see setSelectedParts, setSelectableParts, setSelectedFont +*/ +void QCPLegend::setSelectedIconBorderPen(const QPen &pen) +{ + mSelectedIconBorderPen = pen; +} + +/*! + When the legend box is selected, this brush is used to draw the legend background instead of the normal brush + set via \ref setBrush. + + \see setSelectedParts, setSelectableParts, setSelectedBorderPen +*/ +void QCPLegend::setSelectedBrush(const QBrush &brush) +{ + mSelectedBrush = brush; +} + +/*! + Sets the default font that is used by legend items when they are selected. + + This function will also set \a font on all already existing legend items. + + \see setFont, QCPAbstractLegendItem::setSelectedFont +*/ +void QCPLegend::setSelectedFont(const QFont &font) +{ + mSelectedFont = font; + for (int i=0; isetSelectedFont(font); + } +} + +/*! + Sets the default text color that is used by legend items when they are selected. + + This function will also set \a color on all already existing legend items. + + \see setTextColor, QCPAbstractLegendItem::setSelectedTextColor +*/ +void QCPLegend::setSelectedTextColor(const QColor &color) +{ + mSelectedTextColor = color; + for (int i=0; isetSelectedTextColor(color); + } +} + +/*! + Returns the item with index \a i. + + \see itemCount +*/ +QCPAbstractLegendItem *QCPLegend::item(int index) const +{ + return qobject_cast(elementAt(index)); +} + +/*! + Returns the QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). + If such an item isn't in the legend, returns 0. + + \see hasItemWithPlottable +*/ +QCPPlottableLegendItem *QCPLegend::itemWithPlottable(const QCPAbstractPlottable *plottable) const +{ + for (int i=0; i(item(i))) + { + if (pli->plottable() == plottable) + return pli; + } + } + return 0; +} + +/*! + Returns the number of items currently in the legend. + \see item +*/ +int QCPLegend::itemCount() const +{ + return elementCount(); +} + +/*! + Returns whether the legend contains \a itm. +*/ +bool QCPLegend::hasItem(QCPAbstractLegendItem *item) const +{ + for (int i=0; iitem(i)) + return true; + } + return false; +} + +/*! + Returns whether the legend contains a QCPPlottableLegendItem which is associated with \a plottable (e.g. a \ref QCPGraph*). + If such an item isn't in the legend, returns false. + + \see itemWithPlottable +*/ +bool QCPLegend::hasItemWithPlottable(const QCPAbstractPlottable *plottable) const +{ + return itemWithPlottable(plottable); +} + +/*! + Adds \a item to the legend, if it's not present already. + + Returns true on sucess, i.e. if the item wasn't in the list already and has been successfuly added. + + The legend takes ownership of the item. +*/ +bool QCPLegend::addItem(QCPAbstractLegendItem *item) +{ + if (!hasItem(item)) + { + return addElement(rowCount(), 0, item); + } else + return false; +} + +/*! + Removes the item with index \a index from the legend. + + Returns true, if successful. + + \see itemCount, clearItems +*/ +bool QCPLegend::removeItem(int index) +{ + if (QCPAbstractLegendItem *ali = item(index)) + { + bool success = remove(ali); + simplify(); + return success; + } else + return false; +} + +/*! \overload + + Removes \a item from the legend. + + Returns true, if successful. + + \see clearItems +*/ +bool QCPLegend::removeItem(QCPAbstractLegendItem *item) +{ + bool success = remove(item); + simplify(); + return success; +} + +/*! + Removes all items from the legend. +*/ +void QCPLegend::clearItems() +{ + for (int i=itemCount()-1; i>=0; --i) + removeItem(i); +} + +/*! + Returns the legend items that are currently selected. If no items are selected, + the list is empty. + + \see QCPAbstractLegendItem::setSelected, setSelectable +*/ +QList QCPLegend::selectedItems() const +{ + QList result; + for (int i=0; iselected()) + result.append(ali); + } + } + return result; +} + +/*! \internal + + A convenience function to easily set the QPainter::Antialiased hint on the provided \a painter + before drawing main legend elements. + + This is the antialiasing state the painter passed to the \ref draw method is in by default. + + This function takes into account the local setting of the antialiasing flag as well as the + overrides set with \ref QCustomPlot::setAntialiasedElements and \ref + QCustomPlot::setNotAntialiasedElements. + + \see setAntialiased +*/ +void QCPLegend::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiased, QCP::aeLegend); +} + +/*! \internal + + Returns the pen used to paint the border of the legend, taking into account the selection state + of the legend box. +*/ +QPen QCPLegend::getBorderPen() const +{ + return mSelectedParts.testFlag(spLegendBox) ? mSelectedBorderPen : mBorderPen; +} + +/*! \internal + + Returns the brush used to paint the background of the legend, taking into account the selection + state of the legend box. +*/ +QBrush QCPLegend::getBrush() const +{ + return mSelectedParts.testFlag(spLegendBox) ? mSelectedBrush : mBrush; +} + +/*! \internal + + Draws the legend box with the provided \a painter. The individual legend items are layerables + themselves, thus are drawn independently. +*/ +void QCPLegend::draw(QCPPainter *painter) +{ + // draw background rect: + painter->setBrush(getBrush()); + painter->setPen(getBorderPen()); + painter->drawRect(mOuterRect); +} + +/* inherits documentation from base class */ +double QCPLegend::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + if (!mParentPlot) return -1; + if (onlySelectable && !mSelectableParts.testFlag(spLegendBox)) + return -1; + + if (mOuterRect.contains(pos.toPoint())) + { + if (details) details->setValue(spLegendBox); + return mParentPlot->selectionTolerance()*0.99; + } + return -1; +} + +/* inherits documentation from base class */ +void QCPLegend::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +{ + Q_UNUSED(event) + mSelectedParts = selectedParts(); // in case item selection has changed + if (details.value() == spLegendBox && mSelectableParts.testFlag(spLegendBox)) + { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(additive ? mSelectedParts^spLegendBox : mSelectedParts|spLegendBox); // no need to unset spItems in !additive case, because they will be deselected by QCustomPlot (they're normal QCPLayerables with own deselectEvent) + if (selectionStateChanged) + *selectionStateChanged = mSelectedParts != selBefore; + } +} + +/* inherits documentation from base class */ +void QCPLegend::deselectEvent(bool *selectionStateChanged) +{ + mSelectedParts = selectedParts(); // in case item selection has changed + if (mSelectableParts.testFlag(spLegendBox)) + { + SelectableParts selBefore = mSelectedParts; + setSelectedParts(selectedParts() & ~spLegendBox); + if (selectionStateChanged) + *selectionStateChanged = mSelectedParts != selBefore; + } +} + +/* inherits documentation from base class */ +QCP::Interaction QCPLegend::selectionCategory() const +{ + return QCP::iSelectLegend; +} + +/* inherits documentation from base class */ +QCP::Interaction QCPAbstractLegendItem::selectionCategory() const +{ + return QCP::iSelectLegend; +} + +/* inherits documentation from base class */ +void QCPLegend::parentPlotInitialized(QCustomPlot *parentPlot) +{ + Q_UNUSED(parentPlot) +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPPlotTitle +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPPlotTitle + \brief A layout element displaying a plot title text + + The text may be specified with \ref setText, theformatting can be controlled with \ref setFont + and \ref setTextColor. + + A plot title can be added as follows: + \code + customPlot->plotLayout()->insertRow(0); // inserts an empty row above the default axis rect + customPlot->plotLayout()->addElement(0, 0, new QCPPlotTitle(customPlot, "Your Plot Title")); + \endcode + + Since a plot title is a common requirement, QCustomPlot offers specialized selection signals for + easy interaction with QCPPlotTitle. If a layout element of type QCPPlotTitle is clicked, the + signal \ref QCustomPlot::titleClick is emitted. A double click emits the \ref + QCustomPlot::titleDoubleClick signal. +*/ + +/* start documentation of signals */ + +/*! \fn void QCPPlotTitle::selectionChanged(bool selected) + + This signal is emitted when the selection state has changed to \a selected, either by user + interaction or by a direct call to \ref setSelected. + + \see setSelected, setSelectable +*/ + +/* end documentation of signals */ + +/*! + Creates a new QCPPlotTitle instance and sets default values. The initial text is empty (\ref setText). + + To set the title text in the constructor, rather use \ref QCPPlotTitle(QCustomPlot *parentPlot, const QString &text). +*/ +QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot) : + QCPLayoutElement(parentPlot), + mFont(QFont("sans serif", 13*1.5, QFont::Bold)), + mTextColor(Qt::black), + mSelectedFont(QFont("sans serif", 13*1.6, QFont::Bold)), + mSelectedTextColor(Qt::blue), + mSelectable(false), + mSelected(false) +{ + if (parentPlot) + { + setLayer(parentPlot->currentLayer()); + mFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold); + mSelectedFont = QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold); + } + setMargins(QMargins(5, 5, 5, 0)); +} + +/*! \overload + + Creates a new QCPPlotTitle instance and sets default values. The initial text is set to \a text. +*/ +QCPPlotTitle::QCPPlotTitle(QCustomPlot *parentPlot, const QString &text) : + QCPLayoutElement(parentPlot), + mText(text), + mFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.5, QFont::Bold)), + mTextColor(Qt::black), + mSelectedFont(QFont(parentPlot->font().family(), parentPlot->font().pointSize()*1.6, QFont::Bold)), + mSelectedTextColor(Qt::blue), + mSelectable(false), + mSelected(false) +{ + setLayer("axes"); + setMargins(QMargins(5, 5, 5, 0)); +} + +/*! + Sets the text that will be displayed to \a text. Multiple lines can be created by insertion of "\n". + + \see setFont, setTextColor +*/ +void QCPPlotTitle::setText(const QString &text) +{ + mText = text; +} + +/*! + Sets the \a font of the title text. + + \see setTextColor, setSelectedFont +*/ +void QCPPlotTitle::setFont(const QFont &font) +{ + mFont = font; +} + +/*! + Sets the \a color of the title text. + + \see setFont, setSelectedTextColor +*/ +void QCPPlotTitle::setTextColor(const QColor &color) +{ + mTextColor = color; +} + +/*! + Sets the \a font of the title text that will be used if the plot title is selected (\ref setSelected). + + \see setFont +*/ +void QCPPlotTitle::setSelectedFont(const QFont &font) +{ + mSelectedFont = font; +} + +/*! + Sets the \a color of the title text that will be used if the plot title is selected (\ref setSelected). + + \see setTextColor +*/ +void QCPPlotTitle::setSelectedTextColor(const QColor &color) +{ + mSelectedTextColor = color; +} + +/*! + Sets whether the user may select this plot title to \a selectable. + + Note that even when \a selectable is set to false, the selection state may be changed + programmatically via \ref setSelected. +*/ +void QCPPlotTitle::setSelectable(bool selectable) +{ + if (mSelectable != selectable) + { + mSelectable = selectable; + emit selectableChanged(mSelectable); + } +} + +/*! + Sets the selection state of this plot title to \a selected. If the selection has changed, \ref + selectionChanged is emitted. + + Note that this function can change the selection state independently of the current \ref + setSelectable state. +*/ +void QCPPlotTitle::setSelected(bool selected) +{ + if (mSelected != selected) + { + mSelected = selected; + emit selectionChanged(mSelected); + } +} + +/* inherits documentation from base class */ +void QCPPlotTitle::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + applyAntialiasingHint(painter, mAntialiased, QCP::aeNone); +} + +/* inherits documentation from base class */ +void QCPPlotTitle::draw(QCPPainter *painter) +{ + painter->setFont(mainFont()); + painter->setPen(QPen(mainTextColor())); + painter->drawText(mRect, Qt::AlignCenter, mText, &mTextBoundingRect); +} + +/* inherits documentation from base class */ +QSize QCPPlotTitle::minimumSizeHint() const +{ + QFontMetrics metrics(mFont); + QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); + result.rwidth() += mMargins.left() + mMargins.right(); + result.rheight() += mMargins.top() + mMargins.bottom(); + return result; +} + +/* inherits documentation from base class */ +QSize QCPPlotTitle::maximumSizeHint() const +{ + QFontMetrics metrics(mFont); + QSize result = metrics.boundingRect(0, 0, 0, 0, Qt::AlignCenter, mText).size(); + result.rheight() += mMargins.top() + mMargins.bottom(); + result.setWidth(QWIDGETSIZE_MAX); + return result; +} + +/* inherits documentation from base class */ +void QCPPlotTitle::selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged) +{ + Q_UNUSED(event) + Q_UNUSED(details) + if (mSelectable) + { + bool selBefore = mSelected; + setSelected(additive ? !mSelected : true); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + +/* inherits documentation from base class */ +void QCPPlotTitle::deselectEvent(bool *selectionStateChanged) +{ + if (mSelectable) + { + bool selBefore = mSelected; + setSelected(false); + if (selectionStateChanged) + *selectionStateChanged = mSelected != selBefore; + } +} + +/* inherits documentation from base class */ +double QCPPlotTitle::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + if (mTextBoundingRect.contains(pos.toPoint())) + return mParentPlot->selectionTolerance()*0.99; + else + return -1; +} + +/*! \internal + + Returns the main font to be used. This is mSelectedFont if \ref setSelected is set to + true, else mFont is returned. +*/ +QFont QCPPlotTitle::mainFont() const +{ + return mSelected ? mSelectedFont : mFont; +} + +/*! \internal + + Returns the main color to be used. This is mSelectedTextColor if \ref setSelected is set to + true, else mTextColor is returned. +*/ +QColor QCPPlotTitle::mainTextColor() const +{ + return mSelected ? mSelectedTextColor : mTextColor; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPColorScale +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPColorScale + \brief A color scale for use with color coding data such as QCPColorMap + + This layout element can be placed on the plot to correlate a color gradient with data values. It + is usually used in combination with one or multiple \ref QCPColorMap "QCPColorMaps". + + \image html QCPColorScale.png + + The color scale can be either horizontal or vertical, as shown in the image above. The + orientation and the side where the numbers appear is controlled with \ref setType. + + Use \ref QCPColorMap::setColorScale to connect a color map with a color scale. Once they are + connected, they share their gradient, data range and data scale type (\ref setGradient, \ref + setDataRange, \ref setDataScaleType). Multiple color maps may be associated with a single color + scale, to make them all synchronize these properties. + + To have finer control over the number display and axis behaviour, you can directly access the + \ref axis. See the documentation of QCPAxis for details about configuring axes. For example, if + you want to change the number of automatically generated ticks, call + \code + colorScale->axis()->setAutoTickCount(3); + \endcode + + Placing a color scale next to the main axis rect works like with any other layout element: + \code + QCPColorScale *colorScale = new QCPColorScale(customPlot); + customPlot->plotLayout()->addElement(0, 1, colorScale); + colorScale->setLabel("Some Label Text"); + \endcode + In this case we have placed it to the right of the default axis rect, so it wasn't necessary to + call \ref setType, since \ref QCPAxis::atRight is already the default. The text next to the color + scale can be set with \ref setLabel. + + For optimum appearance (like in the image above), it may be desirable to line up the axis rect and + the borders of the color scale. Use a \ref QCPMarginGroup to achieve this: + \code + QCPMarginGroup *group = new QCPMarginGroup(customPlot); + colorScale->setMarginGroup(QCP::msTop|QCP::msBottom, group); + customPlot->axisRect()->setMarginGroup(QCP::msTop|QCP::msBottom, group); + \endcode + + Color scales are initialized with a non-zero minimum top and bottom margin (\ref + setMinimumMargins), because vertical color scales are most common and the minimum top/bottom + margin makes sure it keeps some distance to the top/bottom widget border. So if you change to a + horizontal color scale by setting \ref setType to \ref QCPAxis::atBottom or \ref QCPAxis::atTop, you + might want to also change the minimum margins accordingly, e.g. \ref + setMinimumMargins(QMargins(6, 0, 6, 0)). +*/ + +/* start documentation of inline functions */ + +/*! \fn QCPAxis *QCPColorScale::axis() const + + Returns the internal \ref QCPAxis instance of this color scale. You can access it to alter the + appearance and behaviour of the axis. \ref QCPColorScale duplicates some properties in its + interface for convenience. Those are \ref setDataRange (\ref QCPAxis::setRange), \ref + setDataScaleType (\ref QCPAxis::setScaleType), and the method \ref setLabel (\ref + QCPAxis::setLabel). As they each are connected, it does not matter whether you use the method on + the QCPColorScale or on its QCPAxis. + + If the type of the color scale is changed with \ref setType, the axis returned by this method + will change, too, to either the left, right, bottom or top axis, depending on which type was set. +*/ + +/* end documentation of signals */ +/* start documentation of signals */ + +/*! \fn void QCPColorScale::dataRangeChanged(QCPRange newRange); + + This signal is emitted when the data range changes. + + \see setDataRange +*/ + +/*! \fn void QCPColorScale::dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + + This signal is emitted when the data scale type changes. + + \see setDataScaleType +*/ + +/*! \fn void QCPColorScale::gradientChanged(QCPColorGradient newGradient); + + This signal is emitted when the gradient changes. + + \see setGradient +*/ + +/* end documentation of signals */ + +/*! + Constructs a new QCPColorScale. +*/ +QCPColorScale::QCPColorScale(QCustomPlot *parentPlot) : + QCPLayoutElement(parentPlot), + mType(QCPAxis::atTop), // set to atTop such that setType(QCPAxis::atRight) below doesn't skip work because it thinks it's already atRight + mDataScaleType(QCPAxis::stLinear), + mBarWidth(20), + mAxisRect(new QCPColorScaleAxisRectPrivate(this)) +{ + setMinimumMargins(QMargins(0, 6, 0, 6)); // for default right color scale types, keep some room at bottom and top (important if no margin group is used) + setType(QCPAxis::atRight); + setDataRange(QCPRange(0, 6)); +} + +QCPColorScale::~QCPColorScale() +{ + delete mAxisRect; +} + +/* undocumented getter */ +QString QCPColorScale::label() const +{ + if (!mColorAxis) + { + qDebug() << Q_FUNC_INFO << "internal color axis undefined"; + return QString(); + } + + return mColorAxis.data()->label(); +} + +/* undocumented getter */ +bool QCPColorScale::rangeDrag() const +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return false; + } + + return mAxisRect.data()->rangeDrag().testFlag(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeDragAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); +} + +/* undocumented getter */ +bool QCPColorScale::rangeZoom() const +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return false; + } + + return mAxisRect.data()->rangeZoom().testFlag(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType)) && + mAxisRect.data()->rangeZoomAxis(QCPAxis::orientation(mType))->orientation() == QCPAxis::orientation(mType); +} + +/*! + Sets at which side of the color scale the axis is placed, and thus also its orientation. + + Note that after setting \a type to a different value, the axis returned by \ref axis() will + be a different one. The new axis will adopt the following properties from the previous axis: The + range, scale type, log base and label. +*/ +void QCPColorScale::setType(QCPAxis::AxisType type) +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + if (mType != type) + { + mType = type; + QCPRange rangeTransfer(0, 6); + double logBaseTransfer = 10; + QString labelTransfer; + // revert some settings on old axis: + if (mColorAxis) + { + rangeTransfer = mColorAxis.data()->range(); + labelTransfer = mColorAxis.data()->label(); + logBaseTransfer = mColorAxis.data()->scaleLogBase(); + mColorAxis.data()->setLabel(""); + disconnect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); + disconnect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); + } + foreach (QCPAxis::AxisType atype, QList() << QCPAxis::atLeft << QCPAxis::atRight << QCPAxis::atBottom << QCPAxis::atTop) + { + mAxisRect.data()->axis(atype)->setTicks(atype == mType); + mAxisRect.data()->axis(atype)->setTickLabels(atype== mType); + } + // set new mColorAxis pointer: + mColorAxis = mAxisRect.data()->axis(mType); + // transfer settings to new axis: + mColorAxis.data()->setRange(rangeTransfer); // transfer range of old axis to new one (necessary if axis changes from vertical to horizontal or vice versa) + mColorAxis.data()->setLabel(labelTransfer); + mColorAxis.data()->setScaleLogBase(logBaseTransfer); // scaleType is synchronized among axes in realtime via signals (connected in QCPColorScale ctor), so we only need to take care of log base here + connect(mColorAxis.data(), SIGNAL(rangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); + connect(mColorAxis.data(), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); + mAxisRect.data()->setRangeDragAxes(QCPAxis::orientation(mType) == Qt::Horizontal ? mColorAxis.data() : 0, + QCPAxis::orientation(mType) == Qt::Vertical ? mColorAxis.data() : 0); + } +} + +/*! + Sets the range spanned by the color gradient and that is shown by the axis in the color scale. + + It is equivalent to calling QCPColorMap::setDataRange on any of the connected color maps. It is + also equivalent to directly accessing the \ref axis and setting its range with \ref + QCPAxis::setRange. + + \see setDataScaleType, setGradient, rescaleDataRange +*/ +void QCPColorScale::setDataRange(const QCPRange &dataRange) +{ + if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) + { + mDataRange = dataRange; + if (mColorAxis) + mColorAxis.data()->setRange(mDataRange); + emit dataRangeChanged(mDataRange); + } +} + +/*! + Sets the scale type of the color scale, i.e. whether values are linearly associated with colors + or logarithmically. + + It is equivalent to calling QCPColorMap::setDataScaleType on any of the connected color maps. It is + also equivalent to directly accessing the \ref axis and setting its scale type with \ref + QCPAxis::setScaleType. + + \see setDataRange, setGradient +*/ +void QCPColorScale::setDataScaleType(QCPAxis::ScaleType scaleType) +{ + if (mDataScaleType != scaleType) + { + mDataScaleType = scaleType; + if (mColorAxis) + mColorAxis.data()->setScaleType(mDataScaleType); + if (mDataScaleType == QCPAxis::stLogarithmic) + setDataRange(mDataRange.sanitizedForLogScale()); + emit dataScaleTypeChanged(mDataScaleType); + } +} + +/*! + Sets the color gradient that will be used to represent data values. + + It is equivalent to calling QCPColorMap::setGradient on any of the connected color maps. + + \see setDataRange, setDataScaleType +*/ +void QCPColorScale::setGradient(const QCPColorGradient &gradient) +{ + if (mGradient != gradient) + { + mGradient = gradient; + if (mAxisRect) + mAxisRect.data()->mGradientImageInvalidated = true; + emit gradientChanged(mGradient); + } +} + +/*! + Sets the axis label of the color scale. This is equivalent to calling \ref QCPAxis::setLabel on + the internal \ref axis. +*/ +void QCPColorScale::setLabel(const QString &str) +{ + if (!mColorAxis) + { + qDebug() << Q_FUNC_INFO << "internal color axis undefined"; + return; + } + + mColorAxis.data()->setLabel(str); +} + +/*! + Sets the width (or height, for horizontal color scales) the bar where the gradient is displayed + will have. +*/ +void QCPColorScale::setBarWidth(int width) +{ + mBarWidth = width; +} + +/*! + Sets whether the user can drag the data range (\ref setDataRange). + + Note that \ref QCP::iRangeDrag must be in the QCustomPlot's interactions (\ref + QCustomPlot::setInteractions) to allow range dragging. +*/ +void QCPColorScale::setRangeDrag(bool enabled) +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + + if (enabled) + mAxisRect.data()->setRangeDrag(QCPAxis::orientation(mType)); + else + mAxisRect.data()->setRangeDrag(0); +} + +/*! + Sets whether the user can zoom the data range (\ref setDataRange) by scrolling the mouse wheel. + + Note that \ref QCP::iRangeZoom must be in the QCustomPlot's interactions (\ref + QCustomPlot::setInteractions) to allow range dragging. +*/ +void QCPColorScale::setRangeZoom(bool enabled) +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + + if (enabled) + mAxisRect.data()->setRangeZoom(QCPAxis::orientation(mType)); + else + mAxisRect.data()->setRangeZoom(0); +} + +/*! + Returns a list of all the color maps associated with this color scale. +*/ +QList QCPColorScale::colorMaps() const +{ + QList result; + for (int i=0; iplottableCount(); ++i) + { + if (QCPColorMap *cm = qobject_cast(mParentPlot->plottable(i))) + if (cm->colorScale() == this) + result.append(cm); + } + return result; +} + +/*! + Changes the data range such that all color maps associated with this color scale are fully mapped + to the gradient in the data dimension. + + \see setDataRange +*/ +void QCPColorScale::rescaleDataRange(bool onlyVisibleMaps) +{ + QList maps = colorMaps(); + QCPRange newRange; + bool haveRange = false; + int sign = 0; // TODO: should change this to QCPAbstractPlottable::SignDomain later (currently is protected, maybe move to QCP namespace) + if (mDataScaleType == QCPAxis::stLogarithmic) + sign = (mDataRange.upper < 0 ? -1 : 1); + for (int i=0; irealVisibility() && onlyVisibleMaps) + continue; + QCPRange mapRange; + if (maps.at(i)->colorScale() == this) + { + bool currentFoundRange = true; + mapRange = maps.at(i)->data()->dataBounds(); + if (sign == 1) + { + if (mapRange.lower <= 0 && mapRange.upper > 0) + mapRange.lower = mapRange.upper*1e-3; + else if (mapRange.lower <= 0 && mapRange.upper <= 0) + currentFoundRange = false; + } else if (sign == -1) + { + if (mapRange.upper >= 0 && mapRange.lower < 0) + mapRange.upper = mapRange.lower*1e-3; + else if (mapRange.upper >= 0 && mapRange.lower >= 0) + currentFoundRange = false; + } + if (currentFoundRange) + { + if (!haveRange) + newRange = mapRange; + else + newRange.expand(mapRange); + haveRange = true; + } + } + } + if (haveRange) + { + if (!QCPRange::validRange(newRange)) // likely due to range being zero (plottable has only constant data in this dimension), shift current range to at least center the data + { + double center = (newRange.lower+newRange.upper)*0.5; // upper and lower should be equal anyway, but just to make sure, incase validRange returned false for other reason + if (mDataScaleType == QCPAxis::stLinear) + { + newRange.lower = center-mDataRange.size()/2.0; + newRange.upper = center+mDataRange.size()/2.0; + } else // mScaleType == stLogarithmic + { + newRange.lower = center/qSqrt(mDataRange.upper/mDataRange.lower); + newRange.upper = center*qSqrt(mDataRange.upper/mDataRange.lower); + } + } + setDataRange(newRange); + } +} + +/* inherits documentation from base class */ +void QCPColorScale::update(UpdatePhase phase) +{ + QCPLayoutElement::update(phase); + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + + mAxisRect.data()->update(phase); + + switch (phase) + { + case upMargins: + { + if (mType == QCPAxis::atBottom || mType == QCPAxis::atTop) + { + setMaximumSize(QWIDGETSIZE_MAX, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom()); + setMinimumSize(0, mBarWidth+mAxisRect.data()->margins().top()+mAxisRect.data()->margins().bottom()+margins().top()+margins().bottom()); + } else + { + setMaximumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), QWIDGETSIZE_MAX); + setMinimumSize(mBarWidth+mAxisRect.data()->margins().left()+mAxisRect.data()->margins().right()+margins().left()+margins().right(), 0); + } + break; + } + case upLayout: + { + mAxisRect.data()->setOuterRect(rect()); + break; + } + default: break; + } +} + +/* inherits documentation from base class */ +void QCPColorScale::applyDefaultAntialiasingHint(QCPPainter *painter) const +{ + painter->setAntialiasing(false); +} + +/* inherits documentation from base class */ +void QCPColorScale::mousePressEvent(QMouseEvent *event) +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->mousePressEvent(event); +} + +/* inherits documentation from base class */ +void QCPColorScale::mouseMoveEvent(QMouseEvent *event) +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->mouseMoveEvent(event); +} + +/* inherits documentation from base class */ +void QCPColorScale::mouseReleaseEvent(QMouseEvent *event) +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->mouseReleaseEvent(event); +} + +/* inherits documentation from base class */ +void QCPColorScale::wheelEvent(QWheelEvent *event) +{ + if (!mAxisRect) + { + qDebug() << Q_FUNC_INFO << "internal axis rect was deleted"; + return; + } + mAxisRect.data()->wheelEvent(event); +} + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPColorScaleAxisRectPrivate +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPColorScaleAxisRectPrivate + + \internal + \brief An axis rect subclass for use in a QCPColorScale + + This is a private class and not part of the public QCustomPlot interface. + + It provides the axis rect functionality for the QCPColorScale class. +*/ + + +/*! + Creates a new instance, as a child of \a parentColorScale. +*/ +QCPColorScaleAxisRectPrivate::QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale) : + QCPAxisRect(parentColorScale->parentPlot(), true), + mParentColorScale(parentColorScale), + mGradientImageInvalidated(true) +{ + setParentLayerable(parentColorScale); + setMinimumMargins(QMargins(0, 0, 0, 0)); + foreach (QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) + { + axis(type)->setVisible(true); + axis(type)->grid()->setVisible(false); + axis(type)->setPadding(0); + connect(axis(type), SIGNAL(selectionChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectionChanged(QCPAxis::SelectableParts))); + connect(axis(type), SIGNAL(selectableChanged(QCPAxis::SelectableParts)), this, SLOT(axisSelectableChanged(QCPAxis::SelectableParts))); + } + + connect(axis(QCPAxis::atLeft), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atRight), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atRight), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atLeft), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atBottom), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atTop), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atTop), SIGNAL(rangeChanged(QCPRange)), axis(QCPAxis::atBottom), SLOT(setRange(QCPRange))); + connect(axis(QCPAxis::atLeft), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atRight), SLOT(setScaleType(QCPAxis::ScaleType))); + connect(axis(QCPAxis::atRight), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atLeft), SLOT(setScaleType(QCPAxis::ScaleType))); + connect(axis(QCPAxis::atBottom), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atTop), SLOT(setScaleType(QCPAxis::ScaleType))); + connect(axis(QCPAxis::atTop), SIGNAL(scaleTypeChanged(QCPAxis::ScaleType)), axis(QCPAxis::atBottom), SLOT(setScaleType(QCPAxis::ScaleType))); + + // make layer transfers of color scale transfer to axis rect and axes + // the axes must be set after axis rect, such that they appear above color gradient drawn by axis rect: + connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), this, SLOT(setLayer(QCPLayer*))); + foreach (QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) + connect(parentColorScale, SIGNAL(layerChanged(QCPLayer*)), axis(type), SLOT(setLayer(QCPLayer*))); +} + +/*! \internal + Updates the color gradient image if necessary, by calling \ref updateGradientImage, then draws + it. Then the axes are drawn by calling the \ref QCPAxisRect::draw base class implementation. +*/ +void QCPColorScaleAxisRectPrivate::draw(QCPPainter *painter) +{ + if (mGradientImageInvalidated) + updateGradientImage(); + + bool mirrorHorz = false; + bool mirrorVert = false; + if (mParentColorScale->mColorAxis) + { + mirrorHorz = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atBottom || mParentColorScale->type() == QCPAxis::atTop); + mirrorVert = mParentColorScale->mColorAxis.data()->rangeReversed() && (mParentColorScale->type() == QCPAxis::atLeft || mParentColorScale->type() == QCPAxis::atRight); + } + + painter->drawImage(rect(), mGradientImage.mirrored(mirrorHorz, mirrorVert)); + QCPAxisRect::draw(painter); +} + +/*! \internal + + Uses the current gradient of the parent \ref QCPColorScale (specified in the constructor) to + generate a gradient image. This gradient image will be used in the \ref draw method. +*/ +void QCPColorScaleAxisRectPrivate::updateGradientImage() +{ + if (rect().isEmpty()) + return; + + int n = mParentColorScale->mGradient.levelCount(); + int w, h; + QVector data(n); + for (int i=0; imType == QCPAxis::atBottom || mParentColorScale->mType == QCPAxis::atTop) + { + w = n; + h = rect().height(); + mGradientImage = QImage(w, h, QImage::Format_RGB32); + QVector pixels; + for (int y=0; y(mGradientImage.scanLine(y))); + mParentColorScale->mGradient.colorize(data.constData(), QCPRange(0, n-1), pixels.first(), n); + for (int y=1; y(mGradientImage.scanLine(y)); + const QRgb lineColor = mParentColorScale->mGradient.color(data[h-1-y], QCPRange(0, n-1)); + for (int x=0; x() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) + { + if (QCPAxis *senderAxis = qobject_cast(sender())) + if (senderAxis->axisType() == type) + continue; + + if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) + { + if (selectedParts.testFlag(QCPAxis::spAxis)) + axis(type)->setSelectedParts(axis(type)->selectedParts() | QCPAxis::spAxis); + else + axis(type)->setSelectedParts(axis(type)->selectedParts() & ~QCPAxis::spAxis); + } + } +} + +/*! \internal + + This slot is connected to the selectableChanged signals of the four axes in the constructor. It + synchronizes the selectability of the axes. +*/ +void QCPColorScaleAxisRectPrivate::axisSelectableChanged(QCPAxis::SelectableParts selectableParts) +{ + // synchronize axis base selectability: + foreach (QCPAxis::AxisType type, QList() << QCPAxis::atBottom << QCPAxis::atTop << QCPAxis::atLeft << QCPAxis::atRight) + { + if (QCPAxis *senderAxis = qobject_cast(sender())) + if (senderAxis->axisType() == type) + continue; + + if (axis(type)->selectableParts().testFlag(QCPAxis::spAxis)) + { + if (selectableParts.testFlag(QCPAxis::spAxis)) + axis(type)->setSelectableParts(axis(type)->selectableParts() | QCPAxis::spAxis); + else + axis(type)->setSelectableParts(axis(type)->selectableParts() & ~QCPAxis::spAxis); + } + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPData +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPData + \brief Holds the data of one single data point for QCPGraph. + + The container for storing multiple data points is \ref QCPDataMap. + + The stored data is: + \li \a key: coordinate on the key axis of this data point + \li \a value: coordinate on the value axis of this data point + \li \a keyErrorMinus: negative error in the key dimension (for error bars) + \li \a keyErrorPlus: positive error in the key dimension (for error bars) + \li \a valueErrorMinus: negative error in the value dimension (for error bars) + \li \a valueErrorPlus: positive error in the value dimension (for error bars) + + \see QCPDataMap +*/ + +/*! + Constructs a data point with key, value and all errors set to zero. +*/ +QCPData::QCPData() : + key(0), + value(0), + keyErrorPlus(0), + keyErrorMinus(0), + valueErrorPlus(0), + valueErrorMinus(0) +{ +} + +/*! + Constructs a data point with the specified \a key and \a value. All errors are set to zero. +*/ +QCPData::QCPData(double key, double value) : + key(key), + value(value), + keyErrorPlus(0), + keyErrorMinus(0), + valueErrorPlus(0), + valueErrorMinus(0) +{ +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPGraph +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPGraph + \brief A plottable representing a graph in a plot. + + \image html QCPGraph.png + + Usually QCustomPlot creates graphs internally via QCustomPlot::addGraph and the resulting + instance is accessed via QCustomPlot::graph. + + To plot data, assign it with the \ref setData or \ref addData functions. Alternatively, you can + also access and modify the graph's data via the \ref data method, which returns a pointer to the + internal \ref QCPDataMap. + + Graphs are used to display single-valued data. Single-valued means that there should only be one + data point per unique key coordinate. In other words, the graph can't have \a loops. If you do + want to plot non-single-valued curves, rather use the QCPCurve plottable. + + \section appearance Changing the appearance + + The appearance of the graph is mainly determined by the line style, scatter style, brush and pen + of the graph (\ref setLineStyle, \ref setScatterStyle, \ref setBrush, \ref setPen). + + \subsection filling Filling under or between graphs + + QCPGraph knows two types of fills: Normal graph fills towards the zero-value-line parallel to + the key axis of the graph, and fills between two graphs, called channel fills. To enable a fill, + just set a brush with \ref setBrush which is neither Qt::NoBrush nor fully transparent. + + By default, a normal fill towards the zero-value-line will be drawn. To set up a channel fill + between this graph and another one, call \ref setChannelFillGraph with the other graph as + parameter. + + \see QCustomPlot::addGraph, QCustomPlot::graph, QCPLegend::addGraph +*/ + +/* start of documentation of inline functions */ + +/*! \fn QCPDataMap *QCPGraph::data() const + + Returns a pointer to the internal data storage of type \ref QCPDataMap. You may use it to + directly manipulate the data, which may be more convenient and faster than using the regular \ref + setData or \ref addData methods, in certain situations. +*/ + +/* end of documentation of inline functions */ + +/*! + Constructs a graph which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value + axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have + the same orientation. If either of these restrictions is violated, a corresponding message is + printed to the debug output (qDebug), the construction is not aborted, though. + + The constructed QCPGraph can be added to the plot with QCustomPlot::addPlottable, QCustomPlot + then takes ownership of the graph. + + To directly create a graph inside a plot, you can also use the simpler QCustomPlot::addGraph function. +*/ +QCPGraph::QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis) : + QCPAbstractPlottable(keyAxis, valueAxis) +{ + mData = new QCPDataMap; + + setPen(QPen(Qt::blue, 0)); + setErrorPen(QPen(Qt::black)); + setBrush(Qt::NoBrush); + setSelectedPen(QPen(QColor(80, 80, 255), 2.5)); + setSelectedBrush(Qt::NoBrush); + + setLineStyle(lsLine); + setErrorType(etNone); + setErrorBarSize(6); + setErrorBarSkipSymbol(true); + setChannelFillGraph(0); + setAdaptiveSampling(true); +} + +QCPGraph::~QCPGraph() +{ + delete mData; +} + +/*! + Replaces the current data with the provided \a data. + + If \a copy is set to true, data points in \a data will only be copied. if false, the graph + takes ownership of the passed data and replaces the internal data pointer with it. This is + significantly faster than copying for large datasets. + + Alternatively, you can also access and modify the graph's data via the \ref data method, which + returns a pointer to the internal \ref QCPDataMap. +*/ +void QCPGraph::setData(QCPDataMap *data, bool copy) +{ + if (copy) + { + *mData = *data; + } else + { + delete mData; + mData = data; + } +} + +/*! \overload + + Replaces the current data with the provided points in \a key and \a value pairs. The provided + vectors should have equal length. Else, the number of added points will be the size of the + smallest vector. +*/ +void QCPGraph::setData(const QVector &key, const QVector &value) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + QCPData newData; + for (int i=0; iinsertMulti(newData.key, newData); + } +} + +/*! + Replaces the current data with the provided points in \a key and \a value pairs. Additionally the + symmetrical value error of the data points are set to the values in \a valueError. + For error bars to show appropriately, see \ref setErrorType. + The provided vectors should have equal length. Else, the number of added points will be the size of the + smallest vector. + + For asymmetrical errors (plus different from minus), see the overloaded version of this function. +*/ +void QCPGraph::setDataValueError(const QVector &key, const QVector &value, const QVector &valueError) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, valueError.size()); + QCPData newData; + for (int i=0; iinsertMulti(key[i], newData); + } +} + +/*! + \overload + Replaces the current data with the provided points in \a key and \a value pairs. Additionally the + negative value error of the data points are set to the values in \a valueErrorMinus, the positive + value error to \a valueErrorPlus. + For error bars to show appropriately, see \ref setErrorType. + The provided vectors should have equal length. Else, the number of added points will be the size of the + smallest vector. +*/ +void QCPGraph::setDataValueError(const QVector &key, const QVector &value, const QVector &valueErrorMinus, const QVector &valueErrorPlus) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, valueErrorMinus.size()); + n = qMin(n, valueErrorPlus.size()); + QCPData newData; + for (int i=0; iinsertMulti(key[i], newData); + } +} + +/*! + Replaces the current data with the provided points in \a key and \a value pairs. Additionally the + symmetrical key error of the data points are set to the values in \a keyError. + For error bars to show appropriately, see \ref setErrorType. + The provided vectors should have equal length. Else, the number of added points will be the size of the + smallest vector. + + For asymmetrical errors (plus different from minus), see the overloaded version of this function. +*/ +void QCPGraph::setDataKeyError(const QVector &key, const QVector &value, const QVector &keyError) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, keyError.size()); + QCPData newData; + for (int i=0; iinsertMulti(key[i], newData); + } +} + +/*! + \overload + Replaces the current data with the provided points in \a key and \a value pairs. Additionally the + negative key error of the data points are set to the values in \a keyErrorMinus, the positive + key error to \a keyErrorPlus. + For error bars to show appropriately, see \ref setErrorType. + The provided vectors should have equal length. Else, the number of added points will be the size of the + smallest vector. +*/ +void QCPGraph::setDataKeyError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, keyErrorMinus.size()); + n = qMin(n, keyErrorPlus.size()); + QCPData newData; + for (int i=0; iinsertMulti(key[i], newData); + } +} + +/*! + Replaces the current data with the provided points in \a key and \a value pairs. Additionally the + symmetrical key and value errors of the data points are set to the values in \a keyError and \a valueError. + For error bars to show appropriately, see \ref setErrorType. + The provided vectors should have equal length. Else, the number of added points will be the size of the + smallest vector. + + For asymmetrical errors (plus different from minus), see the overloaded version of this function. +*/ +void QCPGraph::setDataBothError(const QVector &key, const QVector &value, const QVector &keyError, const QVector &valueError) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, valueError.size()); + n = qMin(n, keyError.size()); + QCPData newData; + for (int i=0; iinsertMulti(key[i], newData); + } +} + +/*! + \overload + Replaces the current data with the provided points in \a key and \a value pairs. Additionally the + negative key and value errors of the data points are set to the values in \a keyErrorMinus and \a valueErrorMinus. The positive + key and value errors are set to the values in \a keyErrorPlus \a valueErrorPlus. + For error bars to show appropriately, see \ref setErrorType. + The provided vectors should have equal length. Else, the number of added points will be the size of the + smallest vector. +*/ +void QCPGraph::setDataBothError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus, const QVector &valueErrorMinus, const QVector &valueErrorPlus) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + n = qMin(n, valueErrorMinus.size()); + n = qMin(n, valueErrorPlus.size()); + n = qMin(n, keyErrorMinus.size()); + n = qMin(n, keyErrorPlus.size()); + QCPData newData; + for (int i=0; iinsertMulti(key[i], newData); + } +} + + +/*! + Sets how the single data points are connected in the plot. For scatter-only plots, set \a ls to + \ref lsNone and \ref setScatterStyle to the desired scatter style. + + \see setScatterStyle +*/ +void QCPGraph::setLineStyle(LineStyle ls) +{ + mLineStyle = ls; +} + +/*! + Sets the visual appearance of single data points in the plot. If set to \ref QCPScatterStyle::ssNone, no scatter points + are drawn (e.g. for line-only-plots with appropriate line style). + + \see QCPScatterStyle, setLineStyle +*/ +void QCPGraph::setScatterStyle(const QCPScatterStyle &style) +{ + mScatterStyle = style; +} + +/*! + Sets which kind of error bars (Key Error, Value Error or both) should be drawn on each data + point. If you set \a errorType to something other than \ref etNone, make sure to actually pass + error data via the specific setData functions along with the data points (e.g. \ref + setDataValueError, \ref setDataKeyError, \ref setDataBothError). + + \see ErrorType +*/ +void QCPGraph::setErrorType(ErrorType errorType) +{ + mErrorType = errorType; +} + +/*! + Sets the pen with which the error bars will be drawn. + \see setErrorBarSize, setErrorType +*/ +void QCPGraph::setErrorPen(const QPen &pen) +{ + mErrorPen = pen; +} + +/*! + Sets the width of the handles at both ends of an error bar in pixels. +*/ +void QCPGraph::setErrorBarSize(double size) +{ + mErrorBarSize = size; +} + +/*! + If \a enabled is set to true, the error bar will not be drawn as a solid line under the scatter symbol but + leave some free space around the symbol. + + This feature uses the current scatter size (\ref QCPScatterStyle::setSize) to determine the size + of the area to leave blank. So when drawing Pixmaps as scatter points (\ref + QCPScatterStyle::ssPixmap), the scatter size must be set manually to a value corresponding to the + size of the Pixmap, if the error bars should leave gaps to its boundaries. + + \ref setErrorType, setErrorBarSize, setScatterStyle +*/ +void QCPGraph::setErrorBarSkipSymbol(bool enabled) +{ + mErrorBarSkipSymbol = enabled; +} + +/*! + Sets the target graph for filling the area between this graph and \a targetGraph with the current + brush (\ref setBrush). + + When \a targetGraph is set to 0, a normal graph fill to the zero-value-line will be shown. To + disable any filling, set the brush to Qt::NoBrush. + + \see setBrush +*/ +void QCPGraph::setChannelFillGraph(QCPGraph *targetGraph) +{ + // prevent setting channel target to this graph itself: + if (targetGraph == this) + { + qDebug() << Q_FUNC_INFO << "targetGraph is this graph itself"; + mChannelFillGraph = 0; + return; + } + // prevent setting channel target to a graph not in the plot: + if (targetGraph && targetGraph->mParentPlot != mParentPlot) + { + qDebug() << Q_FUNC_INFO << "targetGraph not in same plot"; + mChannelFillGraph = 0; + return; + } + + mChannelFillGraph = targetGraph; +} + +/*! + Sets whether adaptive sampling shall be used when plotting this graph. QCustomPlot's adaptive + sampling technique can drastically improve the replot performance for graphs with a larger number + of points (e.g. above 10,000), without notably changing the appearance of the graph. + + By default, adaptive sampling is enabled. Even if enabled, QCustomPlot decides whether adaptive + sampling shall actually be used on a per-graph basis. So leaving adaptive sampling enabled has no + disadvantage in almost all cases. + + \image html adaptive-sampling-line.png "A line plot of 500,000 points without and with adaptive sampling" + + As can be seen, line plots experience no visual degradation from adaptive sampling. Outliers are + reproduced reliably, as well as the overall shape of the data set. The replot time reduces + dramatically though. This allows QCustomPlot to display large amounts of data in realtime. + + \image html adaptive-sampling-scatter.png "A scatter plot of 100,000 points without and with adaptive sampling" + + Care must be taken when using high-density scatter plots in combination with adaptive sampling. + The adaptive sampling algorithm treats scatter plots more carefully than line plots which still + gives a significant reduction of replot times, but not quite as much as for line plots. This is + because scatter plots inherently need more data points to be preserved in order to still resemble + the original, non-adaptive-sampling plot. As shown above, the results still aren't quite + identical, as banding occurs for the outer data points. This is in fact intentional, such that + the boundaries of the data cloud stay visible to the viewer. How strong the banding appears, + depends on the point density, i.e. the number of points in the plot. + + For some situations with scatter plots it might thus be desirable to manually turn adaptive + sampling off. For example, when saving the plot to disk. This can be achieved by setting \a + enabled to false before issuing a command like \ref QCustomPlot::savePng, and setting \a enabled + back to true afterwards. +*/ +void QCPGraph::setAdaptiveSampling(bool enabled) +{ + mAdaptiveSampling = enabled; +} + +/*! + Adds the provided data points in \a dataMap to the current data. + + Alternatively, you can also access and modify the graph's data via the \ref data method, which + returns a pointer to the internal \ref QCPDataMap. + + \see removeData +*/ +void QCPGraph::addData(const QCPDataMap &dataMap) +{ + mData->unite(dataMap); +} + +/*! \overload + Adds the provided single data point in \a data to the current data. + + Alternatively, you can also access and modify the graph's data via the \ref data method, which + returns a pointer to the internal \ref QCPDataMap. + + \see removeData +*/ +void QCPGraph::addData(const QCPData &data) +{ + mData->insertMulti(data.key, data); +} + +/*! \overload + Adds the provided single data point as \a key and \a value pair to the current data. + + Alternatively, you can also access and modify the graph's data via the \ref data method, which + returns a pointer to the internal \ref QCPDataMap. + + \see removeData +*/ +void QCPGraph::addData(double key, double value) +{ + QCPData newData; + newData.key = key; + newData.value = value; + mData->insertMulti(newData.key, newData); +} + +/*! \overload + Adds the provided data points as \a key and \a value pairs to the current data. + + Alternatively, you can also access and modify the graph's data via the \ref data method, which + returns a pointer to the internal \ref QCPDataMap. + + \see removeData +*/ +void QCPGraph::addData(const QVector &keys, const QVector &values) +{ + int n = qMin(keys.size(), values.size()); + QCPData newData; + for (int i=0; iinsertMulti(newData.key, newData); + } +} + +/*! + Removes all data points with keys smaller than \a key. + \see addData, clearData +*/ +void QCPGraph::removeDataBefore(double key) +{ + QCPDataMap::iterator it = mData->begin(); + while (it != mData->end() && it.key() < key) + it = mData->erase(it); +} + +/*! + Removes all data points with keys greater than \a key. + \see addData, clearData +*/ +void QCPGraph::removeDataAfter(double key) +{ + if (mData->isEmpty()) return; + QCPDataMap::iterator it = mData->upperBound(key); + while (it != mData->end()) + it = mData->erase(it); +} + +/*! + Removes all data points with keys between \a fromKey and \a toKey. + if \a fromKey is greater or equal to \a toKey, the function does nothing. To remove + a single data point with known key, use \ref removeData(double key). + + \see addData, clearData +*/ +void QCPGraph::removeData(double fromKey, double toKey) +{ + if (fromKey >= toKey || mData->isEmpty()) return; + QCPDataMap::iterator it = mData->upperBound(fromKey); + QCPDataMap::iterator itEnd = mData->upperBound(toKey); + while (it != itEnd) + it = mData->erase(it); +} + +/*! \overload + + Removes a single data point at \a key. If the position is not known with absolute precision, + consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval around + the suspected position, depeding on the precision with which the key is known. + + \see addData, clearData +*/ +void QCPGraph::removeData(double key) +{ + mData->remove(key); +} + +/*! + Removes all data points. + \see removeData, removeDataAfter, removeDataBefore +*/ +void QCPGraph::clearData() +{ + mData->clear(); +} + +/* inherits documentation from base class */ +double QCPGraph::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if ((onlySelectable && !mSelectable) || mData->isEmpty()) + return -1; + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) + return pointDistance(pos); + else + return -1; +} + +/*! \overload + + Allows to define whether error bars are taken into consideration when determining the new axis + range. + + \see rescaleKeyAxis, rescaleValueAxis, QCPAbstractPlottable::rescaleAxes, QCustomPlot::rescaleAxes +*/ +void QCPGraph::rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const +{ + rescaleKeyAxis(onlyEnlarge, includeErrorBars); + rescaleValueAxis(onlyEnlarge, includeErrorBars); +} + +/*! \overload + + Allows to define whether error bars (of kind \ref QCPGraph::etKey) are taken into consideration + when determining the new axis range. + + \see rescaleAxes, QCPAbstractPlottable::rescaleKeyAxis +*/ +void QCPGraph::rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const +{ + // this code is a copy of QCPAbstractPlottable::rescaleKeyAxis with the only change + // that getKeyRange is passed the includeErrorBars value. + if (mData->isEmpty()) return; + + QCPAxis *keyAxis = mKeyAxis.data(); + if (!keyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } + + SignDomain signDomain = sdBoth; + if (keyAxis->scaleType() == QCPAxis::stLogarithmic) + signDomain = (keyAxis->range().upper < 0 ? sdNegative : sdPositive); + + bool foundRange; + QCPRange newRange = getKeyRange(foundRange, signDomain, includeErrorBars); + + if (foundRange) + { + if (onlyEnlarge) + { + if (keyAxis->range().lower < newRange.lower) + newRange.lower = keyAxis->range().lower; + if (keyAxis->range().upper > newRange.upper) + newRange.upper = keyAxis->range().upper; + } + keyAxis->setRange(newRange); + } +} + +/*! \overload + + Allows to define whether error bars (of kind \ref QCPGraph::etValue) are taken into consideration + when determining the new axis range. + + \see rescaleAxes, QCPAbstractPlottable::rescaleValueAxis +*/ +void QCPGraph::rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const +{ + // this code is a copy of QCPAbstractPlottable::rescaleValueAxis with the only change + // is that getValueRange is passed the includeErrorBars value. + if (mData->isEmpty()) return; + + QCPAxis *valueAxis = mValueAxis.data(); + if (!valueAxis) { qDebug() << Q_FUNC_INFO << "invalid value axis"; return; } + + SignDomain signDomain = sdBoth; + if (valueAxis->scaleType() == QCPAxis::stLogarithmic) + signDomain = (valueAxis->range().upper < 0 ? sdNegative : sdPositive); + + bool foundRange; + QCPRange newRange = getValueRange(foundRange, signDomain, includeErrorBars); + + if (foundRange) + { + if (onlyEnlarge) + { + if (valueAxis->range().lower < newRange.lower) + newRange.lower = valueAxis->range().lower; + if (valueAxis->range().upper > newRange.upper) + newRange.upper = valueAxis->range().upper; + } + valueAxis->setRange(newRange); + } +} + +/* inherits documentation from base class */ +void QCPGraph::draw(QCPPainter *painter) +{ + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (mKeyAxis.data()->range().size() <= 0 || mData->isEmpty()) return; + if (mLineStyle == lsNone && mScatterStyle.isNone()) return; + + // allocate line and (if necessary) point vectors: + QVector *lineData = new QVector; + QVector *scatterData = 0; + if (!mScatterStyle.isNone()) + scatterData = new QVector; + + // fill vectors with data appropriate to plot style: + getPlotData(lineData, scatterData); + + // check data validity if flag set: +#ifdef QCUSTOMPLOT_CHECK_DATA + QCPDataMap::const_iterator it; + for (it = mData->constBegin(); it != mData->constEnd(); ++it) + { + if (QCP::isInvalidData(it.value().key, it.value().value) || + QCP::isInvalidData(it.value().keyErrorPlus, it.value().keyErrorMinus) || + QCP::isInvalidData(it.value().valueErrorPlus, it.value().valueErrorPlus)) + qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name(); + } +#endif + + // draw fill of graph: + drawFill(painter, lineData); + + // draw line: + if (mLineStyle == lsImpulse) + drawImpulsePlot(painter, lineData); + else if (mLineStyle != lsNone) + drawLinePlot(painter, lineData); // also step plots can be drawn as a line plot + + // draw scatters: + if (scatterData) + drawScatterPlot(painter, scatterData); + + // free allocated line and point vectors: + delete lineData; + if (scatterData) + delete scatterData; +} + +/* inherits documentation from base class */ +void QCPGraph::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const +{ + // draw fill: + if (mBrush.style() != Qt::NoBrush) + { + applyFillAntialiasingHint(painter); + painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); + } + // draw line vertically centered: + if (mLineStyle != lsNone) + { + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens + } + // draw scatter symbol: + if (!mScatterStyle.isNone()) + { + applyScattersAntialiasingHint(painter); + // scale scatter pixmap if it's too large to fit in legend icon rect: + if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) + { + QCPScatterStyle scaledStyle(mScatterStyle); + scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); + scaledStyle.applyTo(painter, mPen); + scaledStyle.drawShape(painter, QRectF(rect).center()); + } else + { + mScatterStyle.applyTo(painter, mPen); + mScatterStyle.drawShape(painter, QRectF(rect).center()); + } + } +} + +/*! \internal + + This function branches out to the line style specific "get(...)PlotData" functions, according to + the line style of the graph. + + \a lineData will be filled with raw points that will be drawn with the according draw functions, + e.g. \ref drawLinePlot and \ref drawImpulsePlot. These aren't necessarily the original data + points, since for step plots for example, additional points are needed for drawing lines that + make up steps. If the line style of the graph is \ref lsNone, the \a lineData vector will be left + untouched. + + \a scatterData will be filled with the original data points so \ref drawScatterPlot can draw the + scatter symbols accordingly. If no scatters need to be drawn, i.e. the scatter style's shape is + \ref QCPScatterStyle::ssNone, pass 0 as \a scatterData, and this step will be skipped. + + \see getScatterPlotData, getLinePlotData, getStepLeftPlotData, getStepRightPlotData, + getStepCenterPlotData, getImpulsePlotData +*/ +void QCPGraph::getPlotData(QVector *lineData, QVector *scatterData) const +{ + switch(mLineStyle) + { + case lsNone: getScatterPlotData(scatterData); break; + case lsLine: getLinePlotData(lineData, scatterData); break; + case lsStepLeft: getStepLeftPlotData(lineData, scatterData); break; + case lsStepRight: getStepRightPlotData(lineData, scatterData); break; + case lsStepCenter: getStepCenterPlotData(lineData, scatterData); break; + case lsImpulse: getImpulsePlotData(lineData, scatterData); break; + } +} + +/*! \internal + + If line style is \ref lsNone and the scatter style's shape is not \ref QCPScatterStyle::ssNone, + this function serves at providing the visible data points in \a scatterData, so the \ref + drawScatterPlot function can draw the scatter points accordingly. + + If line style is not \ref lsNone, this function is not called and the data for the scatter points + are (if needed) calculated inside the corresponding other "get(...)PlotData" functions. + + \see drawScatterPlot +*/ +void QCPGraph::getScatterPlotData(QVector *scatterData) const +{ + getPreparedData(0, scatterData); +} + +/*! \internal + + Places the raw data points needed for a normal linearly connected graph in \a linePixelData. + + As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) + points that are visible for drawing scatter points, if necessary. If drawing scatter points is + disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a + scatterData, and the function will skip filling the vector. + + \see drawLinePlot +*/ +void QCPGraph::getLinePlotData(QVector *linePixelData, QVector *scatterData) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; } + + QVector lineData; + getPreparedData(&lineData, scatterData); + linePixelData->reserve(lineData.size()+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill + linePixelData->resize(lineData.size()); + + // transform lineData points to pixels: + if (keyAxis->orientation() == Qt::Vertical) + { + for (int i=0; icoordToPixel(lineData.at(i).value)); + (*linePixelData)[i].setY(keyAxis->coordToPixel(lineData.at(i).key)); + } + } else // key axis is horizontal + { + for (int i=0; icoordToPixel(lineData.at(i).key)); + (*linePixelData)[i].setY(valueAxis->coordToPixel(lineData.at(i).value)); + } + } +} + +/*! + \internal + Places the raw data points needed for a step plot with left oriented steps in \a lineData. + + As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) + points that are visible for drawing scatter points, if necessary. If drawing scatter points is + disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a + scatterData, and the function will skip filling the vector. + + \see drawLinePlot +*/ +void QCPGraph::getStepLeftPlotData(QVector *linePixelData, QVector *scatterData) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } + + QVector lineData; + getPreparedData(&lineData, scatterData); + linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill + linePixelData->resize(lineData.size()*2); + + // calculate steps from lineData and transform to pixel coordinates: + if (keyAxis->orientation() == Qt::Vertical) + { + double lastValue = valueAxis->coordToPixel(lineData.first().value); + double key; + for (int i=0; icoordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+0].setX(lastValue); + (*linePixelData)[i*2+0].setY(key); + lastValue = valueAxis->coordToPixel(lineData.at(i).value); + (*linePixelData)[i*2+1].setX(lastValue); + (*linePixelData)[i*2+1].setY(key); + } + } else // key axis is horizontal + { + double lastValue = valueAxis->coordToPixel(lineData.first().value); + double key; + for (int i=0; icoordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+0].setX(key); + (*linePixelData)[i*2+0].setY(lastValue); + lastValue = valueAxis->coordToPixel(lineData.at(i).value); + (*linePixelData)[i*2+1].setX(key); + (*linePixelData)[i*2+1].setY(lastValue); + } + } +} + +/*! + \internal + Places the raw data points needed for a step plot with right oriented steps in \a lineData. + + As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) + points that are visible for drawing scatter points, if necessary. If drawing scatter points is + disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a + scatterData, and the function will skip filling the vector. + + \see drawLinePlot +*/ +void QCPGraph::getStepRightPlotData(QVector *linePixelData, QVector *scatterData) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } + + QVector lineData; + getPreparedData(&lineData, scatterData); + linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill + linePixelData->resize(lineData.size()*2); + + // calculate steps from lineData and transform to pixel coordinates: + if (keyAxis->orientation() == Qt::Vertical) + { + double lastKey = keyAxis->coordToPixel(lineData.first().key); + double value; + for (int i=0; icoordToPixel(lineData.at(i).value); + (*linePixelData)[i*2+0].setX(value); + (*linePixelData)[i*2+0].setY(lastKey); + lastKey = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+1].setX(value); + (*linePixelData)[i*2+1].setY(lastKey); + } + } else // key axis is horizontal + { + double lastKey = keyAxis->coordToPixel(lineData.first().key); + double value; + for (int i=0; icoordToPixel(lineData.at(i).value); + (*linePixelData)[i*2+0].setX(lastKey); + (*linePixelData)[i*2+0].setY(value); + lastKey = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+1].setX(lastKey); + (*linePixelData)[i*2+1].setY(value); + } + } +} + +/*! + \internal + Places the raw data points needed for a step plot with centered steps in \a lineData. + + As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) + points that are visible for drawing scatter points, if necessary. If drawing scatter points is + disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a + scatterData, and the function will skip filling the vector. + + \see drawLinePlot +*/ +void QCPGraph::getStepCenterPlotData(QVector *linePixelData, QVector *scatterData) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as lineData"; return; } + + QVector lineData; + getPreparedData(&lineData, scatterData); + linePixelData->reserve(lineData.size()*2+2); // added 2 to reserve memory for lower/upper fill base points that might be needed for fill + linePixelData->resize(lineData.size()*2); + // calculate steps from lineData and transform to pixel coordinates: + if (keyAxis->orientation() == Qt::Vertical) + { + double lastKey = keyAxis->coordToPixel(lineData.first().key); + double lastValue = valueAxis->coordToPixel(lineData.first().value); + double key; + (*linePixelData)[0].setX(lastValue); + (*linePixelData)[0].setY(lastKey); + for (int i=1; icoordToPixel(lineData.at(i).key)+lastKey)*0.5; + (*linePixelData)[i*2-1].setX(lastValue); + (*linePixelData)[i*2-1].setY(key); + lastValue = valueAxis->coordToPixel(lineData.at(i).value); + lastKey = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+0].setX(lastValue); + (*linePixelData)[i*2+0].setY(key); + } + (*linePixelData)[lineData.size()*2-1].setX(lastValue); + (*linePixelData)[lineData.size()*2-1].setY(lastKey); + } else // key axis is horizontal + { + double lastKey = keyAxis->coordToPixel(lineData.first().key); + double lastValue = valueAxis->coordToPixel(lineData.first().value); + double key; + (*linePixelData)[0].setX(lastKey); + (*linePixelData)[0].setY(lastValue); + for (int i=1; icoordToPixel(lineData.at(i).key)+lastKey)*0.5; + (*linePixelData)[i*2-1].setX(key); + (*linePixelData)[i*2-1].setY(lastValue); + lastValue = valueAxis->coordToPixel(lineData.at(i).value); + lastKey = keyAxis->coordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+0].setX(key); + (*linePixelData)[i*2+0].setY(lastValue); + } + (*linePixelData)[lineData.size()*2-1].setX(lastKey); + (*linePixelData)[lineData.size()*2-1].setY(lastValue); + } + +} + +/*! + \internal + Places the raw data points needed for an impulse plot in \a lineData. + + As for all plot data retrieval functions, \a scatterData just contains all unaltered data (scatter) + points that are visible for drawing scatter points, if necessary. If drawing scatter points is + disabled (i.e. the scatter style's shape is \ref QCPScatterStyle::ssNone), pass 0 as \a + scatterData, and the function will skip filling the vector. + + \see drawImpulsePlot +*/ +void QCPGraph::getImpulsePlotData(QVector *linePixelData, QVector *scatterData) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (!linePixelData) { qDebug() << Q_FUNC_INFO << "null pointer passed as linePixelData"; return; } + + QVector lineData; + getPreparedData(&lineData, scatterData); + linePixelData->resize(lineData.size()*2); // no need to reserve 2 extra points because impulse plot has no fill + + // transform lineData points to pixels: + if (keyAxis->orientation() == Qt::Vertical) + { + double zeroPointX = valueAxis->coordToPixel(0); + double key; + for (int i=0; icoordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+0].setX(zeroPointX); + (*linePixelData)[i*2+0].setY(key); + (*linePixelData)[i*2+1].setX(valueAxis->coordToPixel(lineData.at(i).value)); + (*linePixelData)[i*2+1].setY(key); + } + } else // key axis is horizontal + { + double zeroPointY = valueAxis->coordToPixel(0); + double key; + for (int i=0; icoordToPixel(lineData.at(i).key); + (*linePixelData)[i*2+0].setX(key); + (*linePixelData)[i*2+0].setY(zeroPointY); + (*linePixelData)[i*2+1].setX(key); + (*linePixelData)[i*2+1].setY(valueAxis->coordToPixel(lineData.at(i).value)); + } + } +} + +/*! \internal + + Draws the fill of the graph with the specified brush. + + If the fill is a normal fill towards the zero-value-line, only the \a lineData is required (and + two extra points at the zero-value-line, which are added by \ref addFillBasePoints and removed by + \ref removeFillBasePoints after the fill drawing is done). + + If the fill is a channel fill between this QCPGraph and another QCPGraph (mChannelFillGraph), the + more complex polygon is calculated with the \ref getChannelFillPolygon function. + + \see drawLinePlot +*/ +void QCPGraph::drawFill(QCPPainter *painter, QVector *lineData) const +{ + if (mLineStyle == lsImpulse) return; // fill doesn't make sense for impulse plot + if (mainBrush().style() == Qt::NoBrush || mainBrush().color().alpha() == 0) return; + + applyFillAntialiasingHint(painter); + if (!mChannelFillGraph) + { + // draw base fill under graph, fill goes all the way to the zero-value-line: + addFillBasePoints(lineData); + painter->setPen(Qt::NoPen); + painter->setBrush(mainBrush()); + painter->drawPolygon(QPolygonF(*lineData)); + removeFillBasePoints(lineData); + } else + { + // draw channel fill between this graph and mChannelFillGraph: + painter->setPen(Qt::NoPen); + painter->setBrush(mainBrush()); + painter->drawPolygon(getChannelFillPolygon(lineData)); + } +} + +/*! \internal + + Draws scatter symbols at every data point passed in \a scatterData. scatter symbols are independent + of the line style and are always drawn if the scatter style's shape is not \ref + QCPScatterStyle::ssNone. Hence, the \a scatterData vector is outputted by all "get(...)PlotData" + functions, together with the (line style dependent) line data. + + \see drawLinePlot, drawImpulsePlot +*/ +void QCPGraph::drawScatterPlot(QCPPainter *painter, QVector *scatterData) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + + // draw error bars: + if (mErrorType != etNone) + { + applyErrorBarsAntialiasingHint(painter); + painter->setPen(mErrorPen); + if (keyAxis->orientation() == Qt::Vertical) + { + for (int i=0; isize(); ++i) + drawError(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key), scatterData->at(i)); + } else + { + for (int i=0; isize(); ++i) + drawError(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value), scatterData->at(i)); + } + } + + // draw scatter point symbols: + applyScattersAntialiasingHint(painter); + mScatterStyle.applyTo(painter, mPen); + if (keyAxis->orientation() == Qt::Vertical) + { + for (int i=0; isize(); ++i) + if (!qIsNaN(scatterData->at(i).value)) + mScatterStyle.drawShape(painter, valueAxis->coordToPixel(scatterData->at(i).value), keyAxis->coordToPixel(scatterData->at(i).key)); + } else + { + for (int i=0; isize(); ++i) + if (!qIsNaN(scatterData->at(i).value)) + mScatterStyle.drawShape(painter, keyAxis->coordToPixel(scatterData->at(i).key), valueAxis->coordToPixel(scatterData->at(i).value)); + } +} + +/*! \internal + + Draws line graphs from the provided data. It connects all points in \a lineData, which was + created by one of the "get(...)PlotData" functions for line styles that require simple line + connections between the point vector they create. These are for example \ref getLinePlotData, + \ref getStepLeftPlotData, \ref getStepRightPlotData and \ref getStepCenterPlotData. + + \see drawScatterPlot, drawImpulsePlot +*/ +void QCPGraph::drawLinePlot(QCPPainter *painter, QVector *lineData) const +{ + // draw line of graph: + if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) + { + applyDefaultAntialiasingHint(painter); + painter->setPen(mainPen()); + painter->setBrush(Qt::NoBrush); + + /* Draws polyline in batches, currently not used: + int p = 0; + while (p < lineData->size()) + { + int batch = qMin(25, lineData->size()-p); + if (p != 0) + { + ++batch; + --p; // to draw the connection lines between two batches + } + painter->drawPolyline(lineData->constData()+p, batch); + p += batch; + } + */ + + // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: + if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && + painter->pen().style() == Qt::SolidLine && + !painter->modes().testFlag(QCPPainter::pmVectorized)&& + !painter->modes().testFlag(QCPPainter::pmNoCaching)) + { + int i = 1; + int lineDataSize = lineData->size(); + while (i < lineDataSize) + { + if (!qIsNaN(lineData->at(i).y()) && !qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line + painter->drawLine(lineData->at(i-1), lineData->at(i)); + else + ++i; + ++i; + } + } else + { + int segmentStart = 0; + int i = 0; + int lineDataSize = lineData->size(); + while (i < lineDataSize) + { + if (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line + { + painter->drawPolyline(lineData->constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point + segmentStart = i+1; + } + ++i; + } + // draw last segment: + painter->drawPolyline(lineData->constData()+segmentStart, lineDataSize-segmentStart); // lineDataSize, because we do want to include the last point + } + } +} + +/*! \internal + + Draws impulses from the provided data, i.e. it connects all line pairs in \a lineData, which was + created by \ref getImpulsePlotData. + + \see drawScatterPlot, drawLinePlot +*/ +void QCPGraph::drawImpulsePlot(QCPPainter *painter, QVector *lineData) const +{ + // draw impulses: + if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) + { + applyDefaultAntialiasingHint(painter); + QPen pen = mainPen(); + pen.setCapStyle(Qt::FlatCap); // so impulse line doesn't reach beyond zero-line + painter->setPen(pen); + painter->setBrush(Qt::NoBrush); + painter->drawLines(*lineData); + } +} + +/*! \internal + + Returns the \a lineData and \a scatterData that need to be plotted for this graph taking into + consideration the current axis ranges and, if \ref setAdaptiveSampling is enabled, local point + densities. + + 0 may be passed as \a lineData or \a scatterData to indicate that the respective dataset isn't + needed. For example, if the scatter style (\ref setScatterStyle) is \ref QCPScatterStyle::ssNone, \a + scatterData should be 0 to prevent unnecessary calculations. + + This method is used by the various "get(...)PlotData" methods to get the basic working set of data. +*/ +void QCPGraph::getPreparedData(QVector *lineData, QVector *scatterData) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + // get visible data range: + QCPDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point + getVisibleDataBounds(lower, upper); + if (lower == mData->constEnd() || upper == mData->constEnd()) + return; + + // count points in visible range, taking into account that we only need to count to the limit maxCount if using adaptive sampling: + int maxCount = std::numeric_limits::max(); + if (mAdaptiveSampling) + { + int keyPixelSpan = qAbs(keyAxis->coordToPixel(lower.key())-keyAxis->coordToPixel(upper.key())); + maxCount = 2*keyPixelSpan+2; + } + int dataCount = countDataInBounds(lower, upper, maxCount); + + if (mAdaptiveSampling && dataCount >= maxCount) // use adaptive sampling only if there are at least two points per pixel on average + { + if (lineData) + { + QCPDataMap::const_iterator it = lower; + QCPDataMap::const_iterator upperEnd = upper+1; + double minValue = it.value().value; + double maxValue = it.value().value; + QCPDataMap::const_iterator currentIntervalFirstPoint = it; + int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction + int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey + double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound)); + double lastIntervalEndKey = currentIntervalStartKey; + double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates + bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) + int intervalDataCount = 1; + ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect + while (it != upperEnd) + { + if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this cluster if necessary + { + if (it.value().value < minValue) + minValue = it.value().value; + else if (it.value().value > maxValue) + maxValue = it.value().value; + ++intervalDataCount; + } else // new pixel interval started + { + if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster + { + if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point is further away, so first point of this cluster must be at a real data point + lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value)); + lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue)); + lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue)); + if (it.key() > currentIntervalStartKey+keyEpsilon*2) // new pixel started further away from previous cluster, so make sure the last point of the cluster is at a real data point + lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.8, (it-1).value().value)); + } else + lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value)); + lastIntervalEndKey = (it-1).value().key; + minValue = it.value().value; + maxValue = it.value().value; + currentIntervalFirstPoint = it; + currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound)); + if (keyEpsilonVariable) + keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); + intervalDataCount = 1; + } + ++it; + } + // handle last interval: + if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them to a cluster + { + if (lastIntervalEndKey < currentIntervalStartKey-keyEpsilon) // last point wasn't a cluster, so first point of this cluster must be at a real data point + lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.2, currentIntervalFirstPoint.value().value)); + lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.25, minValue)); + lineData->append(QCPData(currentIntervalStartKey+keyEpsilon*0.75, maxValue)); + } else + lineData->append(QCPData(currentIntervalFirstPoint.key(), currentIntervalFirstPoint.value().value)); + } + + if (scatterData) + { + double valueMaxRange = valueAxis->range().upper; + double valueMinRange = valueAxis->range().lower; + QCPDataMap::const_iterator it = lower; + QCPDataMap::const_iterator upperEnd = upper+1; + double minValue = it.value().value; + double maxValue = it.value().value; + QCPDataMap::const_iterator minValueIt = it; + QCPDataMap::const_iterator maxValueIt = it; + QCPDataMap::const_iterator currentIntervalStart = it; + int reversedFactor = keyAxis->rangeReversed() ? -1 : 1; // is used to calculate keyEpsilon pixel into the correct direction + int reversedRound = keyAxis->rangeReversed() ? 1 : 0; // is used to switch between floor (normal) and ceil (reversed) rounding of currentIntervalStartKey + double currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(lower.key())+reversedRound)); + double keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); // interval of one pixel on screen when mapped to plot key coordinates + bool keyEpsilonVariable = keyAxis->scaleType() == QCPAxis::stLogarithmic; // indicates whether keyEpsilon needs to be updated after every interval (for log axes) + int intervalDataCount = 1; + ++it; // advance iterator to second data point because adaptive sampling works in 1 point retrospect + while (it != upperEnd) + { + if (it.key() < currentIntervalStartKey+keyEpsilon) // data point is still within same pixel, so skip it and expand value span of this pixel if necessary + { + if (it.value().value < minValue && it.value().value > valueMinRange && it.value().value < valueMaxRange) + { + minValue = it.value().value; + minValueIt = it; + } else if (it.value().value > maxValue && it.value().value > valueMinRange && it.value().value < valueMaxRange) + { + maxValue = it.value().value; + maxValueIt = it; + } + ++intervalDataCount; + } else // new pixel started + { + if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them + { + // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): + double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue)); + int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average + QCPDataMap::const_iterator intervalIt = currentIntervalStart; + int c = 0; + while (intervalIt != it) + { + if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) + scatterData->append(intervalIt.value()); + ++c; + ++intervalIt; + } + } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange) + scatterData->append(currentIntervalStart.value()); + minValue = it.value().value; + maxValue = it.value().value; + currentIntervalStart = it; + currentIntervalStartKey = keyAxis->pixelToCoord((int)(keyAxis->coordToPixel(it.key())+reversedRound)); + if (keyEpsilonVariable) + keyEpsilon = qAbs(currentIntervalStartKey-keyAxis->pixelToCoord(keyAxis->coordToPixel(currentIntervalStartKey)+1.0*reversedFactor)); + intervalDataCount = 1; + } + ++it; + } + // handle last interval: + if (intervalDataCount >= 2) // last pixel had multiple data points, consolidate them + { + // determine value pixel span and add as many points in interval to maintain certain vertical data density (this is specific to scatter plot): + double valuePixelSpan = qAbs(valueAxis->coordToPixel(minValue)-valueAxis->coordToPixel(maxValue)); + int dataModulo = qMax(1, qRound(intervalDataCount/(valuePixelSpan/4.0))); // approximately every 4 value pixels one data point on average + QCPDataMap::const_iterator intervalIt = currentIntervalStart; + int c = 0; + while (intervalIt != it) + { + if ((c % dataModulo == 0 || intervalIt == minValueIt || intervalIt == maxValueIt) && intervalIt.value().value > valueMinRange && intervalIt.value().value < valueMaxRange) + scatterData->append(intervalIt.value()); + ++c; + ++intervalIt; + } + } else if (currentIntervalStart.value().value > valueMinRange && currentIntervalStart.value().value < valueMaxRange) + scatterData->append(currentIntervalStart.value()); + } + } else // don't use adaptive sampling algorithm, transfer points one-to-one from the map into the output parameters + { + QVector *dataVector = 0; + if (lineData) + dataVector = lineData; + else if (scatterData) + dataVector = scatterData; + if (dataVector) + { + QCPDataMap::const_iterator it = lower; + QCPDataMap::const_iterator upperEnd = upper+1; + dataVector->reserve(dataCount+2); // +2 for possible fill end points + while (it != upperEnd) + { + dataVector->append(it.value()); + ++it; + } + } + if (lineData && scatterData) + *scatterData = *dataVector; + } +} + +/*! \internal + + called by the scatter drawing function (\ref drawScatterPlot) to draw the error bars on one data + point. \a x and \a y pixel positions of the data point are passed since they are already known in + pixel coordinates in the drawing function, so we save some extra coordToPixel transforms here. \a + data is therefore only used for the errors, not key and value. +*/ +void QCPGraph::drawError(QCPPainter *painter, double x, double y, const QCPData &data) const +{ + if (qIsNaN(data.value)) + return; + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + + double a, b; // positions of error bar bounds in pixels + double barWidthHalf = mErrorBarSize*0.5; + double skipSymbolMargin = mScatterStyle.size(); // pixels left blank per side, when mErrorBarSkipSymbol is true + + if (keyAxis->orientation() == Qt::Vertical) + { + // draw key error vertically and value error horizontally + if (mErrorType == etKey || mErrorType == etBoth) + { + a = keyAxis->coordToPixel(data.key-data.keyErrorMinus); + b = keyAxis->coordToPixel(data.key+data.keyErrorPlus); + if (keyAxis->rangeReversed()) + qSwap(a,b); + // draw spine: + if (mErrorBarSkipSymbol) + { + if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin + painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin)); + if (y-b > skipSymbolMargin) + painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b)); + } else + painter->drawLine(QLineF(x, a, x, b)); + // draw handles: + painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a)); + painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b)); + } + if (mErrorType == etValue || mErrorType == etBoth) + { + a = valueAxis->coordToPixel(data.value-data.valueErrorMinus); + b = valueAxis->coordToPixel(data.value+data.valueErrorPlus); + if (valueAxis->rangeReversed()) + qSwap(a,b); + // draw spine: + if (mErrorBarSkipSymbol) + { + if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin + painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y)); + if (b-x > skipSymbolMargin) + painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y)); + } else + painter->drawLine(QLineF(a, y, b, y)); + // draw handles: + painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf)); + painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf)); + } + } else // mKeyAxis->orientation() is Qt::Horizontal + { + // draw value error vertically and key error horizontally + if (mErrorType == etKey || mErrorType == etBoth) + { + a = keyAxis->coordToPixel(data.key-data.keyErrorMinus); + b = keyAxis->coordToPixel(data.key+data.keyErrorPlus); + if (keyAxis->rangeReversed()) + qSwap(a,b); + // draw spine: + if (mErrorBarSkipSymbol) + { + if (x-a > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin + painter->drawLine(QLineF(a, y, x-skipSymbolMargin, y)); + if (b-x > skipSymbolMargin) + painter->drawLine(QLineF(x+skipSymbolMargin, y, b, y)); + } else + painter->drawLine(QLineF(a, y, b, y)); + // draw handles: + painter->drawLine(QLineF(a, y-barWidthHalf, a, y+barWidthHalf)); + painter->drawLine(QLineF(b, y-barWidthHalf, b, y+barWidthHalf)); + } + if (mErrorType == etValue || mErrorType == etBoth) + { + a = valueAxis->coordToPixel(data.value-data.valueErrorMinus); + b = valueAxis->coordToPixel(data.value+data.valueErrorPlus); + if (valueAxis->rangeReversed()) + qSwap(a,b); + // draw spine: + if (mErrorBarSkipSymbol) + { + if (a-y > skipSymbolMargin) // don't draw spine if error is so small it's within skipSymbolmargin + painter->drawLine(QLineF(x, a, x, y+skipSymbolMargin)); + if (y-b > skipSymbolMargin) + painter->drawLine(QLineF(x, y-skipSymbolMargin, x, b)); + } else + painter->drawLine(QLineF(x, a, x, b)); + // draw handles: + painter->drawLine(QLineF(x-barWidthHalf, a, x+barWidthHalf, a)); + painter->drawLine(QLineF(x-barWidthHalf, b, x+barWidthHalf, b)); + } + } +} + +/*! \internal + + called by \ref getPreparedData to determine which data (key) range is visible at the current key + axis range setting, so only that needs to be processed. + + \a lower returns an iterator to the lowest data point that needs to be taken into account when + plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a + lower may still be just outside the visible range. + + \a upper returns an iterator to the highest data point. Same as before, \a upper may also lie + just outside of the visible range. + + if the graph contains no data, both \a lower and \a upper point to constEnd. +*/ +void QCPGraph::getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const +{ + if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } + if (mData->isEmpty()) + { + lower = mData->constEnd(); + upper = mData->constEnd(); + return; + } + + // get visible data range as QMap iterators + QCPDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower); + QCPDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper); + bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range + bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range + + lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn + upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn +} + +/*! \internal + + Counts the number of data points between \a lower and \a upper (including them), up to a maximum + of \a maxCount. + + This function is used by \ref getPreparedData to determine whether adaptive sampling shall be + used (if enabled via \ref setAdaptiveSampling) or not. This is also why counting of data points + only needs to be done until \a maxCount is reached, which should be set to the number of data + points at which adaptive sampling sets in. +*/ +int QCPGraph::countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const +{ + if (upper == mData->constEnd() && lower == mData->constEnd()) + return 0; + QCPDataMap::const_iterator it = lower; + int count = 1; + while (it != upper && count < maxCount) + { + ++it; + ++count; + } + return count; +} + +/*! \internal + + The line data vector generated by e.g. getLinePlotData contains only the line that connects the + data points. If the graph needs to be filled, two additional points need to be added at the + value-zero-line in the lower and upper key positions of the graph. This function calculates these + points and adds them to the end of \a lineData. Since the fill is typically drawn before the line + stroke, these added points need to be removed again after the fill is done, with the + removeFillBasePoints function. + + The expanding of \a lineData by two points will not cause unnecessary memory reallocations, + because the data vector generation functions (getLinePlotData etc.) reserve two extra points when + they allocate memory for \a lineData. + + \see removeFillBasePoints, lowerFillBasePoint, upperFillBasePoint +*/ +void QCPGraph::addFillBasePoints(QVector *lineData) const +{ + if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } + + // append points that close the polygon fill at the key axis: + if (mKeyAxis.data()->orientation() == Qt::Vertical) + { + *lineData << upperFillBasePoint(lineData->last().y()); + *lineData << lowerFillBasePoint(lineData->first().y()); + } else + { + *lineData << upperFillBasePoint(lineData->last().x()); + *lineData << lowerFillBasePoint(lineData->first().x()); + } +} + +/*! \internal + + removes the two points from \a lineData that were added by \ref addFillBasePoints. + + \see addFillBasePoints, lowerFillBasePoint, upperFillBasePoint +*/ +void QCPGraph::removeFillBasePoints(QVector *lineData) const +{ + lineData->remove(lineData->size()-2, 2); +} + +/*! \internal + + called by \ref addFillBasePoints to conveniently assign the point which closes the fill polygon + on the lower side of the zero-value-line parallel to the key axis. The logarithmic axis scale + case is a bit special, since the zero-value-line in pixel coordinates is in positive or negative + infinity. So this case is handled separately by just closing the fill polygon on the axis which + lies in the direction towards the zero value. + + \a lowerKey will be the the key (in pixels) of the returned point. Depending on whether the key + axis is horizontal or vertical, \a lowerKey will end up as the x or y value of the returned + point, respectively. + + \see upperFillBasePoint, addFillBasePoints +*/ +QPointF QCPGraph::lowerFillBasePoint(double lowerKey) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } + + QPointF point; + if (valueAxis->scaleType() == QCPAxis::stLinear) + { + if (keyAxis->axisType() == QCPAxis::atLeft) + { + point.setX(valueAxis->coordToPixel(0)); + point.setY(lowerKey); + } else if (keyAxis->axisType() == QCPAxis::atRight) + { + point.setX(valueAxis->coordToPixel(0)); + point.setY(lowerKey); + } else if (keyAxis->axisType() == QCPAxis::atTop) + { + point.setX(lowerKey); + point.setY(valueAxis->coordToPixel(0)); + } else if (keyAxis->axisType() == QCPAxis::atBottom) + { + point.setX(lowerKey); + point.setY(valueAxis->coordToPixel(0)); + } + } else // valueAxis->mScaleType == QCPAxis::stLogarithmic + { + // In logarithmic scaling we can't just draw to value zero so we just fill all the way + // to the axis which is in the direction towards zero + if (keyAxis->orientation() == Qt::Vertical) + { + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis + point.setX(keyAxis->axisRect()->right()); + else + point.setX(keyAxis->axisRect()->left()); + point.setY(lowerKey); + } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) + { + point.setX(lowerKey); + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis + point.setY(keyAxis->axisRect()->top()); + else + point.setY(keyAxis->axisRect()->bottom()); + } + } + return point; +} + +/*! \internal + + called by \ref addFillBasePoints to conveniently assign the point which closes the fill + polygon on the upper side of the zero-value-line parallel to the key axis. The logarithmic axis + scale case is a bit special, since the zero-value-line in pixel coordinates is in positive or + negative infinity. So this case is handled separately by just closing the fill polygon on the + axis which lies in the direction towards the zero value. + + \a upperKey will be the the key (in pixels) of the returned point. Depending on whether the key + axis is horizontal or vertical, \a upperKey will end up as the x or y value of the returned + point, respectively. + + \see lowerFillBasePoint, addFillBasePoints +*/ +QPointF QCPGraph::upperFillBasePoint(double upperKey) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPointF(); } + + QPointF point; + if (valueAxis->scaleType() == QCPAxis::stLinear) + { + if (keyAxis->axisType() == QCPAxis::atLeft) + { + point.setX(valueAxis->coordToPixel(0)); + point.setY(upperKey); + } else if (keyAxis->axisType() == QCPAxis::atRight) + { + point.setX(valueAxis->coordToPixel(0)); + point.setY(upperKey); + } else if (keyAxis->axisType() == QCPAxis::atTop) + { + point.setX(upperKey); + point.setY(valueAxis->coordToPixel(0)); + } else if (keyAxis->axisType() == QCPAxis::atBottom) + { + point.setX(upperKey); + point.setY(valueAxis->coordToPixel(0)); + } + } else // valueAxis->mScaleType == QCPAxis::stLogarithmic + { + // In logarithmic scaling we can't just draw to value 0 so we just fill all the way + // to the axis which is in the direction towards 0 + if (keyAxis->orientation() == Qt::Vertical) + { + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis + point.setX(keyAxis->axisRect()->right()); + else + point.setX(keyAxis->axisRect()->left()); + point.setY(upperKey); + } else if (keyAxis->axisType() == QCPAxis::atTop || keyAxis->axisType() == QCPAxis::atBottom) + { + point.setX(upperKey); + if ((valueAxis->range().upper < 0 && !valueAxis->rangeReversed()) || + (valueAxis->range().upper > 0 && valueAxis->rangeReversed())) // if range is negative, zero is on opposite side of key axis + point.setY(keyAxis->axisRect()->top()); + else + point.setY(keyAxis->axisRect()->bottom()); + } + } + return point; +} + +/*! \internal + + Generates the polygon needed for drawing channel fills between this graph (data passed via \a + lineData) and the graph specified by mChannelFillGraph (data generated by calling its \ref + getPlotData function). May return an empty polygon if the key ranges have no overlap or fill + target graph and this graph don't have same orientation (i.e. both key axes horizontal or both + key axes vertical). For increased performance (due to implicit sharing), keep the returned + QPolygonF const. +*/ +const QPolygonF QCPGraph::getChannelFillPolygon(const QVector *lineData) const +{ + if (!mChannelFillGraph) + return QPolygonF(); + + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); } + if (!mChannelFillGraph.data()->mKeyAxis) { qDebug() << Q_FUNC_INFO << "channel fill target key axis invalid"; return QPolygonF(); } + + if (mChannelFillGraph.data()->mKeyAxis.data()->orientation() != keyAxis->orientation()) + return QPolygonF(); // don't have same axis orientation, can't fill that (Note: if keyAxis fits, valueAxis will fit too, because it's always orthogonal to keyAxis) + + if (lineData->isEmpty()) return QPolygonF(); + QVector otherData; + mChannelFillGraph.data()->getPlotData(&otherData, 0); + if (otherData.isEmpty()) return QPolygonF(); + QVector thisData; + thisData.reserve(lineData->size()+otherData.size()); // because we will join both vectors at end of this function + for (int i=0; isize(); ++i) // don't use the vector<<(vector), it squeezes internally, which ruins the performance tuning with reserve() + thisData << lineData->at(i); + + // pointers to be able to swap them, depending which data range needs cropping: + QVector *staticData = &thisData; + QVector *croppedData = &otherData; + + // crop both vectors to ranges in which the keys overlap (which coord is key, depends on axisType): + if (keyAxis->orientation() == Qt::Horizontal) + { + // x is key + // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: + if (staticData->first().x() > staticData->last().x()) + { + int size = staticData->size(); + for (int i=0; ifirst().x() > croppedData->last().x()) + { + int size = croppedData->size(); + for (int i=0; ifirst().x() < croppedData->first().x()) // other one must be cropped + qSwap(staticData, croppedData); + int lowBound = findIndexBelowX(croppedData, staticData->first().x()); + if (lowBound == -1) return QPolygonF(); // key ranges have no overlap + croppedData->remove(0, lowBound); + // set lowest point of cropped data to fit exactly key position of first static data + // point via linear interpolation: + if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation + double slope; + if (croppedData->at(1).x()-croppedData->at(0).x() != 0) + slope = (croppedData->at(1).y()-croppedData->at(0).y())/(croppedData->at(1).x()-croppedData->at(0).x()); + else + slope = 0; + (*croppedData)[0].setY(croppedData->at(0).y()+slope*(staticData->first().x()-croppedData->at(0).x())); + (*croppedData)[0].setX(staticData->first().x()); + + // crop upper bound: + if (staticData->last().x() > croppedData->last().x()) // other one must be cropped + qSwap(staticData, croppedData); + int highBound = findIndexAboveX(croppedData, staticData->last().x()); + if (highBound == -1) return QPolygonF(); // key ranges have no overlap + croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); + // set highest point of cropped data to fit exactly key position of last static data + // point via linear interpolation: + if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation + int li = croppedData->size()-1; // last index + if (croppedData->at(li).x()-croppedData->at(li-1).x() != 0) + slope = (croppedData->at(li).y()-croppedData->at(li-1).y())/(croppedData->at(li).x()-croppedData->at(li-1).x()); + else + slope = 0; + (*croppedData)[li].setY(croppedData->at(li-1).y()+slope*(staticData->last().x()-croppedData->at(li-1).x())); + (*croppedData)[li].setX(staticData->last().x()); + } else // mKeyAxis->orientation() == Qt::Vertical + { + // y is key + // similar to "x is key" but switched x,y. Further, lower/upper meaning is inverted compared to x, + // because in pixel coordinates, y increases from top to bottom, not bottom to top like data coordinate. + // if an axis range is reversed, the data point keys will be descending. Reverse them, since following algorithm assumes ascending keys: + if (staticData->first().y() < staticData->last().y()) + { + int size = staticData->size(); + for (int i=0; ifirst().y() < croppedData->last().y()) + { + int size = croppedData->size(); + for (int i=0; ifirst().y() > croppedData->first().y()) // other one must be cropped + qSwap(staticData, croppedData); + int lowBound = findIndexAboveY(croppedData, staticData->first().y()); + if (lowBound == -1) return QPolygonF(); // key ranges have no overlap + croppedData->remove(0, lowBound); + // set lowest point of cropped data to fit exactly key position of first static data + // point via linear interpolation: + if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation + double slope; + if (croppedData->at(1).y()-croppedData->at(0).y() != 0) // avoid division by zero in step plots + slope = (croppedData->at(1).x()-croppedData->at(0).x())/(croppedData->at(1).y()-croppedData->at(0).y()); + else + slope = 0; + (*croppedData)[0].setX(croppedData->at(0).x()+slope*(staticData->first().y()-croppedData->at(0).y())); + (*croppedData)[0].setY(staticData->first().y()); + + // crop upper bound: + if (staticData->last().y() < croppedData->last().y()) // other one must be cropped + qSwap(staticData, croppedData); + int highBound = findIndexBelowY(croppedData, staticData->last().y()); + if (highBound == -1) return QPolygonF(); // key ranges have no overlap + croppedData->remove(highBound+1, croppedData->size()-(highBound+1)); + // set highest point of cropped data to fit exactly key position of last static data + // point via linear interpolation: + if (croppedData->size() < 2) return QPolygonF(); // need at least two points for interpolation + int li = croppedData->size()-1; // last index + if (croppedData->at(li).y()-croppedData->at(li-1).y() != 0) // avoid division by zero in step plots + slope = (croppedData->at(li).x()-croppedData->at(li-1).x())/(croppedData->at(li).y()-croppedData->at(li-1).y()); + else + slope = 0; + (*croppedData)[li].setX(croppedData->at(li-1).x()+slope*(staticData->last().y()-croppedData->at(li-1).y())); + (*croppedData)[li].setY(staticData->last().y()); + } + + // return joined: + for (int i=otherData.size()-1; i>=0; --i) // insert reversed, otherwise the polygon will be twisted + thisData << otherData.at(i); + return QPolygonF(thisData); +} + +/*! \internal + + Finds the smallest index of \a data, whose points x value is just above \a x. Assumes x values in + \a data points are ordered ascending, as is the case when plotting with horizontal key axis. + + Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. +*/ +int QCPGraph::findIndexAboveX(const QVector *data, double x) const +{ + for (int i=data->size()-1; i>=0; --i) + { + if (data->at(i).x() < x) + { + if (isize()-1) + return i+1; + else + return data->size()-1; + } + } + return -1; +} + +/*! \internal + + Finds the highest index of \a data, whose points x value is just below \a x. Assumes x values in + \a data points are ordered ascending, as is the case when plotting with horizontal key axis. + + Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. +*/ +int QCPGraph::findIndexBelowX(const QVector *data, double x) const +{ + for (int i=0; isize(); ++i) + { + if (data->at(i).x() > x) + { + if (i>0) + return i-1; + else + return 0; + } + } + return -1; +} + +/*! \internal + + Finds the smallest index of \a data, whose points y value is just above \a y. Assumes y values in + \a data points are ordered descending, as is the case when plotting with vertical key axis. + + Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. +*/ +int QCPGraph::findIndexAboveY(const QVector *data, double y) const +{ + for (int i=0; isize(); ++i) + { + if (data->at(i).y() < y) + { + if (i>0) + return i-1; + else + return 0; + } + } + return -1; +} + +/*! \internal + + Calculates the (minimum) distance (in pixels) the graph's representation has from the given \a + pixelPoint in pixels. This is used to determine whether the graph was clicked or not, e.g. in + \ref selectTest. + + If either the graph has no data or if the line style is \ref lsNone and the scatter style's shape + is \ref QCPScatterStyle::ssNone (i.e. there is no visual representation of the graph), returns + 500. +*/ +double QCPGraph::pointDistance(const QPointF &pixelPoint) const +{ + if (mData->isEmpty()) + { + qDebug() << Q_FUNC_INFO << "requested point distance on graph" << mName << "without data"; + return 500; + } + if (mData->size() == 1) + { + QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value); + return QVector2D(dataPoint-pixelPoint).length(); + } + + if (mLineStyle == lsNone && mScatterStyle.isNone()) + return 500; + + // calculate minimum distances to graph representation: + if (mLineStyle == lsNone) + { + // no line displayed, only calculate distance to scatter points: + QVector *scatterData = new QVector; + getScatterPlotData(scatterData); + double minDistSqr = std::numeric_limits::max(); + QPointF ptA; + QPointF ptB = coordsToPixels(scatterData->at(0).key, scatterData->at(0).value); // getScatterPlotData returns in plot coordinates, so transform to pixels + for (int i=1; isize(); ++i) + { + ptA = ptB; + ptB = coordsToPixels(scatterData->at(i).key, scatterData->at(i).value); + double currentDistSqr = distSqrToLine(ptA, ptB, pixelPoint); + if (currentDistSqr < minDistSqr) + minDistSqr = currentDistSqr; + } + delete scatterData; + return qSqrt(minDistSqr); + } else + { + // line displayed calculate distance to line segments: + QVector *lineData = new QVector; + getPlotData(lineData, 0); // unlike with getScatterPlotData we get pixel coordinates here + double minDistSqr = std::numeric_limits::max(); + if (mLineStyle == lsImpulse) + { + // impulse plot differs from other line styles in that the lineData points are only pairwise connected: + for (int i=0; isize()-1; i+=2) // iterate pairs + { + double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); + if (currentDistSqr < minDistSqr) + minDistSqr = currentDistSqr; + } + } else + { + // all other line plots (line and step) connect points directly: + for (int i=0; isize()-1; ++i) + { + double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); + if (currentDistSqr < minDistSqr) + minDistSqr = currentDistSqr; + } + } + delete lineData; + return qSqrt(minDistSqr); + } +} + +/*! \internal + + Finds the highest index of \a data, whose points y value is just below \a y. Assumes y values in + \a data points are ordered descending, as is the case when plotting with vertical key axis (since + keys are ordered ascending). + + Used to calculate the channel fill polygon, see \ref getChannelFillPolygon. +*/ +int QCPGraph::findIndexBelowY(const QVector *data, double y) const +{ + for (int i=data->size()-1; i>=0; --i) + { + if (data->at(i).y() > y) + { + if (isize()-1) + return i+1; + else + return data->size()-1; + } + } + return -1; +} + +/* inherits documentation from base class */ +QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain) const +{ + // just call the specialized version which takes an additional argument whether error bars + // should also be taken into consideration for range calculation. We set this to true here. + return getKeyRange(foundRange, inSignDomain, true); +} + +/* inherits documentation from base class */ +QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain) const +{ + // just call the specialized version which takes an additional argument whether error bars + // should also be taken into consideration for range calculation. We set this to true here. + return getValueRange(foundRange, inSignDomain, true); +} + +/*! \overload + + Allows to specify whether the error bars should be included in the range calculation. + + \see getKeyRange(bool &foundRange, SignDomain inSignDomain) +*/ +QCPRange QCPGraph::getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const +{ + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + + double current, currentErrorMinus, currentErrorPlus; + + if (inSignDomain == sdBoth) // range may be anywhere + { + QCPDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().key; + currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); + currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); + if (current-currentErrorMinus < range.lower || !haveLower) + { + range.lower = current-currentErrorMinus; + haveLower = true; + } + if (current+currentErrorPlus > range.upper || !haveUpper) + { + range.upper = current+currentErrorPlus; + haveUpper = true; + } + ++it; + } + } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain + { + QCPDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().key; + currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); + currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); + if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0) + { + range.lower = current-currentErrorMinus; + haveLower = true; + } + if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0) + { + range.upper = current+currentErrorPlus; + haveUpper = true; + } + if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point. + { + if ((current < range.lower || !haveLower) && current < 0) + { + range.lower = current; + haveLower = true; + } + if ((current > range.upper || !haveUpper) && current < 0) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain + { + QCPDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().key; + currentErrorMinus = (includeErrors ? it.value().keyErrorMinus : 0); + currentErrorPlus = (includeErrors ? it.value().keyErrorPlus : 0); + if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0) + { + range.lower = current-currentErrorMinus; + haveLower = true; + } + if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0) + { + range.upper = current+currentErrorPlus; + haveUpper = true; + } + if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point. + { + if ((current < range.lower || !haveLower) && current > 0) + { + range.lower = current; + haveLower = true; + } + if ((current > range.upper || !haveUpper) && current > 0) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + } + + foundRange = haveLower && haveUpper; + return range; +} + +/*! \overload + + Allows to specify whether the error bars should be included in the range calculation. + + \see getValueRange(bool &foundRange, SignDomain inSignDomain) +*/ +QCPRange QCPGraph::getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const +{ + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + + double current, currentErrorMinus, currentErrorPlus; + + if (inSignDomain == sdBoth) // range may be anywhere + { + QCPDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().value; + currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); + currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); + if (current-currentErrorMinus < range.lower || !haveLower) + { + range.lower = current-currentErrorMinus; + haveLower = true; + } + if (current+currentErrorPlus > range.upper || !haveUpper) + { + range.upper = current+currentErrorPlus; + haveUpper = true; + } + ++it; + } + } else if (inSignDomain == sdNegative) // range may only be in the negative sign domain + { + QCPDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().value; + currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); + currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); + if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus < 0) + { + range.lower = current-currentErrorMinus; + haveLower = true; + } + if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus < 0) + { + range.upper = current+currentErrorPlus; + haveUpper = true; + } + if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to get that point. + { + if ((current < range.lower || !haveLower) && current < 0) + { + range.lower = current; + haveLower = true; + } + if ((current > range.upper || !haveUpper) && current < 0) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + } else if (inSignDomain == sdPositive) // range may only be in the positive sign domain + { + QCPDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().value; + currentErrorMinus = (includeErrors ? it.value().valueErrorMinus : 0); + currentErrorPlus = (includeErrors ? it.value().valueErrorPlus : 0); + if ((current-currentErrorMinus < range.lower || !haveLower) && current-currentErrorMinus > 0) + { + range.lower = current-currentErrorMinus; + haveLower = true; + } + if ((current+currentErrorPlus > range.upper || !haveUpper) && current+currentErrorPlus > 0) + { + range.upper = current+currentErrorPlus; + haveUpper = true; + } + if (includeErrors) // in case point is in valid sign domain but errobars stretch beyond it, we still want to geht that point. + { + if ((current < range.lower || !haveLower) && current > 0) + { + range.lower = current; + haveLower = true; + } + if ((current > range.upper || !haveUpper) && current > 0) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + } + + foundRange = haveLower && haveUpper; + return range; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPCurveData +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPCurveData + \brief Holds the data of one single data point for QCPCurve. + + The container for storing multiple data points is \ref QCPCurveDataMap. + + The stored data is: + \li \a t: the free parameter of the curve at this curve point (cp. the mathematical vector (x(t), y(t))) + \li \a key: coordinate on the key axis of this curve point + \li \a value: coordinate on the value axis of this curve point + + \see QCPCurveDataMap +*/ + +/*! + Constructs a curve data point with t, key and value set to zero. +*/ +QCPCurveData::QCPCurveData() : + t(0), + key(0), + value(0) +{ +} + +/*! + Constructs a curve data point with the specified \a t, \a key and \a value. +*/ +QCPCurveData::QCPCurveData(double t, double key, double value) : + t(t), + key(key), + value(value) +{ +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPCurve +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPCurve + \brief A plottable representing a parametric curve in a plot. + + \image html QCPCurve.png + + Unlike QCPGraph, plottables of this type may have multiple points with the same key coordinate, + so their visual representation can have \a loops. This is realized by introducing a third + coordinate \a t, which defines the order of the points described by the other two coordinates \a + x and \a y. + + To plot data, assign it with the \ref setData or \ref addData functions. + + \section appearance Changing the appearance + + The appearance of the curve is determined by the pen and the brush (\ref setPen, \ref setBrush). + \section usage Usage + + Like all data representing objects in QCustomPlot, the QCPCurve is a plottable (QCPAbstractPlottable). So + the plottable-interface of QCustomPlot applies (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) + + Usually, you first create an instance: + \code + QCPCurve *newCurve = new QCPCurve(customPlot->xAxis, customPlot->yAxis);\endcode + add it to the customPlot with QCustomPlot::addPlottable: + \code + customPlot->addPlottable(newCurve);\endcode + and then modify the properties of the newly created plottable, e.g.: + \code + newCurve->setName("Fermat's Spiral"); + newCurve->setData(tData, xData, yData);\endcode +*/ + +/*! + Constructs a curve which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value + axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have + the same orientation. If either of these restrictions is violated, a corresponding message is + printed to the debug output (qDebug), the construction is not aborted, though. + + The constructed QCPCurve can be added to the plot with QCustomPlot::addPlottable, QCustomPlot + then takes ownership of the graph. +*/ +QCPCurve::QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis) : + QCPAbstractPlottable(keyAxis, valueAxis) +{ + mData = new QCPCurveDataMap; + mPen.setColor(Qt::blue); + mPen.setStyle(Qt::SolidLine); + mBrush.setColor(Qt::blue); + mBrush.setStyle(Qt::NoBrush); + mSelectedPen = mPen; + mSelectedPen.setWidthF(2.5); + mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen + mSelectedBrush = mBrush; + + setScatterStyle(QCPScatterStyle()); + setLineStyle(lsLine); +} + +QCPCurve::~QCPCurve() +{ + delete mData; +} + +/*! + Replaces the current data with the provided \a data. + + If \a copy is set to true, data points in \a data will only be copied. if false, the plottable + takes ownership of the passed data and replaces the internal data pointer with it. This is + significantly faster than copying for large datasets. +*/ +void QCPCurve::setData(QCPCurveDataMap *data, bool copy) +{ + if (copy) + { + *mData = *data; + } else + { + delete mData; + mData = data; + } +} + +/*! \overload + + Replaces the current data with the provided points in \a t, \a key and \a value tuples. The + provided vectors should have equal length. Else, the number of added points will be the size of + the smallest vector. +*/ +void QCPCurve::setData(const QVector &t, const QVector &key, const QVector &value) +{ + mData->clear(); + int n = t.size(); + n = qMin(n, key.size()); + n = qMin(n, value.size()); + QCPCurveData newData; + for (int i=0; iinsertMulti(newData.t, newData); + } +} + +/*! \overload + + Replaces the current data with the provided \a key and \a value pairs. The t parameter + of each data point will be set to the integer index of the respective key/value pair. +*/ +void QCPCurve::setData(const QVector &key, const QVector &value) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + QCPCurveData newData; + for (int i=0; iinsertMulti(newData.t, newData); + } +} + +/*! + Sets the visual appearance of single data points in the plot. If set to \ref + QCPScatterStyle::ssNone, no scatter points are drawn (e.g. for line-only plots with appropriate + line style). + + \see QCPScatterStyle, setLineStyle +*/ +void QCPCurve::setScatterStyle(const QCPScatterStyle &style) +{ + mScatterStyle = style; +} + +/*! + Sets how the single data points are connected in the plot or how they are represented visually + apart from the scatter symbol. For scatter-only plots, set \a style to \ref lsNone and \ref + setScatterStyle to the desired scatter style. + + \see setScatterStyle +*/ +void QCPCurve::setLineStyle(QCPCurve::LineStyle style) +{ + mLineStyle = style; +} + +/*! + Adds the provided data points in \a dataMap to the current data. + \see removeData +*/ +void QCPCurve::addData(const QCPCurveDataMap &dataMap) +{ + mData->unite(dataMap); +} + +/*! \overload + Adds the provided single data point in \a data to the current data. + \see removeData +*/ +void QCPCurve::addData(const QCPCurveData &data) +{ + mData->insertMulti(data.t, data); +} + +/*! \overload + Adds the provided single data point as \a t, \a key and \a value tuple to the current data + \see removeData +*/ +void QCPCurve::addData(double t, double key, double value) +{ + QCPCurveData newData; + newData.t = t; + newData.key = key; + newData.value = value; + mData->insertMulti(newData.t, newData); +} + +/*! \overload + + Adds the provided single data point as \a key and \a value pair to the current data The t + parameter of the data point is set to the t of the last data point plus 1. If there is no last + data point, t will be set to 0. + + \see removeData +*/ +void QCPCurve::addData(double key, double value) +{ + QCPCurveData newData; + if (!mData->isEmpty()) + newData.t = (mData->constEnd()-1).key()+1; + else + newData.t = 0; + newData.key = key; + newData.value = value; + mData->insertMulti(newData.t, newData); +} + +/*! \overload + Adds the provided data points as \a t, \a key and \a value tuples to the current data. + \see removeData +*/ +void QCPCurve::addData(const QVector &ts, const QVector &keys, const QVector &values) +{ + int n = ts.size(); + n = qMin(n, keys.size()); + n = qMin(n, values.size()); + QCPCurveData newData; + for (int i=0; iinsertMulti(newData.t, newData); + } +} + +/*! + Removes all data points with curve parameter t smaller than \a t. + \see addData, clearData +*/ +void QCPCurve::removeDataBefore(double t) +{ + QCPCurveDataMap::iterator it = mData->begin(); + while (it != mData->end() && it.key() < t) + it = mData->erase(it); +} + +/*! + Removes all data points with curve parameter t greater than \a t. + \see addData, clearData +*/ +void QCPCurve::removeDataAfter(double t) +{ + if (mData->isEmpty()) return; + QCPCurveDataMap::iterator it = mData->upperBound(t); + while (it != mData->end()) + it = mData->erase(it); +} + +/*! + Removes all data points with curve parameter t between \a fromt and \a tot. if \a fromt is + greater or equal to \a tot, the function does nothing. To remove a single data point with known + t, use \ref removeData(double t). + + \see addData, clearData +*/ +void QCPCurve::removeData(double fromt, double tot) +{ + if (fromt >= tot || mData->isEmpty()) return; + QCPCurveDataMap::iterator it = mData->upperBound(fromt); + QCPCurveDataMap::iterator itEnd = mData->upperBound(tot); + while (it != itEnd) + it = mData->erase(it); +} + +/*! \overload + + Removes a single data point at curve parameter \a t. If the position is not known with absolute + precision, consider using \ref removeData(double fromt, double tot) with a small fuzziness + interval around the suspected position, depeding on the precision with which the curve parameter + is known. + + \see addData, clearData +*/ +void QCPCurve::removeData(double t) +{ + mData->remove(t); +} + +/*! + Removes all data points. + \see removeData, removeDataAfter, removeDataBefore +*/ +void QCPCurve::clearData() +{ + mData->clear(); +} + +/* inherits documentation from base class */ +double QCPCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if ((onlySelectable && !mSelectable) || mData->isEmpty()) + return -1; + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) + return pointDistance(pos); + else + return -1; +} + +/* inherits documentation from base class */ +void QCPCurve::draw(QCPPainter *painter) +{ + if (mData->isEmpty()) return; + + // allocate line vector: + QVector *lineData = new QVector; + + // fill with curve data: + getCurveData(lineData); + + // check data validity if flag set: +#ifdef QCUSTOMPLOT_CHECK_DATA + QCPCurveDataMap::const_iterator it; + for (it = mData->constBegin(); it != mData->constEnd(); ++it) + { + if (QCP::isInvalidData(it.value().t) || + QCP::isInvalidData(it.value().key, it.value().value)) + qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "invalid." << "Plottable name:" << name(); + } +#endif + + // draw curve fill: + if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) + { + applyFillAntialiasingHint(painter); + painter->setPen(Qt::NoPen); + painter->setBrush(mainBrush()); + painter->drawPolygon(QPolygonF(*lineData)); + } + + // draw curve line: + if (mLineStyle != lsNone && mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) + { + applyDefaultAntialiasingHint(painter); + painter->setPen(mainPen()); + painter->setBrush(Qt::NoBrush); + // if drawing solid line and not in PDF, use much faster line drawing instead of polyline: + if (mParentPlot->plottingHints().testFlag(QCP::phFastPolylines) && + painter->pen().style() == Qt::SolidLine && + !painter->modes().testFlag(QCPPainter::pmVectorized) && + !painter->modes().testFlag(QCPPainter::pmNoCaching)) + { + int i = 1; + int lineDataSize = lineData->size(); + while (i < lineDataSize) + { + if (!qIsNaN(lineData->at(i).y()) && !qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line + painter->drawLine(lineData->at(i-1), lineData->at(i)); + else + ++i; + ++i; + } + } else + { + int segmentStart = 0; + int i = 0; + int lineDataSize = lineData->size(); + while (i < lineDataSize) + { + if (qIsNaN(lineData->at(i).y()) || qIsNaN(lineData->at(i).x())) // NaNs create a gap in the line + { + painter->drawPolyline(lineData->constData()+segmentStart, i-segmentStart); // i, because we don't want to include the current NaN point + segmentStart = i+1; + } + ++i; + } + // draw last segment: + painter->drawPolyline(lineData->constData()+segmentStart, lineDataSize-segmentStart); // lineDataSize, because we do want to include the last point + } + } + + // draw scatters: + if (!mScatterStyle.isNone()) + drawScatterPlot(painter, lineData); + + // free allocated line data: + delete lineData; +} + +/* inherits documentation from base class */ +void QCPCurve::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const +{ + // draw fill: + if (mBrush.style() != Qt::NoBrush) + { + applyFillAntialiasingHint(painter); + painter->fillRect(QRectF(rect.left(), rect.top()+rect.height()/2.0, rect.width(), rect.height()/3.0), mBrush); + } + // draw line vertically centered: + if (mLineStyle != lsNone) + { + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->drawLine(QLineF(rect.left(), rect.top()+rect.height()/2.0, rect.right()+5, rect.top()+rect.height()/2.0)); // +5 on x2 else last segment is missing from dashed/dotted pens + } + // draw scatter symbol: + if (!mScatterStyle.isNone()) + { + applyScattersAntialiasingHint(painter); + // scale scatter pixmap if it's too large to fit in legend icon rect: + if (mScatterStyle.shape() == QCPScatterStyle::ssPixmap && (mScatterStyle.pixmap().size().width() > rect.width() || mScatterStyle.pixmap().size().height() > rect.height())) + { + QCPScatterStyle scaledStyle(mScatterStyle); + scaledStyle.setPixmap(scaledStyle.pixmap().scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::SmoothTransformation)); + scaledStyle.applyTo(painter, mPen); + scaledStyle.drawShape(painter, QRectF(rect).center()); + } else + { + mScatterStyle.applyTo(painter, mPen); + mScatterStyle.drawShape(painter, QRectF(rect).center()); + } + } +} + +/*! \internal + + Draws scatter symbols at every data point passed in \a pointData. scatter symbols are independent of + the line style and are always drawn if scatter shape is not \ref QCPScatterStyle::ssNone. +*/ +void QCPCurve::drawScatterPlot(QCPPainter *painter, const QVector *pointData) const +{ + // draw scatter point symbols: + applyScattersAntialiasingHint(painter); + mScatterStyle.applyTo(painter, mPen); + for (int i=0; isize(); ++i) + if (!qIsNaN(pointData->at(i).x()) && !qIsNaN(pointData->at(i).y())) + mScatterStyle.drawShape(painter, pointData->at(i)); +} + +/*! \internal + + called by QCPCurve::draw to generate a point vector (in pixel coordinates) which represents the + line of the curve. + + Line segments that aren't visible in the current axis rect are handled in an optimized way. They + are projected onto a rectangle slightly larger than the visible axis rect and simplified + regarding point count. The algorithm makes sure to preserve appearance of lines and fills inside + the visible axis rect by generating new temporary points on the outer rect if necessary. + + Methods that are also involved in the algorithm are: \ref getRegion, \ref getOptimizedPoint, \ref + getOptimizedCornerPoints \ref mayTraverse, \ref getTraverse, \ref getTraverseCornerPoints. +*/ +void QCPCurve::getCurveData(QVector *lineData) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + + // add margins to rect to compensate for stroke width + double strokeMargin = qMax(qreal(1.0), qreal(mainPen().widthF()*0.75)); // stroke radius + 50% safety + if (!mScatterStyle.isNone()) + strokeMargin = qMax(strokeMargin, mScatterStyle.size()); + double rectLeft = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().lower)-strokeMargin*((keyAxis->orientation()==Qt::Vertical)!=keyAxis->rangeReversed()?-1:1)); + double rectRight = keyAxis->pixelToCoord(keyAxis->coordToPixel(keyAxis->range().upper)+strokeMargin*((keyAxis->orientation()==Qt::Vertical)!=keyAxis->rangeReversed()?-1:1)); + double rectBottom = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().lower)+strokeMargin*((valueAxis->orientation()==Qt::Horizontal)!=valueAxis->rangeReversed()?-1:1)); + double rectTop = valueAxis->pixelToCoord(valueAxis->coordToPixel(valueAxis->range().upper)-strokeMargin*((valueAxis->orientation()==Qt::Horizontal)!=valueAxis->rangeReversed()?-1:1)); + int currentRegion; + QCPCurveDataMap::const_iterator it = mData->constBegin(); + QCPCurveDataMap::const_iterator prevIt = mData->constEnd()-1; + int prevRegion = getRegion(prevIt.value().key, prevIt.value().value, rectLeft, rectTop, rectRight, rectBottom); + QVector trailingPoints; // points that must be applied after all other points (are generated only when handling first point to get virtual segment between last and first point right) + while (it != mData->constEnd()) + { + currentRegion = getRegion(it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); + if (currentRegion != prevRegion) // changed region, possibly need to add some optimized edge points or original points if entering R + { + if (currentRegion != 5) // segment doesn't end in R, so it's a candidate for removal + { + QPointF crossA, crossB; + if (prevRegion == 5) // we're coming from R, so add this point optimized + { + lineData->append(getOptimizedPoint(currentRegion, it.value().key, it.value().value, prevIt.value().key, prevIt.value().value, rectLeft, rectTop, rectRight, rectBottom)); + // in the situations 5->1/7/9/3 the segment may leave R and directly cross through two outer regions. In these cases we need to add an additional corner point + *lineData << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); + } else if (mayTraverse(prevRegion, currentRegion) && + getTraverse(prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom, crossA, crossB)) + { + // add the two cross points optimized if segment crosses R and if segment isn't virtual zeroth segment between last and first curve point: + QVector beforeTraverseCornerPoints, afterTraverseCornerPoints; + getTraverseCornerPoints(prevRegion, currentRegion, rectLeft, rectTop, rectRight, rectBottom, beforeTraverseCornerPoints, afterTraverseCornerPoints); + if (it != mData->constBegin()) + { + *lineData << beforeTraverseCornerPoints; + lineData->append(crossA); + lineData->append(crossB); + *lineData << afterTraverseCornerPoints; + } else + { + lineData->append(crossB); + *lineData << afterTraverseCornerPoints; + trailingPoints << beforeTraverseCornerPoints << crossA ; + } + } else // doesn't cross R, line is just moving around in outside regions, so only need to add optimized point(s) at the boundary corner(s) + { + *lineData << getOptimizedCornerPoints(prevRegion, currentRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); + } + } else // segment does end in R, so we add previous point optimized and this point at original position + { + if (it == mData->constBegin()) // it is first point in curve and prevIt is last one. So save optimized point for adding it to the lineData in the end + trailingPoints << getOptimizedPoint(prevRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom); + else + lineData->append(getOptimizedPoint(prevRegion, prevIt.value().key, prevIt.value().value, it.value().key, it.value().value, rectLeft, rectTop, rectRight, rectBottom)); + lineData->append(coordsToPixels(it.value().key, it.value().value)); + } + } else // region didn't change + { + if (currentRegion == 5) // still in R, keep adding original points + { + lineData->append(coordsToPixels(it.value().key, it.value().value)); + } else // still outside R, no need to add anything + { + // see how this is not doing anything? That's the main optimization... + } + } + prevIt = it; + prevRegion = currentRegion; + ++it; + } + *lineData << trailingPoints; +} + +/*! \internal + + This function is part of the curve optimization algorithm of \ref getCurveData. + + It returns the region of the given point (\a x, \a y) with respect to a rectangle defined by \a + rectLeft, \a rectTop, \a rectRight, and \a rectBottom. + + The regions are enumerated from top to bottom and left to right: + + + + + +
147
258
369
+ + With the rectangle being region 5, and the outer regions extending infinitely outwards. In the + curve optimization algorithm, region 5 is considered to be the visible portion of the plot. +*/ +int QCPCurve::getRegion(double x, double y, double rectLeft, double rectTop, double rectRight, double rectBottom) const +{ + if (x < rectLeft) // region 123 + { + if (y > rectTop) + return 1; + else if (y < rectBottom) + return 3; + else + return 2; + } else if (x > rectRight) // region 789 + { + if (y > rectTop) + return 7; + else if (y < rectBottom) + return 9; + else + return 8; + } else // region 456 + { + if (y > rectTop) + return 4; + else if (y < rectBottom) + return 6; + else + return 5; + } +} + +/*! \internal + + This function is part of the curve optimization algorithm of \ref getCurveData. + + This method is used in case the current segment passes from inside the visible rect (region 5, + see \ref getRegion) to any of the outer regions (\a otherRegion). The current segment is given by + the line connecting (\a key, \a value) with (\a otherKey, \a otherValue). + + It returns the intersection point of the segment with the border of region 5. + + For this function it doesn't matter whether (\a key, \a value) is the point inside region 5 or + whether it's (\a otherKey, \a otherValue), i.e. whether the segment is coming from region 5 or + leaving it. It is important though that \a otherRegion correctly identifies the other region not + equal to 5. +*/ +QPointF QCPCurve::getOptimizedPoint(int otherRegion, double otherKey, double otherValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const +{ + double intersectKey = rectLeft; // initial value is just fail-safe + double intersectValue = rectTop; // initial value is just fail-safe + switch (otherRegion) + { + case 1: // top and left edge + { + intersectValue = rectTop; + intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); + if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: + { + intersectKey = rectLeft; + intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); + } + break; + } + case 2: // left edge + { + intersectKey = rectLeft; + intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); + break; + } + case 3: // bottom and left edge + { + intersectValue = rectBottom; + intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); + if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: + { + intersectKey = rectLeft; + intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); + } + break; + } + case 4: // top edge + { + intersectValue = rectTop; + intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); + break; + } + case 5: + { + break; // case 5 shouldn't happen for this function but we add it anyway to prevent potential discontinuity in branch table + } + case 6: // bottom edge + { + intersectValue = rectBottom; + intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); + break; + } + case 7: // top and right edge + { + intersectValue = rectTop; + intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); + if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: + { + intersectKey = rectRight; + intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); + } + break; + } + case 8: // right edge + { + intersectKey = rectRight; + intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); + break; + } + case 9: // bottom and right edge + { + intersectValue = rectBottom; + intersectKey = otherKey + (key-otherKey)/(value-otherValue)*(intersectValue-otherValue); + if (intersectKey < rectLeft || intersectKey > rectRight) // doesn't intersect, so must intersect other: + { + intersectKey = rectRight; + intersectValue = otherValue + (value-otherValue)/(key-otherKey)*(intersectKey-otherKey); + } + break; + } + } + return coordsToPixels(intersectKey, intersectValue); +} + +/*! \internal + + This function is part of the curve optimization algorithm of \ref getCurveData. + + In situations where a single segment skips over multiple regions it might become necessary to add + extra points at the corners of region 5 (see \ref getRegion) such that the optimized segment + doesn't unintentionally cut through the visible area of the axis rect and create plot artifacts. + This method provides these points that must be added, assuming the original segment doesn't + start, end, or traverse region 5. (Corner points where region 5 is traversed are calculated by + \ref getTraverseCornerPoints.) + + For example, consider a segment which directly goes from region 4 to 2 but originally is far out + to the top left such that it doesn't cross region 5. Naively optimizing these points by + projecting them on the top and left borders of region 5 will create a segment that surely crosses + 5, creating a visual artifact in the plot. This method prevents this by providing extra points at + the top left corner, making the optimized curve correctly pass from region 4 to 1 to 2 without + traversing 5. +*/ +QVector QCPCurve::getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const +{ + QVector result; + switch (prevRegion) + { + case 1: + { + switch (currentRegion) + { + case 2: { result << coordsToPixels(rectLeft, rectTop); break; } + case 4: { result << coordsToPixels(rectLeft, rectTop); break; } + case 3: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); break; } + case 7: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); break; } + case 6: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } + case 8: { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } + case 9: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points + if ((value-prevValue)/(key-prevKey)*(rectLeft-key)+value < rectBottom) // segment passes below R + { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); } + else + { result << coordsToPixels(rectLeft, rectTop) << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); } + break; + } + } + break; + } + case 2: + { + switch (currentRegion) + { + case 1: { result << coordsToPixels(rectLeft, rectTop); break; } + case 3: { result << coordsToPixels(rectLeft, rectBottom); break; } + case 4: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } + case 6: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } + case 7: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); break; } + case 9: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); break; } + } + break; + } + case 3: + { + switch (currentRegion) + { + case 2: { result << coordsToPixels(rectLeft, rectBottom); break; } + case 6: { result << coordsToPixels(rectLeft, rectBottom); break; } + case 1: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); break; } + case 9: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); break; } + case 4: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } + case 8: { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } + case 7: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points + if ((value-prevValue)/(key-prevKey)*(rectRight-key)+value < rectBottom) // segment passes below R + { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); } + else + { result << coordsToPixels(rectLeft, rectBottom) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); } + break; + } + } + break; + } + case 4: + { + switch (currentRegion) + { + case 1: { result << coordsToPixels(rectLeft, rectTop); break; } + case 7: { result << coordsToPixels(rectRight, rectTop); break; } + case 2: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } + case 8: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } + case 3: { result << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); break; } + case 9: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectRight, rectBottom); break; } + } + break; + } + case 5: + { + switch (currentRegion) + { + case 1: { result << coordsToPixels(rectLeft, rectTop); break; } + case 7: { result << coordsToPixels(rectRight, rectTop); break; } + case 9: { result << coordsToPixels(rectRight, rectBottom); break; } + case 3: { result << coordsToPixels(rectLeft, rectBottom); break; } + } + break; + } + case 6: + { + switch (currentRegion) + { + case 3: { result << coordsToPixels(rectLeft, rectBottom); break; } + case 9: { result << coordsToPixels(rectRight, rectBottom); break; } + case 2: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } + case 8: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } + case 1: { result << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); break; } + case 7: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectRight, rectTop); break; } + } + break; + } + case 7: + { + switch (currentRegion) + { + case 4: { result << coordsToPixels(rectRight, rectTop); break; } + case 8: { result << coordsToPixels(rectRight, rectTop); break; } + case 1: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); break; } + case 9: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); break; } + case 2: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); break; } + case 6: { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } + case 3: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points + if ((value-prevValue)/(key-prevKey)*(rectRight-key)+value < rectBottom) // segment passes below R + { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); } + else + { result << coordsToPixels(rectRight, rectTop) << coordsToPixels(rectLeft, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); } + break; + } + } + break; + } + case 8: + { + switch (currentRegion) + { + case 7: { result << coordsToPixels(rectRight, rectTop); break; } + case 9: { result << coordsToPixels(rectRight, rectBottom); break; } + case 4: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } + case 6: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); break; } + case 1: { result << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); break; } + case 3: { result << coordsToPixels(rectRight, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectBottom); break; } + } + break; + } + case 9: + { + switch (currentRegion) + { + case 6: { result << coordsToPixels(rectRight, rectBottom); break; } + case 8: { result << coordsToPixels(rectRight, rectBottom); break; } + case 3: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); break; } + case 7: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); break; } + case 2: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); break; } + case 4: { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); result.append(result.last()); break; } + case 1: { // in this case we need another distinction of cases: segment may pass below or above rect, requiring either bottom right or top left corner points + if ((value-prevValue)/(key-prevKey)*(rectLeft-key)+value < rectBottom) // segment passes below R + { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectLeft, rectBottom); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); } + else + { result << coordsToPixels(rectRight, rectBottom) << coordsToPixels(rectRight, rectTop); result.append(result.last()); result << coordsToPixels(rectLeft, rectTop); } + break; + } + } + break; + } + } + return result; +} + +/*! \internal + + This function is part of the curve optimization algorithm of \ref getCurveData. + + This method returns whether a segment going from \a prevRegion to \a currentRegion (see \ref + getRegion) may traverse the visible region 5. This function assumes that neither \a prevRegion + nor \a currentRegion is 5 itself. + + If this method returns false, the segment for sure doesn't pass region 5. If it returns true, the + segment may or may not pass region 5 and a more fine-grained calculation must be used (\ref + getTraverse). +*/ +bool QCPCurve::mayTraverse(int prevRegion, int currentRegion) const +{ + switch (prevRegion) + { + case 1: + { + switch (currentRegion) + { + case 4: + case 7: + case 2: + case 3: return false; + default: return true; + } + } + case 2: + { + switch (currentRegion) + { + case 1: + case 3: return false; + default: return true; + } + } + case 3: + { + switch (currentRegion) + { + case 1: + case 2: + case 6: + case 9: return false; + default: return true; + } + } + case 4: + { + switch (currentRegion) + { + case 1: + case 7: return false; + default: return true; + } + } + case 5: return false; // should never occur + case 6: + { + switch (currentRegion) + { + case 3: + case 9: return false; + default: return true; + } + } + case 7: + { + switch (currentRegion) + { + case 1: + case 4: + case 8: + case 9: return false; + default: return true; + } + } + case 8: + { + switch (currentRegion) + { + case 7: + case 9: return false; + default: return true; + } + } + case 9: + { + switch (currentRegion) + { + case 3: + case 6: + case 8: + case 7: return false; + default: return true; + } + } + default: return true; + } +} + + +/*! \internal + + This function is part of the curve optimization algorithm of \ref getCurveData. + + This method assumes that the \ref mayTraverse test has returned true, so there is a chance the + segment defined by (\a prevKey, \a prevValue) and (\a key, \a value) goes through the visible + region 5. + + The return value of this method indicates whether the segment actually traverses region 5 or not. + + If the segment traverses 5, the output parameters \a crossA and \a crossB indicate the entry and + exit points of region 5. They will become the optimized points for that segment. +*/ +bool QCPCurve::getTraverse(double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom, QPointF &crossA, QPointF &crossB) const +{ + QList intersections; // x of QVector2D corresponds to key and y to value + if (qFuzzyIsNull(key-prevKey)) // line is parallel to value axis + { + // due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is traversed here + intersections.append(QVector2D(key, rectBottom)); // direction will be taken care of at end of method + intersections.append(QVector2D(key, rectTop)); + } else if (qFuzzyIsNull(value-prevValue)) // line is parallel to key axis + { + // due to region filter in mayTraverseR(), if line is parallel to value or key axis, R is traversed here + intersections.append(QVector2D(rectLeft, value)); // direction will be taken care of at end of method + intersections.append(QVector2D(rectRight, value)); + } else // line is skewed + { + double gamma; + double keyPerValue = (key-prevKey)/(value-prevValue); + // check top of rect: + gamma = prevKey + (rectTop-prevValue)*keyPerValue; + if (gamma >= rectLeft && gamma <= rectRight) + intersections.append(QVector2D(gamma, rectTop)); + // check bottom of rect: + gamma = prevKey + (rectBottom-prevValue)*keyPerValue; + if (gamma >= rectLeft && gamma <= rectRight) + intersections.append(QVector2D(gamma, rectBottom)); + double valuePerKey = 1.0/keyPerValue; + // check left of rect: + gamma = prevValue + (rectLeft-prevKey)*valuePerKey; + if (gamma >= rectBottom && gamma <= rectTop) + intersections.append(QVector2D(rectLeft, gamma)); + // check right of rect: + gamma = prevValue + (rectRight-prevKey)*valuePerKey; + if (gamma >= rectBottom && gamma <= rectTop) + intersections.append(QVector2D(rectRight, gamma)); + } + + // handle cases where found points isn't exactly 2: + if (intersections.size() > 2) + { + // line probably goes through corner of rect, and we got duplicate points there. single out the point pair with greatest distance in between: + double distSqrMax = 0; + QVector2D pv1, pv2; + for (int i=0; i distSqrMax) + { + pv1 = intersections.at(i); + pv2 = intersections.at(k); + distSqrMax = distSqr; + } + } + } + intersections = QList() << pv1 << pv2; + } else if (intersections.size() != 2) + { + // one or even zero points found (shouldn't happen unless line perfectly tangent to corner), no need to draw segment + return false; + } + + // possibly re-sort points so optimized point segment has same direction as original segment: + if ((key-prevKey)*(intersections.at(1).x()-intersections.at(0).x()) + (value-prevValue)*(intersections.at(1).y()-intersections.at(0).y()) < 0) // scalar product of both segments < 0 -> opposite direction + intersections.swap(0, 1); + crossA = coordsToPixels(intersections.at(0).x(), intersections.at(0).y()); + crossB = coordsToPixels(intersections.at(1).x(), intersections.at(1).y()); + return true; +} + +/*! \internal + + This function is part of the curve optimization algorithm of \ref getCurveData. + + This method assumes that the \ref getTraverse test has returned true, so the segment definitely + traverses the visible region 5 when going from \a prevRegion to \a currentRegion. + + In certain situations it is not sufficient to merely generate the entry and exit points of the + segment into/out of region 5, as \ref getTraverse provides. It may happen that a single segment, in + addition to traversing region 5, skips another region outside of region 5, which makes it + necessary to add an optimized corner point there (very similar to the job \ref + getOptimizedCornerPoints does for segments that are completely in outside regions and don't + traverse 5). + + As an example, consider a segment going from region 1 to region 6, traversing the lower left + corner of region 5. In this configuration, the segment additionally crosses the border between + region 1 and 2 before entering region 5. This makes it necessary to add an additional point in + the top left corner, before adding the optimized traverse points. So in this case, the output + parameter \a beforeTraverse will contain the top left corner point, and \a afterTraverse will be + empty. + + In some cases, such as when going from region 1 to 9, it may even be necessary to add additional + corner points before and after the traverse. Then both \a beforeTraverse and \a afterTraverse + return the respective corner points. +*/ +void QCPCurve::getTraverseCornerPoints(int prevRegion, int currentRegion, double rectLeft, double rectTop, double rectRight, double rectBottom, QVector &beforeTraverse, QVector &afterTraverse) const +{ + switch (prevRegion) + { + case 1: + { + switch (currentRegion) + { + case 6: { beforeTraverse << coordsToPixels(rectLeft, rectTop); break; } + case 9: { beforeTraverse << coordsToPixels(rectLeft, rectTop); afterTraverse << coordsToPixels(rectRight, rectBottom); break; } + case 8: { beforeTraverse << coordsToPixels(rectLeft, rectTop); break; } + } + break; + } + case 2: + { + switch (currentRegion) + { + case 7: { afterTraverse << coordsToPixels(rectRight, rectTop); break; } + case 9: { afterTraverse << coordsToPixels(rectRight, rectBottom); break; } + } + break; + } + case 3: + { + switch (currentRegion) + { + case 4: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); break; } + case 7: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); afterTraverse << coordsToPixels(rectRight, rectTop); break; } + case 8: { beforeTraverse << coordsToPixels(rectLeft, rectBottom); break; } + } + break; + } + case 4: + { + switch (currentRegion) + { + case 3: { afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } + case 9: { afterTraverse << coordsToPixels(rectRight, rectBottom); break; } + } + break; + } + case 5: { break; } // shouldn't happen because this method only handles full traverses + case 6: + { + switch (currentRegion) + { + case 1: { afterTraverse << coordsToPixels(rectLeft, rectTop); break; } + case 7: { afterTraverse << coordsToPixels(rectRight, rectTop); break; } + } + break; + } + case 7: + { + switch (currentRegion) + { + case 2: { beforeTraverse << coordsToPixels(rectRight, rectTop); break; } + case 3: { beforeTraverse << coordsToPixels(rectRight, rectTop); afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } + case 6: { beforeTraverse << coordsToPixels(rectRight, rectTop); break; } + } + break; + } + case 8: + { + switch (currentRegion) + { + case 1: { afterTraverse << coordsToPixels(rectLeft, rectTop); break; } + case 3: { afterTraverse << coordsToPixels(rectLeft, rectBottom); break; } + } + break; + } + case 9: + { + switch (currentRegion) + { + case 2: { beforeTraverse << coordsToPixels(rectRight, rectBottom); break; } + case 1: { beforeTraverse << coordsToPixels(rectRight, rectBottom); afterTraverse << coordsToPixels(rectLeft, rectTop); break; } + case 4: { beforeTraverse << coordsToPixels(rectRight, rectBottom); break; } + } + break; + } + } +} + +/*! \internal + + Calculates the (minimum) distance (in pixels) the curve's representation has from the given \a + pixelPoint in pixels. This is used to determine whether the curve was clicked or not, e.g. in + \ref selectTest. +*/ +double QCPCurve::pointDistance(const QPointF &pixelPoint) const +{ + if (mData->isEmpty()) + { + qDebug() << Q_FUNC_INFO << "requested point distance on curve" << mName << "without data"; + return 500; + } + if (mData->size() == 1) + { + QPointF dataPoint = coordsToPixels(mData->constBegin().key(), mData->constBegin().value().value); + return QVector2D(dataPoint-pixelPoint).length(); + } + + // calculate minimum distance to line segments: + QVector *lineData = new QVector; + getCurveData(lineData); + double minDistSqr = std::numeric_limits::max(); + for (int i=0; isize()-1; ++i) + { + double currentDistSqr = distSqrToLine(lineData->at(i), lineData->at(i+1), pixelPoint); + if (currentDistSqr < minDistSqr) + minDistSqr = currentDistSqr; + } + delete lineData; + return qSqrt(minDistSqr); +} + +/* inherits documentation from base class */ +QCPRange QCPCurve::getKeyRange(bool &foundRange, SignDomain inSignDomain) const +{ + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + + double current; + + QCPCurveDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().key; + if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) + { + if (current < range.lower || !haveLower) + { + range.lower = current; + haveLower = true; + } + if (current > range.upper || !haveUpper) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + + foundRange = haveLower && haveUpper; + return range; +} + +/* inherits documentation from base class */ +QCPRange QCPCurve::getValueRange(bool &foundRange, SignDomain inSignDomain) const +{ + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + + double current; + + QCPCurveDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().value; + if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) + { + if (current < range.lower || !haveLower) + { + range.lower = current; + haveLower = true; + } + if (current > range.upper || !haveUpper) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + + foundRange = haveLower && haveUpper; + return range; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPBarsGroup +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPBarsGroup + \brief Groups multiple QCPBars together so they appear side by side + + \image html QCPBarsGroup.png + + When showing multiple QCPBars in one plot which have bars at identical keys, it may be desirable + to have them appearing next to each other at each key. This is what adding the respective QCPBars + plottables to a QCPBarsGroup achieves. (An alternative approach is to stack them on top of each + other, see \ref QCPBars::moveAbove.) + + \section qcpbarsgroup-usage Usage + + To add a QCPBars plottable to the group, create a new group and then add the respective bars + intances: + \code + QCPBarsGroup *group = new QCPBarsGroup(customPlot); + group->append(bars1); + group->append(bars2); + \endcode + Alternatively to appending to the group like shown above, you can also set the group on the + QCPBars plottable via \ref QCPBars::setBarsGroup. + + The spacing between the bars can be configured via \ref setSpacingType and \ref setSpacing. The + bars in this group appear in the plot in the order they were appended. To insert a bars plottable + at a certain index position, or to reposition a bars plottable which is already in the group, use + \ref insert. + + To remove specific bars from the group, use either \ref remove or call \ref + QCPBars::setBarsGroup "QCPBars::setBarsGroup(0)" on the respective bars plottable. + + To clear the entire group, call \ref clear, or simply delete the group. +*/ + +/* start of documentation of inline functions */ + +/*! \fn QList QCPBarsGroup::bars() const + + Returns all bars currently in this group. + + \see bars(int index) +*/ + +/*! \fn int QCPBarsGroup::size() const + + Returns the number of QCPBars plottables that are part of this group. + +*/ + +/*! \fn bool QCPBarsGroup::isEmpty() const + + Returns whether this bars group is empty. + + \see size +*/ + +/*! \fn bool QCPBarsGroup::contains(QCPBars *bars) + + Returns whether the specified \a bars plottable is part of this group. + +*/ + +/* end of documentation of inline functions */ + +/*! + Constructs a new bars group for the specified QCustomPlot instance. +*/ +QCPBarsGroup::QCPBarsGroup(QCustomPlot *parentPlot) : + QObject(parentPlot), + mParentPlot(parentPlot), + mSpacingType(stAbsolute), + mSpacing(4) +{ +} + +QCPBarsGroup::~QCPBarsGroup() +{ + clear(); +} + +/*! + Sets how the spacing between adjacent bars is interpreted. See \ref SpacingType. + + The actual spacing can then be specified with \ref setSpacing. + + \see setSpacing +*/ +void QCPBarsGroup::setSpacingType(SpacingType spacingType) +{ + mSpacingType = spacingType; +} + +/*! + Sets the spacing between adjacent bars. What the number passed as \a spacing actually means, is + defined by the current \ref SpacingType, which can be set with \ref setSpacingType. + + \see setSpacingType +*/ +void QCPBarsGroup::setSpacing(double spacing) +{ + mSpacing = spacing; +} + +/*! + Returns the QCPBars instance with the specified \a index in this group. If no such QCPBars + exists, returns 0. + + \see bars(), size +*/ +QCPBars *QCPBarsGroup::bars(int index) const +{ + if (index >= 0 && index < mBars.size()) + { + return mBars.at(index); + } else + { + qDebug() << Q_FUNC_INFO << "index out of bounds:" << index; + return 0; + } +} + +/*! + Removes all QCPBars plottables from this group. + + \see isEmpty +*/ +void QCPBarsGroup::clear() +{ + foreach (QCPBars *bars, mBars) // since foreach takes a copy, removing bars in the loop is okay + bars->setBarsGroup(0); // removes itself via removeBars +} + +/*! + Adds the specified \a bars plottable to this group. Alternatively, you can also use \ref + QCPBars::setBarsGroup on the \a bars instance. + + \see insert, remove +*/ +void QCPBarsGroup::append(QCPBars *bars) +{ + if (!bars) + { + qDebug() << Q_FUNC_INFO << "bars is 0"; + return; + } + + if (!mBars.contains(bars)) + bars->setBarsGroup(this); + else + qDebug() << Q_FUNC_INFO << "bars plottable is already in this bars group:" << reinterpret_cast(bars); +} + +/*! + Inserts the specified \a bars plottable into this group at the specified index position \a i. + This gives you full control over the ordering of the bars. + + \a bars may already be part of this group. In that case, \a bars is just moved to the new index + position. + + \see append, remove +*/ +void QCPBarsGroup::insert(int i, QCPBars *bars) +{ + if (!bars) + { + qDebug() << Q_FUNC_INFO << "bars is 0"; + return; + } + + // first append to bars list normally: + if (!mBars.contains(bars)) + bars->setBarsGroup(this); + // then move to according position: + mBars.move(mBars.indexOf(bars), qBound(0, i, mBars.size()-1)); +} + +/*! + Removes the specified \a bars plottable from this group. + + \see contains, clear +*/ +void QCPBarsGroup::remove(QCPBars *bars) +{ + if (!bars) + { + qDebug() << Q_FUNC_INFO << "bars is 0"; + return; + } + + if (mBars.contains(bars)) + bars->setBarsGroup(0); + else + qDebug() << Q_FUNC_INFO << "bars plottable is not in this bars group:" << reinterpret_cast(bars); +} + +/*! \internal + + Adds the specified \a bars to the internal mBars list of bars. This method does not change the + barsGroup property on \a bars. + + \see unregisterBars +*/ +void QCPBarsGroup::registerBars(QCPBars *bars) +{ + if (!mBars.contains(bars)) + mBars.append(bars); +} + +/*! \internal + + Removes the specified \a bars from the internal mBars list of bars. This method does not change + the barsGroup property on \a bars. + + \see registerBars +*/ +void QCPBarsGroup::unregisterBars(QCPBars *bars) +{ + mBars.removeOne(bars); +} + +/*! \internal + + Returns the pixel offset in the key dimension the specified \a bars plottable should have at the + given key coordinate \a keyCoord. The offset is relative to the pixel position of the key + coordinate \a keyCoord. +*/ +double QCPBarsGroup::keyPixelOffset(const QCPBars *bars, double keyCoord) +{ + // find list of all base bars in case some mBars are stacked: + QList baseBars; + foreach (const QCPBars *b, mBars) + { + while (b->barBelow()) + b = b->barBelow(); + if (!baseBars.contains(b)) + baseBars.append(b); + } + // find base bar this "bars" is stacked on: + const QCPBars *thisBase = bars; + while (thisBase->barBelow()) + thisBase = thisBase->barBelow(); + + // determine key pixel offset of this base bars considering all other base bars in this barsgroup: + double result = 0; + int index = baseBars.indexOf(thisBase); + if (index >= 0) + { + int startIndex; + double lowerPixelWidth, upperPixelWidth; + if (baseBars.size() % 2 == 1 && index == (baseBars.size()-1)/2) // is center bar (int division on purpose) + { + return result; + } else if (index < (baseBars.size()-1)/2.0) // bar is to the left of center + { + if (baseBars.size() % 2 == 0) // even number of bars + { + startIndex = baseBars.size()/2-1; + result -= getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing + } else // uneven number of bars + { + startIndex = (baseBars.size()-1)/2-1; + baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); + result -= qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar + result -= getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing + } + for (int i=startIndex; i>index; --i) // add widths and spacings of bars in between center and our bars + { + baseBars.at(i)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); + result -= qAbs(upperPixelWidth-lowerPixelWidth); + result -= getPixelSpacing(baseBars.at(i), keyCoord); + } + // finally half of our bars width: + baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); + result -= qAbs(upperPixelWidth-lowerPixelWidth)*0.5; + } else // bar is to the right of center + { + if (baseBars.size() % 2 == 0) // even number of bars + { + startIndex = baseBars.size()/2; + result += getPixelSpacing(baseBars.at(startIndex), keyCoord)*0.5; // half of middle spacing + } else // uneven number of bars + { + startIndex = (baseBars.size()-1)/2+1; + baseBars.at((baseBars.size()-1)/2)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); + result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; // half of center bar + result += getPixelSpacing(baseBars.at((baseBars.size()-1)/2), keyCoord); // center bar spacing + } + for (int i=startIndex; igetPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); + result += qAbs(upperPixelWidth-lowerPixelWidth); + result += getPixelSpacing(baseBars.at(i), keyCoord); + } + // finally half of our bars width: + baseBars.at(index)->getPixelWidth(keyCoord, lowerPixelWidth, upperPixelWidth); + result += qAbs(upperPixelWidth-lowerPixelWidth)*0.5; + } + } + return result; +} + +/*! \internal + + Returns the spacing in pixels which is between this \a bars and the following one, both at the + key coordinate \a keyCoord. + + \note Typically the returned value doesn't depend on \a bars or \a keyCoord. \a bars is only + needed to get acces to the key axis transformation and axis rect for the modes \ref + stAxisRectRatio and \ref stPlotCoords. The \a keyCoord is only relevant for spacings given in + \ref stPlotCoords on a logarithmic axis. +*/ +double QCPBarsGroup::getPixelSpacing(const QCPBars *bars, double keyCoord) +{ + switch (mSpacingType) + { + case stAbsolute: + { + return mSpacing; + } + case stAxisRectRatio: + { + if (bars->keyAxis()->orientation() == Qt::Horizontal) + return bars->keyAxis()->axisRect()->width()*mSpacing; + else + return bars->keyAxis()->axisRect()->height()*mSpacing; + } + case stPlotCoords: + { + double keyPixel = bars->keyAxis()->coordToPixel(keyCoord); + return bars->keyAxis()->coordToPixel(keyCoord+mSpacing)-keyPixel; + } + } + return 0; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPBarData +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPBarData + \brief Holds the data of one single data point (one bar) for QCPBars. + + The container for storing multiple data points is \ref QCPBarDataMap. + + The stored data is: + \li \a key: coordinate on the key axis of this bar + \li \a value: height coordinate on the value axis of this bar + + \see QCPBarDataaMap +*/ + +/*! + Constructs a bar data point with key and value set to zero. +*/ +QCPBarData::QCPBarData() : + key(0), + value(0) +{ +} + +/*! + Constructs a bar data point with the specified \a key and \a value. +*/ +QCPBarData::QCPBarData(double key, double value) : + key(key), + value(value) +{ +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPBars +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPBars + \brief A plottable representing a bar chart in a plot. + + \image html QCPBars.png + + To plot data, assign it with the \ref setData or \ref addData functions. + + \section appearance Changing the appearance + + The appearance of the bars is determined by the pen and the brush (\ref setPen, \ref setBrush). + The width of the individual bars can be controlled with \ref setWidthType and \ref setWidth. + + Bar charts are stackable. This means, two QCPBars plottables can be placed on top of each other + (see \ref QCPBars::moveAbove). So when two bars are at the same key position, they will appear + stacked. + + If you would like to group multiple QCPBars plottables together so they appear side by side as + shown below, use QCPBarsGroup. + + \image html QCPBarsGroup.png + + \section usage Usage + + Like all data representing objects in QCustomPlot, the QCPBars is a plottable + (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies + (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) + + Usually, you first create an instance: + \code + QCPBars *newBars = new QCPBars(customPlot->xAxis, customPlot->yAxis);\endcode + add it to the customPlot with QCustomPlot::addPlottable: + \code + customPlot->addPlottable(newBars);\endcode + and then modify the properties of the newly created plottable, e.g.: + \code + newBars->setName("Country population"); + newBars->setData(xData, yData);\endcode +*/ + +/* start of documentation of inline functions */ + +/*! \fn QCPBars *QCPBars::barBelow() const + Returns the bars plottable that is directly below this bars plottable. + If there is no such plottable, returns 0. + + \see barAbove, moveBelow, moveAbove +*/ + +/*! \fn QCPBars *QCPBars::barAbove() const + Returns the bars plottable that is directly above this bars plottable. + If there is no such plottable, returns 0. + + \see barBelow, moveBelow, moveAbove +*/ + +/* end of documentation of inline functions */ + +/*! + Constructs a bar chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value + axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have + the same orientation. If either of these restrictions is violated, a corresponding message is + printed to the debug output (qDebug), the construction is not aborted, though. + + The constructed QCPBars can be added to the plot with QCustomPlot::addPlottable, QCustomPlot + then takes ownership of the bar chart. +*/ +QCPBars::QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis) : + QCPAbstractPlottable(keyAxis, valueAxis), + mData(new QCPBarDataMap), + mWidth(0.75), + mWidthType(wtPlotCoords), + mBarsGroup(0), + mBaseValue(0) +{ + // modify inherited properties from abstract plottable: + mPen.setColor(Qt::blue); + mPen.setStyle(Qt::SolidLine); + mBrush.setColor(QColor(40, 50, 255, 30)); + mBrush.setStyle(Qt::SolidPattern); + mSelectedPen = mPen; + mSelectedPen.setWidthF(2.5); + mSelectedPen.setColor(QColor(80, 80, 255)); // lighter than Qt::blue of mPen + mSelectedBrush = mBrush; +} + +QCPBars::~QCPBars() +{ + setBarsGroup(0); + if (mBarBelow || mBarAbove) + connectBars(mBarBelow.data(), mBarAbove.data()); // take this bar out of any stacking + delete mData; +} + +/*! + Sets the width of the bars. + + How the number passed as \a width is interpreted (e.g. screen pixels, plot coordinates,...), + depends on the currently set width type, see \ref setWidthType and \ref WidthType. +*/ +void QCPBars::setWidth(double width) +{ + mWidth = width; +} + +/*! + Sets how the width of the bars is defined. See the documentation of \ref WidthType for an + explanation of the possible values for \a widthType. + + The default value is \ref wtPlotCoords. + + \see setWidth +*/ +void QCPBars::setWidthType(QCPBars::WidthType widthType) +{ + mWidthType = widthType; +} + +/*! + Sets to which QCPBarsGroup this QCPBars instance belongs to. Alternatively, you can also use \ref + QCPBarsGroup::append. + + To remove this QCPBars from any group, set \a barsGroup to 0. +*/ +void QCPBars::setBarsGroup(QCPBarsGroup *barsGroup) +{ + // deregister at old group: + if (mBarsGroup) + mBarsGroup->unregisterBars(this); + mBarsGroup = barsGroup; + // register at new group: + if (mBarsGroup) + mBarsGroup->registerBars(this); +} + +/*! + Sets the base value of this bars plottable. + + The base value defines where on the value coordinate the bars start. How far the bars extend from + the base value is given by their individual value data. For example, if the base value is set to + 1, a bar with data value 2 will have its lowest point at value coordinate 1 and highest point at + 3. + + For stacked bars, only the base value of the bottom-most QCPBars has meaning. + + The default base value is 0. +*/ +void QCPBars::setBaseValue(double baseValue) +{ + mBaseValue = baseValue; +} + +/*! + Replaces the current data with the provided \a data. + + If \a copy is set to true, data points in \a data will only be copied. if false, the plottable + takes ownership of the passed data and replaces the internal data pointer with it. This is + significantly faster than copying for large datasets. +*/ +void QCPBars::setData(QCPBarDataMap *data, bool copy) +{ + if (copy) + { + *mData = *data; + } else + { + delete mData; + mData = data; + } +} + +/*! \overload + + Replaces the current data with the provided points in \a key and \a value tuples. The + provided vectors should have equal length. Else, the number of added points will be the size of + the smallest vector. +*/ +void QCPBars::setData(const QVector &key, const QVector &value) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, value.size()); + QCPBarData newData; + for (int i=0; iinsertMulti(newData.key, newData); + } +} + +/*! + Moves this bars plottable below \a bars. In other words, the bars of this plottable will appear + below the bars of \a bars. The move target \a bars must use the same key and value axis as this + plottable. + + Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already + has a bars object below itself, this bars object is inserted between the two. If this bars object + is already between two other bars, the two other bars will be stacked on top of each other after + the operation. + + To remove this bars plottable from any stacking, set \a bars to 0. + + \see moveBelow, barAbove, barBelow +*/ +void QCPBars::moveBelow(QCPBars *bars) +{ + if (bars == this) return; + if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) + { + qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; + return; + } + // remove from stacking: + connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 + // if new bar given, insert this bar below it: + if (bars) + { + if (bars->mBarBelow) + connectBars(bars->mBarBelow.data(), this); + connectBars(this, bars); + } +} + +/*! + Moves this bars plottable above \a bars. In other words, the bars of this plottable will appear + above the bars of \a bars. The move target \a bars must use the same key and value axis as this + plottable. + + Inserting into and removing from existing bar stacking is handled gracefully. If \a bars already + has a bars object below itself, this bars object is inserted between the two. If this bars object + is already between two other bars, the two other bars will be stacked on top of each other after + the operation. + + To remove this bars plottable from any stacking, set \a bars to 0. + + \see moveBelow, barBelow, barAbove +*/ +void QCPBars::moveAbove(QCPBars *bars) +{ + if (bars == this) return; + if (bars && (bars->keyAxis() != mKeyAxis.data() || bars->valueAxis() != mValueAxis.data())) + { + qDebug() << Q_FUNC_INFO << "passed QCPBars* doesn't have same key and value axis as this QCPBars"; + return; + } + // remove from stacking: + connectBars(mBarBelow.data(), mBarAbove.data()); // Note: also works if one (or both) of them is 0 + // if new bar given, insert this bar above it: + if (bars) + { + if (bars->mBarAbove) + connectBars(this, bars->mBarAbove.data()); + connectBars(bars, this); + } +} + +/*! + Adds the provided data points in \a dataMap to the current data. + \see removeData +*/ +void QCPBars::addData(const QCPBarDataMap &dataMap) +{ + mData->unite(dataMap); +} + +/*! \overload + Adds the provided single data point in \a data to the current data. + \see removeData +*/ +void QCPBars::addData(const QCPBarData &data) +{ + mData->insertMulti(data.key, data); +} + +/*! \overload + Adds the provided single data point as \a key and \a value tuple to the current data + \see removeData +*/ +void QCPBars::addData(double key, double value) +{ + QCPBarData newData; + newData.key = key; + newData.value = value; + mData->insertMulti(newData.key, newData); +} + +/*! \overload + Adds the provided data points as \a key and \a value tuples to the current data. + \see removeData +*/ +void QCPBars::addData(const QVector &keys, const QVector &values) +{ + int n = keys.size(); + n = qMin(n, values.size()); + QCPBarData newData; + for (int i=0; iinsertMulti(newData.key, newData); + } +} + +/*! + Removes all data points with key smaller than \a key. + \see addData, clearData +*/ +void QCPBars::removeDataBefore(double key) +{ + QCPBarDataMap::iterator it = mData->begin(); + while (it != mData->end() && it.key() < key) + it = mData->erase(it); +} + +/*! + Removes all data points with key greater than \a key. + \see addData, clearData +*/ +void QCPBars::removeDataAfter(double key) +{ + if (mData->isEmpty()) return; + QCPBarDataMap::iterator it = mData->upperBound(key); + while (it != mData->end()) + it = mData->erase(it); +} + +/*! + Removes all data points with key between \a fromKey and \a toKey. if \a fromKey is + greater or equal to \a toKey, the function does nothing. To remove a single data point with known + key, use \ref removeData(double key). + + \see addData, clearData +*/ +void QCPBars::removeData(double fromKey, double toKey) +{ + if (fromKey >= toKey || mData->isEmpty()) return; + QCPBarDataMap::iterator it = mData->upperBound(fromKey); + QCPBarDataMap::iterator itEnd = mData->upperBound(toKey); + while (it != itEnd) + it = mData->erase(it); +} + +/*! \overload + + Removes a single data point at \a key. If the position is not known with absolute precision, + consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval + around the suspected position, depeding on the precision with which the key is known. + + \see addData, clearData +*/ +void QCPBars::removeData(double key) +{ + mData->remove(key); +} + +/*! + Removes all data points. + \see removeData, removeDataAfter, removeDataBefore +*/ +void QCPBars::clearData() +{ + mData->clear(); +} + +/* inherits documentation from base class */ +double QCPBars::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) + { + QCPBarDataMap::ConstIterator it; + for (it = mData->constBegin(); it != mData->constEnd(); ++it) + { + if (getBarPolygon(it.value().key, it.value().value).boundingRect().contains(pos)) + return mParentPlot->selectionTolerance()*0.99; + } + } + return -1; +} + +/* inherits documentation from base class */ +void QCPBars::draw(QCPPainter *painter) +{ + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + if (mData->isEmpty()) return; + + QCPBarDataMap::const_iterator it, lower, upperEnd; + getVisibleDataBounds(lower, upperEnd); + for (it = lower; it != upperEnd; ++it) + { + // check data validity if flag set: +#ifdef QCUSTOMPLOT_CHECK_DATA + if (QCP::isInvalidData(it.value().key, it.value().value)) + qDebug() << Q_FUNC_INFO << "Data point at" << it.key() << "of drawn range invalid." << "Plottable name:" << name(); +#endif + QPolygonF barPolygon = getBarPolygon(it.key(), it.value().value); + // draw bar fill: + if (mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) + { + applyFillAntialiasingHint(painter); + painter->setPen(Qt::NoPen); + painter->setBrush(mainBrush()); + painter->drawPolygon(barPolygon); + } + // draw bar line: + if (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0) + { + applyDefaultAntialiasingHint(painter); + painter->setPen(mainPen()); + painter->setBrush(Qt::NoBrush); + painter->drawPolyline(barPolygon); + } + } +} + +/* inherits documentation from base class */ +void QCPBars::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const +{ + // draw filled rect: + applyDefaultAntialiasingHint(painter); + painter->setBrush(mBrush); + painter->setPen(mPen); + QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); + r.moveCenter(rect.center()); + painter->drawRect(r); +} + +/*! \internal + + called by \ref draw to determine which data (key) range is visible at the current key axis range + setting, so only that needs to be processed. It also takes into account the bar width. + + \a lower returns an iterator to the lowest data point that needs to be taken into account when + plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a + lower may still be just outside the visible range. + + \a upperEnd returns an iterator one higher than the highest visible data point. Same as before, \a + upperEnd may also lie just outside of the visible range. + + if the bars plottable contains no data, both \a lower and \a upperEnd point to constEnd. +*/ +void QCPBars::getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarDataMap::const_iterator &upperEnd) const +{ + if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } + if (mData->isEmpty()) + { + lower = mData->constEnd(); + upperEnd = mData->constEnd(); + return; + } + + // get visible data range as QMap iterators + lower = mData->lowerBound(mKeyAxis.data()->range().lower); + upperEnd = mData->upperBound(mKeyAxis.data()->range().upper); + double lowerPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().lower); + double upperPixelBound = mKeyAxis.data()->coordToPixel(mKeyAxis.data()->range().upper); + bool isVisible = false; + // walk left from lbound to find lower bar that actually is completely outside visible pixel range: + QCPBarDataMap::const_iterator it = lower; + while (it != mData->constBegin()) + { + --it; + QRectF barBounds = getBarPolygon(it.value().key, it.value().value).boundingRect(); + if (mKeyAxis.data()->orientation() == Qt::Horizontal) + isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.right() >= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.left() <= lowerPixelBound)); + else // keyaxis is vertical + isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.top() <= lowerPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= lowerPixelBound)); + if (isVisible) + lower = it; + else + break; + } + // walk right from ubound to find upper bar that actually is completely outside visible pixel range: + it = upperEnd; + while (it != mData->constEnd()) + { + QRectF barBounds = getBarPolygon(upperEnd.value().key, upperEnd.value().value).boundingRect(); + if (mKeyAxis.data()->orientation() == Qt::Horizontal) + isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.left() <= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.right() >= upperPixelBound)); + else // keyaxis is vertical + isVisible = ((!mKeyAxis.data()->rangeReversed() && barBounds.bottom() >= upperPixelBound) || (mKeyAxis.data()->rangeReversed() && barBounds.top() <= upperPixelBound)); + if (isVisible) + upperEnd = it+1; + else + break; + ++it; + } +} + +/*! \internal + + Returns the polygon of a single bar with \a key and \a value. The Polygon is open at the bottom + and shifted according to the bar stacking (see \ref moveAbove) and base value (see \ref + setBaseValue). +*/ +QPolygonF QCPBars::getBarPolygon(double key, double value) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return QPolygonF(); } + + QPolygonF result; + double lowerPixelWidth, upperPixelWidth; + getPixelWidth(key, lowerPixelWidth, upperPixelWidth); + double base = getStackedBaseValue(key, value >= 0); + double basePixel = valueAxis->coordToPixel(base); + double valuePixel = valueAxis->coordToPixel(base+value); + double keyPixel = keyAxis->coordToPixel(key); + if (mBarsGroup) + keyPixel += mBarsGroup->keyPixelOffset(this, key); + if (keyAxis->orientation() == Qt::Horizontal) + { + result << QPointF(keyPixel+lowerPixelWidth, basePixel); + result << QPointF(keyPixel+lowerPixelWidth, valuePixel); + result << QPointF(keyPixel+upperPixelWidth, valuePixel); + result << QPointF(keyPixel+upperPixelWidth, basePixel); + } else + { + result << QPointF(basePixel, keyPixel+lowerPixelWidth); + result << QPointF(valuePixel, keyPixel+lowerPixelWidth); + result << QPointF(valuePixel, keyPixel+upperPixelWidth); + result << QPointF(basePixel, keyPixel+upperPixelWidth); + } + return result; +} + +/*! \internal + + This function is used to determine the width of the bar at coordinate \a key, according to the + specified width (\ref setWidth) and width type (\ref setWidthType). + + The output parameters \a lower and \a upper return the number of pixels the bar extends to lower + and higher keys, relative to the \a key coordinate (so with a non-reversed horizontal axis, \a + lower is negative and \a upper positive). +*/ +void QCPBars::getPixelWidth(double key, double &lower, double &upper) const +{ + switch (mWidthType) + { + case wtAbsolute: + { + upper = mWidth*0.5; + lower = -upper; + if (mKeyAxis && (mKeyAxis.data()->rangeReversed() ^ (mKeyAxis.data()->orientation() == Qt::Vertical))) + qSwap(lower, upper); + break; + } + case wtAxisRectRatio: + { + if (mKeyAxis && mKeyAxis.data()->axisRect()) + { + if (mKeyAxis.data()->orientation() == Qt::Horizontal) + upper = mKeyAxis.data()->axisRect()->width()*mWidth*0.5; + else + upper = mKeyAxis.data()->axisRect()->height()*mWidth*0.5; + lower = -upper; + if (mKeyAxis && (mKeyAxis.data()->rangeReversed() ^ (mKeyAxis.data()->orientation() == Qt::Vertical))) + qSwap(lower, upper); + } else + qDebug() << Q_FUNC_INFO << "No key axis or axis rect defined"; + break; + } + case wtPlotCoords: + { + if (mKeyAxis) + { + double keyPixel = mKeyAxis.data()->coordToPixel(key); + upper = mKeyAxis.data()->coordToPixel(key+mWidth*0.5)-keyPixel; + lower = mKeyAxis.data()->coordToPixel(key-mWidth*0.5)-keyPixel; + // no need to qSwap(lower, higher) when range reversed, because higher/lower are gained by + // coordinate transform which includes range direction + } else + qDebug() << Q_FUNC_INFO << "No key axis defined"; + break; + } + } +} + +/*! \internal + + This function is called to find at which value to start drawing the base of a bar at \a key, when + it is stacked on top of another QCPBars (e.g. with \ref moveAbove). + + positive and negative bars are separated per stack (positive are stacked above baseValue upwards, + negative are stacked below baseValue downwards). This can be indicated with \a positive. So if the + bar for which we need the base value is negative, set \a positive to false. +*/ +double QCPBars::getStackedBaseValue(double key, bool positive) const +{ + if (mBarBelow) + { + double max = 0; // don't use mBaseValue here because only base value of bottom-most bar has meaning in a bar stack + // find bars of mBarBelow that are approximately at key and find largest one: + double epsilon = qAbs(key)*1e-6; // should be safe even when changed to use float at some point + if (key == 0) + epsilon = 1e-6; + QCPBarDataMap::const_iterator it = mBarBelow.data()->mData->lowerBound(key-epsilon); + QCPBarDataMap::const_iterator itEnd = mBarBelow.data()->mData->upperBound(key+epsilon); + while (it != itEnd) + { + if ((positive && it.value().value > max) || + (!positive && it.value().value < max)) + max = it.value().value; + ++it; + } + // recurse down the bar-stack to find the total height: + return max + mBarBelow.data()->getStackedBaseValue(key, positive); + } else + return mBaseValue; +} + +/*! \internal + + Connects \a below and \a above to each other via their mBarAbove/mBarBelow properties. The bar(s) + currently above lower and below upper will become disconnected to lower/upper. + + If lower is zero, upper will be disconnected at the bottom. + If upper is zero, lower will be disconnected at the top. +*/ +void QCPBars::connectBars(QCPBars *lower, QCPBars *upper) +{ + if (!lower && !upper) return; + + if (!lower) // disconnect upper at bottom + { + // disconnect old bar below upper: + if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) + upper->mBarBelow.data()->mBarAbove = 0; + upper->mBarBelow = 0; + } else if (!upper) // disconnect lower at top + { + // disconnect old bar above lower: + if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) + lower->mBarAbove.data()->mBarBelow = 0; + lower->mBarAbove = 0; + } else // connect lower and upper + { + // disconnect old bar above lower: + if (lower->mBarAbove && lower->mBarAbove.data()->mBarBelow.data() == lower) + lower->mBarAbove.data()->mBarBelow = 0; + // disconnect old bar below upper: + if (upper->mBarBelow && upper->mBarBelow.data()->mBarAbove.data() == upper) + upper->mBarBelow.data()->mBarAbove = 0; + lower->mBarAbove = upper; + upper->mBarBelow = lower; + } +} + +/* inherits documentation from base class */ +QCPRange QCPBars::getKeyRange(bool &foundRange, SignDomain inSignDomain) const +{ + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + + double current; + QCPBarDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().key; + if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) + { + if (current < range.lower || !haveLower) + { + range.lower = current; + haveLower = true; + } + if (current > range.upper || !haveUpper) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + // determine exact range of bars by including bar width and barsgroup offset: + if (haveLower && mKeyAxis) + { + double lowerPixelWidth, upperPixelWidth, keyPixel; + getPixelWidth(range.lower, lowerPixelWidth, upperPixelWidth); + keyPixel = mKeyAxis.data()->coordToPixel(range.lower) + lowerPixelWidth; + if (mBarsGroup) + keyPixel += mBarsGroup->keyPixelOffset(this, range.lower); + range.lower = mKeyAxis.data()->pixelToCoord(keyPixel); + } + if (haveUpper && mKeyAxis) + { + double lowerPixelWidth, upperPixelWidth, keyPixel; + getPixelWidth(range.upper, lowerPixelWidth, upperPixelWidth); + keyPixel = mKeyAxis.data()->coordToPixel(range.upper) + upperPixelWidth; + if (mBarsGroup) + keyPixel += mBarsGroup->keyPixelOffset(this, range.upper); + range.upper = mKeyAxis.data()->pixelToCoord(keyPixel); + } + foundRange = haveLower && haveUpper; + return range; +} + +/* inherits documentation from base class */ +QCPRange QCPBars::getValueRange(bool &foundRange, SignDomain inSignDomain) const +{ + QCPRange range; + range.lower = mBaseValue; + range.upper = mBaseValue; + bool haveLower = true; // set to true, because baseValue should always be visible in bar charts + bool haveUpper = true; // set to true, because baseValue should always be visible in bar charts + double current; + + QCPBarDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().value + getStackedBaseValue(it.value().key, it.value().value >= 0); + if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) + { + if (current < range.lower || !haveLower) + { + range.lower = current; + haveLower = true; + } + if (current > range.upper || !haveUpper) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + + foundRange = true; // return true because bar charts always have the 0-line visible + return range; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPStatisticalBox +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPStatisticalBox + \brief A plottable representing a single statistical box in a plot. + + \image html QCPStatisticalBox.png + + To plot data, assign it with the individual parameter functions or use \ref setData to set all + parameters at once. The individual functions are: + \li \ref setMinimum + \li \ref setLowerQuartile + \li \ref setMedian + \li \ref setUpperQuartile + \li \ref setMaximum + + Additionally you can define a list of outliers, drawn as scatter datapoints: + \li \ref setOutliers + + \section appearance Changing the appearance + + The appearance of the box itself is controlled via \ref setPen and \ref setBrush. You may change + the width of the box with \ref setWidth in plot coordinates (not pixels). + + Analog functions exist for the minimum/maximum-whiskers: \ref setWhiskerPen, \ref + setWhiskerBarPen, \ref setWhiskerWidth. The whisker width is the width of the bar at the top + (maximum) and bottom (minimum). + + The median indicator line has its own pen, \ref setMedianPen. + + If the whisker backbone pen is changed, make sure to set the capStyle to Qt::FlatCap. Else, the + backbone line might exceed the whisker bars by a few pixels due to the pen cap being not + perfectly flat. + + The Outlier data points are drawn as normal scatter points. Their look can be controlled with + \ref setOutlierStyle + + \section usage Usage + + Like all data representing objects in QCustomPlot, the QCPStatisticalBox is a plottable + (QCPAbstractPlottable). So the plottable-interface of QCustomPlot applies + (QCustomPlot::plottable, QCustomPlot::addPlottable, QCustomPlot::removePlottable, etc.) + + Usually, you first create an instance: + \code + QCPStatisticalBox *newBox = new QCPStatisticalBox(customPlot->xAxis, customPlot->yAxis);\endcode + add it to the customPlot with QCustomPlot::addPlottable: + \code + customPlot->addPlottable(newBox);\endcode + and then modify the properties of the newly created plottable, e.g.: + \code + newBox->setName("Measurement Series 1"); + newBox->setData(1, 3, 4, 5, 7); + newBox->setOutliers(QVector() << 0.5 << 0.64 << 7.2 << 7.42);\endcode +*/ + +/*! + Constructs a statistical box which uses \a keyAxis as its key axis ("x") and \a valueAxis as its + value axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and + not have the same orientation. If either of these restrictions is violated, a corresponding + message is printed to the debug output (qDebug), the construction is not aborted, though. + + The constructed statistical box can be added to the plot with QCustomPlot::addPlottable, + QCustomPlot then takes ownership of the statistical box. +*/ +QCPStatisticalBox::QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis) : + QCPAbstractPlottable(keyAxis, valueAxis), + mKey(0), + mMinimum(0), + mLowerQuartile(0), + mMedian(0), + mUpperQuartile(0), + mMaximum(0) +{ + setOutlierStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, Qt::blue, 6)); + setWhiskerWidth(0.2); + setWidth(0.5); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2.5)); + setMedianPen(QPen(Qt::black, 3, Qt::SolidLine, Qt::FlatCap)); + setWhiskerPen(QPen(Qt::black, 0, Qt::DashLine, Qt::FlatCap)); + setWhiskerBarPen(QPen(Qt::black)); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); +} + +/*! + Sets the key coordinate of the statistical box. +*/ +void QCPStatisticalBox::setKey(double key) +{ + mKey = key; +} + +/*! + Sets the parameter "minimum" of the statistical box plot. This is the position of the lower + whisker, typically the minimum measurement of the sample that's not considered an outlier. + + \see setMaximum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth +*/ +void QCPStatisticalBox::setMinimum(double value) +{ + mMinimum = value; +} + +/*! + Sets the parameter "lower Quartile" of the statistical box plot. This is the lower end of the + box. The lower and the upper quartiles are the two statistical quartiles around the median of the + sample, they contain 50% of the sample data. + + \see setUpperQuartile, setPen, setBrush, setWidth +*/ +void QCPStatisticalBox::setLowerQuartile(double value) +{ + mLowerQuartile = value; +} + +/*! + Sets the parameter "median" of the statistical box plot. This is the value of the median mark + inside the quartile box. The median separates the sample data in half (50% of the sample data is + below/above the median). + + \see setMedianPen +*/ +void QCPStatisticalBox::setMedian(double value) +{ + mMedian = value; +} + +/*! + Sets the parameter "upper Quartile" of the statistical box plot. This is the upper end of the + box. The lower and the upper quartiles are the two statistical quartiles around the median of the + sample, they contain 50% of the sample data. + + \see setLowerQuartile, setPen, setBrush, setWidth +*/ +void QCPStatisticalBox::setUpperQuartile(double value) +{ + mUpperQuartile = value; +} + +/*! + Sets the parameter "maximum" of the statistical box plot. This is the position of the upper + whisker, typically the maximum measurement of the sample that's not considered an outlier. + + \see setMinimum, setWhiskerPen, setWhiskerBarPen, setWhiskerWidth +*/ +void QCPStatisticalBox::setMaximum(double value) +{ + mMaximum = value; +} + +/*! + Sets a vector of outlier values that will be drawn as scatters. Any data points in the sample + that are not within the whiskers (\ref setMinimum, \ref setMaximum) should be considered outliers + and displayed as such. + + \see setOutlierStyle +*/ +void QCPStatisticalBox::setOutliers(const QVector &values) +{ + mOutliers = values; +} + +/*! + Sets all parameters of the statistical box plot at once. + + \see setKey, setMinimum, setLowerQuartile, setMedian, setUpperQuartile, setMaximum +*/ +void QCPStatisticalBox::setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum) +{ + setKey(key); + setMinimum(minimum); + setLowerQuartile(lowerQuartile); + setMedian(median); + setUpperQuartile(upperQuartile); + setMaximum(maximum); +} + +/*! + Sets the width of the box in key coordinates. + + \see setWhiskerWidth +*/ +void QCPStatisticalBox::setWidth(double width) +{ + mWidth = width; +} + +/*! + Sets the width of the whiskers (\ref setMinimum, \ref setMaximum) in key coordinates. + + \see setWidth +*/ +void QCPStatisticalBox::setWhiskerWidth(double width) +{ + mWhiskerWidth = width; +} + +/*! + Sets the pen used for drawing the whisker backbone (That's the line parallel to the value axis). + + Make sure to set the \a pen capStyle to Qt::FlatCap to prevent the whisker backbone from reaching + a few pixels past the whisker bars, when using a non-zero pen width. + + \see setWhiskerBarPen +*/ +void QCPStatisticalBox::setWhiskerPen(const QPen &pen) +{ + mWhiskerPen = pen; +} + +/*! + Sets the pen used for drawing the whisker bars (Those are the lines parallel to the key axis at + each end of the whisker backbone). + + \see setWhiskerPen +*/ +void QCPStatisticalBox::setWhiskerBarPen(const QPen &pen) +{ + mWhiskerBarPen = pen; +} + +/*! + Sets the pen used for drawing the median indicator line inside the statistical box. +*/ +void QCPStatisticalBox::setMedianPen(const QPen &pen) +{ + mMedianPen = pen; +} + +/*! + Sets the appearance of the outlier data points. + + \see setOutliers +*/ +void QCPStatisticalBox::setOutlierStyle(const QCPScatterStyle &style) +{ + mOutlierStyle = style; +} + +/* inherits documentation from base class */ +void QCPStatisticalBox::clearData() +{ + setOutliers(QVector()); + setKey(0); + setMinimum(0); + setLowerQuartile(0); + setMedian(0); + setUpperQuartile(0); + setMaximum(0); +} + +/* inherits documentation from base class */ +double QCPStatisticalBox::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) + { + double posKey, posValue; + pixelsToCoords(pos, posKey, posValue); + // quartile box: + QCPRange keyRange(mKey-mWidth*0.5, mKey+mWidth*0.5); + QCPRange valueRange(mLowerQuartile, mUpperQuartile); + if (keyRange.contains(posKey) && valueRange.contains(posValue)) + return mParentPlot->selectionTolerance()*0.99; + + // min/max whiskers: + if (QCPRange(mMinimum, mMaximum).contains(posValue)) + return qAbs(mKeyAxis.data()->coordToPixel(mKey)-mKeyAxis.data()->coordToPixel(posKey)); + } + return -1; +} + +/* inherits documentation from base class */ +void QCPStatisticalBox::draw(QCPPainter *painter) +{ + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + + // check data validity if flag set: +#ifdef QCUSTOMPLOT_CHECK_DATA + if (QCP::isInvalidData(mKey, mMedian) || + QCP::isInvalidData(mLowerQuartile, mUpperQuartile) || + QCP::isInvalidData(mMinimum, mMaximum)) + qDebug() << Q_FUNC_INFO << "Data point at" << mKey << "of drawn range has invalid data." << "Plottable name:" << name(); + for (int i=0; isave(); + painter->setClipRect(quartileBox, Qt::IntersectClip); + drawMedian(painter); + painter->restore(); + + drawWhiskers(painter); + drawOutliers(painter); +} + +/* inherits documentation from base class */ +void QCPStatisticalBox::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const +{ + // draw filled rect: + applyDefaultAntialiasingHint(painter); + painter->setPen(mPen); + painter->setBrush(mBrush); + QRectF r = QRectF(0, 0, rect.width()*0.67, rect.height()*0.67); + r.moveCenter(rect.center()); + painter->drawRect(r); +} + +/*! \internal + + Draws the quartile box. \a box is an output parameter that returns the quartile box (in pixel + coordinates) which is used to set the clip rect of the painter before calling \ref drawMedian (so + the median doesn't draw outside the quartile box). +*/ +void QCPStatisticalBox::drawQuartileBox(QCPPainter *painter, QRectF *quartileBox) const +{ + QRectF box; + box.setTopLeft(coordsToPixels(mKey-mWidth*0.5, mUpperQuartile)); + box.setBottomRight(coordsToPixels(mKey+mWidth*0.5, mLowerQuartile)); + applyDefaultAntialiasingHint(painter); + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + painter->drawRect(box); + if (quartileBox) + *quartileBox = box; +} + +/*! \internal + + Draws the median line inside the quartile box. +*/ +void QCPStatisticalBox::drawMedian(QCPPainter *painter) const +{ + QLineF medianLine; + medianLine.setP1(coordsToPixels(mKey-mWidth*0.5, mMedian)); + medianLine.setP2(coordsToPixels(mKey+mWidth*0.5, mMedian)); + applyDefaultAntialiasingHint(painter); + painter->setPen(mMedianPen); + painter->drawLine(medianLine); +} + +/*! \internal + + Draws both whisker backbones and bars. +*/ +void QCPStatisticalBox::drawWhiskers(QCPPainter *painter) const +{ + QLineF backboneMin, backboneMax, barMin, barMax; + backboneMax.setPoints(coordsToPixels(mKey, mUpperQuartile), coordsToPixels(mKey, mMaximum)); + backboneMin.setPoints(coordsToPixels(mKey, mLowerQuartile), coordsToPixels(mKey, mMinimum)); + barMax.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMaximum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMaximum)); + barMin.setPoints(coordsToPixels(mKey-mWhiskerWidth*0.5, mMinimum), coordsToPixels(mKey+mWhiskerWidth*0.5, mMinimum)); + applyErrorBarsAntialiasingHint(painter); + painter->setPen(mWhiskerPen); + painter->drawLine(backboneMin); + painter->drawLine(backboneMax); + painter->setPen(mWhiskerBarPen); + painter->drawLine(barMin); + painter->drawLine(barMax); +} + +/*! \internal + + Draws the outlier scatter points. +*/ +void QCPStatisticalBox::drawOutliers(QCPPainter *painter) const +{ + applyScattersAntialiasingHint(painter); + mOutlierStyle.applyTo(painter, mPen); + for (int i=0; i 0) + return QCPRange(mKey-mWidth*0.5, mKey+mWidth*0.5); + else if (mKey > 0) + return QCPRange(mKey, mKey+mWidth*0.5); + else + { + foundRange = false; + return QCPRange(); + } + } + foundRange = false; + return QCPRange(); +} + +/* inherits documentation from base class */ +QCPRange QCPStatisticalBox::getValueRange(bool &foundRange, SignDomain inSignDomain) const +{ + QVector values; // values that must be considered (i.e. all outliers and the five box-parameters) + values.reserve(mOutliers.size() + 5); + values << mMaximum << mUpperQuartile << mMedian << mLowerQuartile << mMinimum; + values << mOutliers; + // go through values and find the ones in legal range: + bool haveUpper = false; + bool haveLower = false; + double upper = 0; + double lower = 0; + for (int i=0; i 0) || + (inSignDomain == sdBoth)) + { + if (values.at(i) > upper || !haveUpper) + { + upper = values.at(i); + haveUpper = true; + } + if (values.at(i) < lower || !haveLower) + { + lower = values.at(i); + haveLower = true; + } + } + } + // return the bounds if we found some sensible values: + if (haveLower && haveUpper) + { + foundRange = true; + return QCPRange(lower, upper); + } else // might happen if all values are in other sign domain + { + foundRange = false; + return QCPRange(); + } +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPColorMapData +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPColorMapData + \brief Holds the two-dimensional data of a QCPColorMap plottable. + + This class is a data storage for \ref QCPColorMap. It holds a two-dimensional array, which \ref + QCPColorMap then displays as a 2D image in the plot, where the array values are represented by a + color, depending on the value. + + The size of the array can be controlled via \ref setSize (or \ref setKeySize, \ref setValueSize). + Which plot coordinates these cells correspond to can be configured with \ref setRange (or \ref + setKeyRange, \ref setValueRange). + + The data cells can be accessed in two ways: They can be directly addressed by an integer index + with \ref setCell. This is the fastest method. Alternatively, they can be addressed by their plot + coordinate with \ref setData. plot coordinate to cell index transformations and vice versa are + provided by the functions \ref coordToCell and \ref cellToCoord. + + This class also buffers the minimum and maximum values that are in the data set, to provide + QCPColorMap::rescaleDataRange with the necessary information quickly. Setting a cell to a value + that is greater than the current maximum increases this maximum to the new value. However, + setting the cell that currently holds the maximum value to a smaller value doesn't decrease the + maximum again, because finding the true new maximum would require going through the entire data + array, which might be time consuming. The same holds for the data minimum. This functionality is + given by \ref recalculateDataBounds, such that you can decide when it is sensible to find the + true current minimum and maximum. The method QCPColorMap::rescaleDataRange offers a convenience + parameter \a recalculateDataBounds which may be set to true to automatically call \ref + recalculateDataBounds internally. +*/ + +/* start of documentation of inline functions */ + +/*! \fn bool QCPColorMapData::isEmpty() const + + Returns whether this instance carries no data. This is equivalent to having a size where at least + one of the dimensions is 0 (see \ref setSize). +*/ + +/* end of documentation of inline functions */ + +/*! + Constructs a new QCPColorMapData instance. The instance has \a keySize cells in the key direction + and \a valueSize cells in the value direction. These cells will be displayed by the \ref QCPColorMap + at the coordinates \a keyRange and \a valueRange. + + \see setSize, setKeySize, setValueSize, setRange, setKeyRange, setValueRange +*/ +QCPColorMapData::QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange) : + mKeySize(0), + mValueSize(0), + mKeyRange(keyRange), + mValueRange(valueRange), + mIsEmpty(true), + mData(0), + mDataModified(true) +{ + setSize(keySize, valueSize); + fill(0); +} + +QCPColorMapData::~QCPColorMapData() +{ + if (mData) + delete[] mData; +} + +/*! + Constructs a new QCPColorMapData instance copying the data and range of \a other. +*/ +QCPColorMapData::QCPColorMapData(const QCPColorMapData &other) : + mKeySize(0), + mValueSize(0), + mIsEmpty(true), + mData(0), + mDataModified(true) +{ + *this = other; +} + +/*! + Overwrites this color map data instance with the data stored in \a other. +*/ +QCPColorMapData &QCPColorMapData::operator=(const QCPColorMapData &other) +{ + if (&other != this) + { + const int keySize = other.keySize(); + const int valueSize = other.valueSize(); + setSize(keySize, valueSize); + setRange(other.keyRange(), other.valueRange()); + if (!mIsEmpty) + memcpy(mData, other.mData, sizeof(mData[0])*keySize*valueSize); + mDataBounds = other.mDataBounds; + mDataModified = true; + } + return *this; +} + +/* undocumented getter */ +double QCPColorMapData::data(double key, double value) +{ + int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; + int valueCell = (1.0-(value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower))*(mValueSize-1)+0.5; + if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) + return mData[valueCell*mKeySize + keyCell]; + else + return 0; +} + +/* undocumented getter */ +double QCPColorMapData::cell(int keyIndex, int valueIndex) +{ + if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) + return mData[valueIndex*mKeySize + keyIndex]; + else + return 0; +} + +/*! + Resizes the data array to have \a keySize cells in the key dimension and \a valueSize cells in + the value dimension. + + The current data is discarded and the map cells are set to 0, unless the map had already the + requested size. + + Setting at least one of \a keySize or \a valueSize to zero frees the internal data array and \ref + isEmpty returns true. + + \see setRange, setKeySize, setValueSize +*/ +void QCPColorMapData::setSize(int keySize, int valueSize) +{ + if (keySize != mKeySize || valueSize != mValueSize) + { + mKeySize = keySize; + mValueSize = valueSize; + if (mData) + delete[] mData; + mIsEmpty = mKeySize == 0 || mValueSize == 0; + if (!mIsEmpty) + { +#ifdef __EXCEPTIONS + try { // 2D arrays get memory intensive fast. So if the allocation fails, at least output debug message +#endif + mData = new double[mKeySize*mValueSize]; +#ifdef __EXCEPTIONS + } catch (...) { mData = 0; } +#endif + if (mData) + fill(0); + else + qDebug() << Q_FUNC_INFO << "out of memory for data dimensions "<< mKeySize << "*" << mValueSize; + } else + mData = 0; + mDataModified = true; + } +} + +/*! + Resizes the data array to have \a keySize cells in the key dimension. + + The current data is discarded and the map cells are set to 0, unless the map had already the + requested size. + + Setting \a keySize to zero frees the internal data array and \ref isEmpty returns true. + + \see setKeyRange, setSize, setValueSize +*/ +void QCPColorMapData::setKeySize(int keySize) +{ + setSize(keySize, mValueSize); +} + +/*! + Resizes the data array to have \a valueSize cells in the value dimension. + + The current data is discarded and the map cells are set to 0, unless the map had already the + requested size. + + Setting \a valueSize to zero frees the internal data array and \ref isEmpty returns true. + + \see setValueRange, setSize, setKeySize +*/ +void QCPColorMapData::setValueSize(int valueSize) +{ + setSize(mKeySize, valueSize); +} + +/*! + Sets the coordinate ranges the data shall be distributed over. This defines the rectangular area + covered by the color map in plot coordinates. + + The outer cells will be centered on the range boundaries given to this function. For example, if + the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will + be cells centered on the key coordinates 2, 2.5 and 3. + + \see setSize +*/ +void QCPColorMapData::setRange(const QCPRange &keyRange, const QCPRange &valueRange) +{ + setKeyRange(keyRange); + setValueRange(valueRange); +} + +/*! + Sets the coordinate range the data shall be distributed over in the key dimension. Together with + the value range, This defines the rectangular area covered by the color map in plot coordinates. + + The outer cells will be centered on the range boundaries given to this function. For example, if + the key size (\ref setKeySize) is 3 and \a keyRange is set to QCPRange(2, 3) there will + be cells centered on the key coordinates 2, 2.5 and 3. + + \see setRange, setValueRange, setSize +*/ +void QCPColorMapData::setKeyRange(const QCPRange &keyRange) +{ + mKeyRange = keyRange; +} + +/*! + Sets the coordinate range the data shall be distributed over in the value dimension. Together with + the key range, This defines the rectangular area covered by the color map in plot coordinates. + + The outer cells will be centered on the range boundaries given to this function. For example, if + the value size (\ref setValueSize) is 3 and \a valueRange is set to QCPRange(2, 3) there + will be cells centered on the value coordinates 2, 2.5 and 3. + + \see setRange, setKeyRange, setSize +*/ +void QCPColorMapData::setValueRange(const QCPRange &valueRange) +{ + mValueRange = valueRange; +} + +/*! + Sets the data of the cell, which lies at the plot coordinates given by \a key and \a value, to \a + z. + + \see setCell, setRange +*/ +void QCPColorMapData::setData(double key, double value, double z) +{ + int keyCell = (key-mKeyRange.lower)/(mKeyRange.upper-mKeyRange.lower)*(mKeySize-1)+0.5; + int valueCell = (value-mValueRange.lower)/(mValueRange.upper-mValueRange.lower)*(mValueSize-1)+0.5; + if (keyCell >= 0 && keyCell < mKeySize && valueCell >= 0 && valueCell < mValueSize) + { + mData[valueCell*mKeySize + keyCell] = z; + if (z < mDataBounds.lower) + mDataBounds.lower = z; + if (z > mDataBounds.upper) + mDataBounds.upper = z; + mDataModified = true; + } +} + +/*! + Sets the data of the cell with indices \a keyIndex and \a valueIndex to \a z. The indices + enumerate the cells starting from zero, up to the map's size-1 in the respective dimension (see + \ref setSize). + + In the standard plot configuration (horizontal key axis and vertical value axis, both not + range-reversed), the cell with indices (0, 0) is in the bottom left corner and the cell with + indices (keySize-1, valueSize-1) is in the top right corner of the color map. + + \see setData, setSize +*/ +void QCPColorMapData::setCell(int keyIndex, int valueIndex, double z) +{ + if (keyIndex >= 0 && keyIndex < mKeySize && valueIndex >= 0 && valueIndex < mValueSize) + { + mData[valueIndex*mKeySize + keyIndex] = z; + if (z < mDataBounds.lower) + mDataBounds.lower = z; + if (z > mDataBounds.upper) + mDataBounds.upper = z; + mDataModified = true; + } +} + +/*! + Goes through the data and updates the buffered minimum and maximum data values. + + Calling this method is only advised if you are about to call \ref QCPColorMap::rescaleDataRange + and can not guarantee that the cells holding the maximum or minimum data haven't been overwritten + with a smaller or larger value respectively, since the buffered maximum/minimum values have been + updated the last time. Why this is the case is explained in the class description (\ref + QCPColorMapData). + + Note that the method \ref QCPColorMap::rescaleDataRange provides a parameter \a + recalculateDataBounds for convenience. Setting this to true will call this method for you, before + doing the rescale. +*/ +void QCPColorMapData::recalculateDataBounds() +{ + if (mKeySize > 0 && mValueSize > 0) + { + double minHeight = mData[0]; + double maxHeight = mData[0]; + const int dataCount = mValueSize*mKeySize; + for (int i=0; i maxHeight) + maxHeight = mData[i]; + if (mData[i] < minHeight) + minHeight = mData[i]; + } + mDataBounds.lower = minHeight; + mDataBounds.upper = maxHeight; + } +} + +/*! + Frees the internal data memory. + + This is equivalent to calling \ref setSize "setSize(0, 0)". +*/ +void QCPColorMapData::clear() +{ + setSize(0, 0); +} + +/*! + Sets all cells to the value \a z. +*/ +void QCPColorMapData::fill(double z) +{ + const int dataCount = mValueSize*mKeySize; + for (int i=0; ixAxis, customPlot->yAxis);\endcode + add it to the customPlot with QCustomPlot::addPlottable: + \code + customPlot->addPlottable(colorMap);\endcode + and then modify the properties of the newly created color map, e.g.: + \code + colorMap->data()->setSize(50, 50); + colorMap->data()->setRange(QCPRange(0, 2), QCPRange(0, 2)); + for (int x=0; x<50; ++x) + for (int y=0; y<50; ++y) + colorMap->data()->setCell(x, y, qCos(x/10.0)+qSin(y/10.0)); + colorMap->setGradient(QCPColorGradient::gpPolar); + colorMap->rescaleDataRange(true); + customPlot->rescaleAxes(); + customPlot->replot(); + \endcode + + \note The QCPColorMap always displays the data at equal key/value intervals, even if the key or + value axis is set to a logarithmic scaling. If you want to use QCPColorMap with logarithmic axes, + you shouldn't use the \ref QCPColorMapData::setData method as it uses a linear transformation to + determine the cell index. Rather directly access the cell index with \ref + QCPColorMapData::setCell. +*/ + +/* start documentation of inline functions */ + +/*! \fn QCPColorMapData *QCPColorMap::data() const + + Returns a pointer to the internal data storage of type \ref QCPColorMapData. Access this to + modify data points (cells) and the color map key/value range. + + \see setData +*/ + +/* end documentation of inline functions */ + +/* start documentation of signals */ + +/*! \fn void QCPColorMap::dataRangeChanged(QCPRange newRange); + + This signal is emitted when the data range changes. + + \see setDataRange +*/ + +/*! \fn void QCPColorMap::dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + + This signal is emitted when the data scale type changes. + + \see setDataScaleType +*/ + +/*! \fn void QCPColorMap::gradientChanged(QCPColorGradient newGradient); + + This signal is emitted when the gradient changes. + + \see setGradient +*/ + +/* end documentation of signals */ + +/*! + Constructs a color map with the specified \a keyAxis and \a valueAxis. + + The constructed QCPColorMap can be added to the plot with QCustomPlot::addPlottable, QCustomPlot + then takes ownership of the color map. +*/ +QCPColorMap::QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis) : + QCPAbstractPlottable(keyAxis, valueAxis), + mDataScaleType(QCPAxis::stLinear), + mMapData(new QCPColorMapData(10, 10, QCPRange(0, 5), QCPRange(0, 5))), + mInterpolate(true), + mTightBoundary(false), + mMapImageInvalidated(true) +{ +} + +QCPColorMap::~QCPColorMap() +{ + delete mMapData; +} + +/*! + Replaces the current \ref data with the provided \a data. + + If \a copy is set to true, the \a data object will only be copied. if false, the color map + takes ownership of the passed data and replaces the internal data pointer with it. This is + significantly faster than copying for large datasets. +*/ +void QCPColorMap::setData(QCPColorMapData *data, bool copy) +{ + if (copy) + { + *mMapData = *data; + } else + { + delete mMapData; + mMapData = data; + } + mMapImageInvalidated = true; +} + +/*! + Sets the data range of this color map to \a dataRange. The data range defines which data values + are mapped to the color gradient. + + To make the data range span the full range of the data set, use \ref rescaleDataRange. + + \see QCPColorScale::setDataRange +*/ +void QCPColorMap::setDataRange(const QCPRange &dataRange) +{ + if (!QCPRange::validRange(dataRange)) return; + if (mDataRange.lower != dataRange.lower || mDataRange.upper != dataRange.upper) + { + if (mDataScaleType == QCPAxis::stLogarithmic) + mDataRange = dataRange.sanitizedForLogScale(); + else + mDataRange = dataRange.sanitizedForLinScale(); + mMapImageInvalidated = true; + emit dataRangeChanged(mDataRange); + } +} + +/*! + Sets whether the data is correlated with the color gradient linearly or logarithmically. + + \see QCPColorScale::setDataScaleType +*/ +void QCPColorMap::setDataScaleType(QCPAxis::ScaleType scaleType) +{ + if (mDataScaleType != scaleType) + { + mDataScaleType = scaleType; + mMapImageInvalidated = true; + emit dataScaleTypeChanged(mDataScaleType); + if (mDataScaleType == QCPAxis::stLogarithmic) + setDataRange(mDataRange.sanitizedForLogScale()); + } +} + +/*! + Sets the color gradient that is used to represent the data. For more details on how to create an + own gradient or use one of the preset gradients, see \ref QCPColorGradient. + + The colors defined by the gradient will be used to represent data values in the currently set + data range, see \ref setDataRange. Data points that are outside this data range will either be + colored uniformly with the respective gradient boundary color, or the gradient will repeat, + depending on \ref QCPColorGradient::setPeriodic. + + \see QCPColorScale::setGradient +*/ +void QCPColorMap::setGradient(const QCPColorGradient &gradient) +{ + if (mGradient != gradient) + { + mGradient = gradient; + mMapImageInvalidated = true; + emit gradientChanged(mGradient); + } +} + +/*! + Sets whether the color map image shall use bicubic interpolation when displaying the color map + shrinked or expanded, and not at a 1:1 pixel-to-data scale. + + \image html QCPColorMap-interpolate.png "A 10*10 color map, with interpolation and without interpolation enabled" +*/ +void QCPColorMap::setInterpolate(bool enabled) +{ + mInterpolate = enabled; +} + +/*! + Sets whether the outer most data rows and columns are clipped to the specified key and value + range (see \ref QCPColorMapData::setKeyRange, \ref QCPColorMapData::setValueRange). + + if \a enabled is set to false, the data points at the border of the color map are drawn with the + same width and height as all other data points. Since the data points are represented by + rectangles of one color centered on the data coordinate, this means that the shown color map + extends by half a data point over the specified key/value range in each direction. + + \image html QCPColorMap-tightboundary.png "A color map, with tight boundary enabled and disabled" +*/ +void QCPColorMap::setTightBoundary(bool enabled) +{ + mTightBoundary = enabled; +} + +/*! + Associates the color scale \a colorScale with this color map. + + This means that both the color scale and the color map synchronize their gradient, data range and + data scale type (\ref setGradient, \ref setDataRange, \ref setDataScaleType). Multiple color maps + can be associated with one single color scale. This causes the color maps to also synchronize + those properties, via the mutual color scale. + + This function causes the color map to adopt the current color gradient, data range and data scale + type of \a colorScale. After this call, you may change these properties at either the color map + or the color scale, and the setting will be applied to both. + + Pass 0 as \a colorScale to disconnect the color scale from this color map again. +*/ +void QCPColorMap::setColorScale(QCPColorScale *colorScale) +{ + if (mColorScale) // unconnect signals from old color scale + { + disconnect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); + disconnect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); + disconnect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); + disconnect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); + disconnect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); + disconnect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); + } + mColorScale = colorScale; + if (mColorScale) // connect signals to new color scale + { + setGradient(mColorScale.data()->gradient()); + setDataRange(mColorScale.data()->dataRange()); + setDataScaleType(mColorScale.data()->dataScaleType()); + connect(this, SIGNAL(dataRangeChanged(QCPRange)), mColorScale.data(), SLOT(setDataRange(QCPRange))); + connect(this, SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), mColorScale.data(), SLOT(setDataScaleType(QCPAxis::ScaleType))); + connect(this, SIGNAL(gradientChanged(QCPColorGradient)), mColorScale.data(), SLOT(setGradient(QCPColorGradient))); + connect(mColorScale.data(), SIGNAL(dataRangeChanged(QCPRange)), this, SLOT(setDataRange(QCPRange))); + connect(mColorScale.data(), SIGNAL(gradientChanged(QCPColorGradient)), this, SLOT(setGradient(QCPColorGradient))); + connect(mColorScale.data(), SIGNAL(dataScaleTypeChanged(QCPAxis::ScaleType)), this, SLOT(setDataScaleType(QCPAxis::ScaleType))); + } +} + +/*! + Sets the data range (\ref setDataRange) to span the minimum and maximum values that occur in the + current data set. This corresponds to the \ref rescaleKeyAxis or \ref rescaleValueAxis methods, + only for the third data dimension of the color map. + + The minimum and maximum values of the data set are buffered in the internal QCPColorMapData + instance (\ref data). As data is updated via its \ref QCPColorMapData::setCell or \ref + QCPColorMapData::setData, the buffered minimum and maximum values are updated, too. For + performance reasons, however, they are only updated in an expanding fashion. So the buffered + maximum can only increase and the buffered minimum can only decrease. In consequence, changes to + the data that actually lower the maximum of the data set (by overwriting the cell holding the + current maximum with a smaller value), aren't recognized and the buffered maximum overestimates + the true maximum of the data set. The same happens for the buffered minimum. To recalculate the + true minimum and maximum by explicitly looking at each cell, the method + QCPColorMapData::recalculateDataBounds can be used. For convenience, setting the parameter \a + recalculateDataBounds calls this method before setting the data range to the buffered minimum and + maximum. + + \see setDataRange +*/ +void QCPColorMap::rescaleDataRange(bool recalculateDataBounds) +{ + if (recalculateDataBounds) + mMapData->recalculateDataBounds(); + setDataRange(mMapData->dataBounds()); +} + +/*! + Takes the current appearance of the color map and updates the legend icon, which is used to + represent this color map in the legend (see \ref QCPLegend). + + The \a transformMode specifies whether the rescaling is done by a faster, low quality image + scaling algorithm (Qt::FastTransformation) or by a slower, higher quality algorithm + (Qt::SmoothTransformation). + + The current color map appearance is scaled down to \a thumbSize. Ideally, this should be equal to + the size of the legend icon (see \ref QCPLegend::setIconSize). If it isn't exactly the configured + legend icon size, the thumb will be rescaled during drawing of the legend item. + + \see setDataRange +*/ +void QCPColorMap::updateLegendIcon(Qt::TransformationMode transformMode, const QSize &thumbSize) +{ + if (mMapImage.isNull() && !data()->isEmpty()) + updateMapImage(); // try to update map image if it's null (happens if no draw has happened yet) + + if (!mMapImage.isNull()) // might still be null, e.g. if data is empty, so check here again + { + bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); + bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); + mLegendIcon = QPixmap::fromImage(mMapImage.mirrored(mirrorX, mirrorY)).scaled(thumbSize, Qt::KeepAspectRatio, transformMode); + } +} + +/*! + Clears the colormap data by calling \ref QCPColorMapData::clear() on the internal data. This also + resizes the map to 0x0 cells. +*/ +void QCPColorMap::clearData() +{ + mMapData->clear(); +} + +/* inherits documentation from base class */ +double QCPColorMap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) + { + double posKey, posValue; + pixelsToCoords(pos, posKey, posValue); + if (mMapData->keyRange().contains(posKey) && mMapData->valueRange().contains(posValue)) + return mParentPlot->selectionTolerance()*0.99; + } + return -1; +} + +/*! \internal + + Updates the internal map image buffer by going through the internal \ref QCPColorMapData and + turning the data values into color pixels with \ref QCPColorGradient::colorize. + + This method is called by \ref QCPColorMap::draw if either the data has been modified or the map image + has been invalidated for a different reason (e.g. a change of the data range with \ref + setDataRange). +*/ +void QCPColorMap::updateMapImage() +{ + QCPAxis *keyAxis = mKeyAxis.data(); + if (!keyAxis) return; + + // resize mMapImage to correct dimensions, according to key/value axes orientation: + if (keyAxis->orientation() == Qt::Horizontal && (mMapImage.size().width() != mMapData->keySize() || mMapImage.size().height() != mMapData->valueSize())) + mMapImage = QImage(QSize(mMapData->keySize(), mMapData->valueSize()), QImage::Format_RGB32); + else if (keyAxis->orientation() == Qt::Vertical && (mMapImage.size().width() != mMapData->valueSize() || mMapImage.size().height() != mMapData->keySize())) + mMapImage = QImage(QSize(mMapData->valueSize(), mMapData->keySize()), QImage::Format_RGB32); + + const int keySize = mMapData->keySize(); + const int valueSize = mMapData->valueSize(); + const double *rawData = mMapData->mData; + + if (keyAxis->orientation() == Qt::Horizontal) + { + const int lineCount = valueSize; + const int rowCount = keySize; + for (int line=0; line(mMapImage.scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) + mGradient.colorize(rawData+line*rowCount, mDataRange, pixels, rowCount, 1, mDataScaleType==QCPAxis::stLogarithmic); + } + } else // keyAxis->orientation() == Qt::Vertical + { + const int lineCount = keySize; + const int rowCount = valueSize; + for (int line=0; line(mMapImage.scanLine(lineCount-1-line)); // invert scanline index because QImage counts scanlines from top, but our vertical index counts from bottom (mathematical coordinate system) + mGradient.colorize(rawData+line, mDataRange, pixels, rowCount, lineCount, mDataScaleType==QCPAxis::stLogarithmic); + } + } + + mMapData->mDataModified = false; + mMapImageInvalidated = false; +} + +/* inherits documentation from base class */ +void QCPColorMap::draw(QCPPainter *painter) +{ + if (mMapData->isEmpty()) return; + if (!mKeyAxis || !mValueAxis) return; + applyDefaultAntialiasingHint(painter); + + if (mMapData->mDataModified || mMapImageInvalidated) + updateMapImage(); + + double halfSampleKey = 0; + double halfSampleValue = 0; + if (mMapData->keySize() > 1) + halfSampleKey = 0.5*mMapData->keyRange().size()/(double)(mMapData->keySize()-1); + if (mMapData->valueSize() > 1) + halfSampleValue = 0.5*mMapData->valueRange().size()/(double)(mMapData->valueSize()-1); + QRectF imageRect(coordsToPixels(mMapData->keyRange().lower-halfSampleKey, mMapData->valueRange().lower-halfSampleValue), + coordsToPixels(mMapData->keyRange().upper+halfSampleKey, mMapData->valueRange().upper+halfSampleValue)); + imageRect = imageRect.normalized(); + bool mirrorX = (keyAxis()->orientation() == Qt::Horizontal ? keyAxis() : valueAxis())->rangeReversed(); + bool mirrorY = (valueAxis()->orientation() == Qt::Vertical ? valueAxis() : keyAxis())->rangeReversed(); + bool smoothBackup = painter->renderHints().testFlag(QPainter::SmoothPixmapTransform); + painter->setRenderHint(QPainter::SmoothPixmapTransform, mInterpolate); + QRegion clipBackup; + if (mTightBoundary) + { + clipBackup = painter->clipRegion(); + painter->setClipRect(QRectF(coordsToPixels(mMapData->keyRange().lower, mMapData->valueRange().lower), + coordsToPixels(mMapData->keyRange().upper, mMapData->valueRange().upper)).normalized(), Qt::IntersectClip); + } + painter->drawImage(imageRect, mMapImage.mirrored(mirrorX, mirrorY)); + if (mTightBoundary) + painter->setClipRegion(clipBackup); + painter->setRenderHint(QPainter::SmoothPixmapTransform, smoothBackup); +} + +/* inherits documentation from base class */ +void QCPColorMap::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const +{ + applyDefaultAntialiasingHint(painter); + // draw map thumbnail: + if (!mLegendIcon.isNull()) + { + QPixmap scaledIcon = mLegendIcon.scaled(rect.size().toSize(), Qt::KeepAspectRatio, Qt::FastTransformation); + QRectF iconRect = QRectF(0, 0, scaledIcon.width(), scaledIcon.height()); + iconRect.moveCenter(rect.center()); + painter->drawPixmap(iconRect.topLeft(), scaledIcon); + } + /* + // draw frame: + painter->setBrush(Qt::NoBrush); + painter->setPen(Qt::black); + painter->drawRect(rect.adjusted(1, 1, 0, 0)); + */ +} + +/* inherits documentation from base class */ +QCPRange QCPColorMap::getKeyRange(bool &foundRange, SignDomain inSignDomain) const +{ + foundRange = true; + QCPRange result = mMapData->keyRange(); + result.normalize(); + if (inSignDomain == QCPAbstractPlottable::sdPositive) + { + if (result.lower <= 0 && result.upper > 0) + result.lower = result.upper*1e-3; + else if (result.lower <= 0 && result.upper <= 0) + foundRange = false; + } else if (inSignDomain == QCPAbstractPlottable::sdNegative) + { + if (result.upper >= 0 && result.lower < 0) + result.upper = result.lower*1e-3; + else if (result.upper >= 0 && result.lower >= 0) + foundRange = false; + } + return result; +} + +/* inherits documentation from base class */ +QCPRange QCPColorMap::getValueRange(bool &foundRange, SignDomain inSignDomain) const +{ + foundRange = true; + QCPRange result = mMapData->valueRange(); + result.normalize(); + if (inSignDomain == QCPAbstractPlottable::sdPositive) + { + if (result.lower <= 0 && result.upper > 0) + result.lower = result.upper*1e-3; + else if (result.lower <= 0 && result.upper <= 0) + foundRange = false; + } else if (inSignDomain == QCPAbstractPlottable::sdNegative) + { + if (result.upper >= 0 && result.lower < 0) + result.upper = result.lower*1e-3; + else if (result.upper >= 0 && result.lower >= 0) + foundRange = false; + } + return result; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPFinancialData +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPFinancialData + \brief Holds the data of one single data point for QCPFinancial. + + The container for storing multiple data points is \ref QCPFinancialDataMap. + + The stored data is: + \li \a key: coordinate on the key axis of this data point + \li \a open: The opening value at the data point + \li \a high: The high/maximum value at the data point + \li \a low: The low/minimum value at the data point + \li \a close: The closing value at the data point + + \see QCPFinancialDataMap +*/ + +/*! + Constructs a data point with key and all values set to zero. +*/ +QCPFinancialData::QCPFinancialData() : + key(0), + open(0), + high(0), + low(0), + close(0) +{ +} + +/*! + Constructs a data point with the specified \a key and OHLC values. +*/ +QCPFinancialData::QCPFinancialData(double key, double open, double high, double low, double close) : + key(key), + open(open), + high(high), + low(low), + close(close) +{ +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPFinancial +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPFinancial + \brief A plottable representing a financial stock chart + + \image html QCPFinancial.png + + This plottable represents time series data binned to certain intervals, mainly used for stock + charts. The two common representations OHLC (Open-High-Low-Close) bars and Candlesticks can be + set via \ref setChartStyle. + + The data is passed via \ref setData as a set of open/high/low/close values at certain keys + (typically times). This means the data must be already binned appropriately. If data is only + available as a series of values (e.g. \a price against \a time), you can use the static + convenience function \ref timeSeriesToOhlc to generate binned OHLC-data which can then be passed + to \ref setData. + + The width of the OHLC bars/candlesticks can be controlled with \ref setWidth and is given in plot + key coordinates. A typical choice is to set it to (or slightly less than) one bin interval width. + + \section appearance Changing the appearance + + Charts can be either single- or two-colored (\ref setTwoColored). If set to be single-colored, + lines are drawn with the plottable's pen (\ref setPen) and fills with the brush (\ref setBrush). + + If set to two-colored, positive changes of the value during an interval (\a close >= \a open) are + represented with a different pen and brush than negative changes (\a close < \a open). These can + be configured with \ref setPenPositive, \ref setPenNegative, \ref setBrushPositive, and \ref + setBrushNegative. In two-colored mode, the normal plottable pen/brush is ignored. Upon selection + however, the normal selected pen/brush (\ref setSelectedPen, \ref setSelectedBrush) is used, + irrespective of whether the chart is single- or two-colored. + +*/ + +/* start of documentation of inline functions */ + +/*! \fn QCPFinancialDataMap *QCPFinancial::data() const + + Returns a pointer to the internal data storage of type \ref QCPFinancialDataMap. You may use it to + directly manipulate the data, which may be more convenient and faster than using the regular \ref + setData or \ref addData methods, in certain situations. +*/ + +/* end of documentation of inline functions */ + +/*! + Constructs a financial chart which uses \a keyAxis as its key axis ("x") and \a valueAxis as its value + axis ("y"). \a keyAxis and \a valueAxis must reside in the same QCustomPlot instance and not have + the same orientation. If either of these restrictions is violated, a corresponding message is + printed to the debug output (qDebug), the construction is not aborted, though. + + The constructed QCPFinancial can be added to the plot with QCustomPlot::addPlottable, QCustomPlot + then takes ownership of the financial chart. +*/ +QCPFinancial::QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis) : + QCPAbstractPlottable(keyAxis, valueAxis), + mData(0), + mChartStyle(csOhlc), + mWidth(0.5), + mTwoColored(false), + mBrushPositive(QBrush(QColor(210, 210, 255))), + mBrushNegative(QBrush(QColor(255, 210, 210))), + mPenPositive(QPen(QColor(10, 40, 180))), + mPenNegative(QPen(QColor(180, 40, 10))) +{ + mData = new QCPFinancialDataMap; + + setSelectedPen(QPen(QColor(80, 80, 255), 2.5)); + setSelectedBrush(QBrush(QColor(80, 80, 255))); +} + +QCPFinancial::~QCPFinancial() +{ + delete mData; +} + +/*! + Replaces the current data with the provided \a data. + + If \a copy is set to true, data points in \a data will only be copied. if false, the plottable + takes ownership of the passed data and replaces the internal data pointer with it. This is + significantly faster than copying for large datasets. + + Alternatively, you can also access and modify the plottable's data via the \ref data method, which + returns a pointer to the internal \ref QCPFinancialDataMap. + + \see timeSeriesToOhlc +*/ +void QCPFinancial::setData(QCPFinancialDataMap *data, bool copy) +{ + if (copy) + { + *mData = *data; + } else + { + delete mData; + mData = data; + } +} + +/*! \overload + + Replaces the current data with the provided open/high/low/close data. The provided vectors should + have equal length. Else, the number of added points will be the size of the smallest vector. + + \see timeSeriesToOhlc +*/ +void QCPFinancial::setData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close) +{ + mData->clear(); + int n = key.size(); + n = qMin(n, open.size()); + n = qMin(n, high.size()); + n = qMin(n, low.size()); + n = qMin(n, close.size()); + for (int i=0; iinsertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i])); + } +} + +/*! + Sets which representation style shall be used to display the OHLC data. +*/ +void QCPFinancial::setChartStyle(QCPFinancial::ChartStyle style) +{ + mChartStyle = style; +} + +/*! + Sets the width of the individual bars/candlesticks to \a width in plot key coordinates. + + A typical choice is to set it to (or slightly less than) one bin interval width. +*/ +void QCPFinancial::setWidth(double width) +{ + mWidth = width; +} + +/*! + Sets whether this chart shall contrast positive from negative trends per data point by using two + separate colors to draw the respective bars/candlesticks. + + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref + setBrush). + + \see setPenPositive, setPenNegative, setBrushPositive, setBrushNegative +*/ +void QCPFinancial::setTwoColored(bool twoColored) +{ + mTwoColored = twoColored; +} + +/*! + If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills + of data points with a positive trend (i.e. bars/candlesticks with close >= open). + + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref + setBrush). + + \see setBrushNegative, setPenPositive, setPenNegative +*/ +void QCPFinancial::setBrushPositive(const QBrush &brush) +{ + mBrushPositive = brush; +} + +/*! + If \ref setTwoColored is set to true, this function controls the brush that is used to draw fills + of data points with a negative trend (i.e. bars/candlesticks with close < open). + + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref + setBrush). + + \see setBrushPositive, setPenNegative, setPenPositive +*/ +void QCPFinancial::setBrushNegative(const QBrush &brush) +{ + mBrushNegative = brush; +} + +/*! + If \ref setTwoColored is set to true, this function controls the pen that is used to draw + outlines of data points with a positive trend (i.e. bars/candlesticks with close >= open). + + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref + setBrush). + + \see setPenNegative, setBrushPositive, setBrushNegative +*/ +void QCPFinancial::setPenPositive(const QPen &pen) +{ + mPenPositive = pen; +} + +/*! + If \ref setTwoColored is set to true, this function controls the pen that is used to draw + outlines of data points with a negative trend (i.e. bars/candlesticks with close < open). + + If \a twoColored is false, the normal plottable's pen and brush are used (\ref setPen, \ref + setBrush). + + \see setPenPositive, setBrushNegative, setBrushPositive +*/ +void QCPFinancial::setPenNegative(const QPen &pen) +{ + mPenNegative = pen; +} + +/*! + Adds the provided data points in \a dataMap to the current data. + + Alternatively, you can also access and modify the data via the \ref data method, which returns a + pointer to the internal \ref QCPFinancialDataMap. + + \see removeData +*/ +void QCPFinancial::addData(const QCPFinancialDataMap &dataMap) +{ + mData->unite(dataMap); +} + +/*! \overload + + Adds the provided single data point in \a data to the current data. + + Alternatively, you can also access and modify the data via the \ref data method, which returns a + pointer to the internal \ref QCPFinancialData. + + \see removeData +*/ +void QCPFinancial::addData(const QCPFinancialData &data) +{ + mData->insertMulti(data.key, data); +} + +/*! \overload + + Adds the provided single data point given by \a key, \a open, \a high, \a low, and \a close to + the current data. + + Alternatively, you can also access and modify the data via the \ref data method, which returns a + pointer to the internal \ref QCPFinancialData. + + \see removeData +*/ +void QCPFinancial::addData(double key, double open, double high, double low, double close) +{ + mData->insertMulti(key, QCPFinancialData(key, open, high, low, close)); +} + +/*! \overload + + Adds the provided open/high/low/close data to the current data. + + Alternatively, you can also access and modify the data via the \ref data method, which returns a + pointer to the internal \ref QCPFinancialData. + + \see removeData +*/ +void QCPFinancial::addData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close) +{ + int n = key.size(); + n = qMin(n, open.size()); + n = qMin(n, high.size()); + n = qMin(n, low.size()); + n = qMin(n, close.size()); + for (int i=0; iinsertMulti(key[i], QCPFinancialData(key[i], open[i], high[i], low[i], close[i])); + } +} + +/*! + Removes all data points with keys smaller than \a key. + + \see addData, clearData +*/ +void QCPFinancial::removeDataBefore(double key) +{ + QCPFinancialDataMap::iterator it = mData->begin(); + while (it != mData->end() && it.key() < key) + it = mData->erase(it); +} + +/*! + Removes all data points with keys greater than \a key. + + \see addData, clearData +*/ +void QCPFinancial::removeDataAfter(double key) +{ + if (mData->isEmpty()) return; + QCPFinancialDataMap::iterator it = mData->upperBound(key); + while (it != mData->end()) + it = mData->erase(it); +} + +/*! + Removes all data points with keys between \a fromKey and \a toKey. if \a fromKey is greater or + equal to \a toKey, the function does nothing. To remove a single data point with known key, use + \ref removeData(double key). + + \see addData, clearData +*/ +void QCPFinancial::removeData(double fromKey, double toKey) +{ + if (fromKey >= toKey || mData->isEmpty()) return; + QCPFinancialDataMap::iterator it = mData->upperBound(fromKey); + QCPFinancialDataMap::iterator itEnd = mData->upperBound(toKey); + while (it != itEnd) + it = mData->erase(it); +} + +/*! \overload + + Removes a single data point at \a key. If the position is not known with absolute precision, + consider using \ref removeData(double fromKey, double toKey) with a small fuzziness interval + around the suspected position, depeding on the precision with which the key is known. + + \see addData, clearData +*/ +void QCPFinancial::removeData(double key) +{ + mData->remove(key); +} + +/*! + Removes all data points. + + \see removeData, removeDataAfter, removeDataBefore +*/ +void QCPFinancial::clearData() +{ + mData->clear(); +} + +/* inherits documentation from base class */ +double QCPFinancial::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + if (!mKeyAxis || !mValueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } + + if (mKeyAxis.data()->axisRect()->rect().contains(pos.toPoint())) + { + // get visible data range: + QCPFinancialDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point + getVisibleDataBounds(lower, upper); + if (lower == mData->constEnd() || upper == mData->constEnd()) + return -1; + // perform select test according to configured style: + switch (mChartStyle) + { + case QCPFinancial::csOhlc: + return ohlcSelectTest(pos, lower, upper+1); break; + case QCPFinancial::csCandlestick: + return candlestickSelectTest(pos, lower, upper+1); break; + } + } + return -1; +} + +/*! + A convenience function that converts time series data (\a value against \a time) to OHLC binned + data points. The return value can then be passed on to \ref setData. + + The size of the bins can be controlled with \a timeBinSize in the same units as \a time is given. + For example, if the unit of \a time is seconds and single OHLC/Candlesticks should span an hour + each, set \a timeBinSize to 3600. + + \a timeBinOffset allows to control precisely at what \a time coordinate a bin should start. The + value passed as \a timeBinOffset doesn't need to be in the range encompassed by the \a time keys. + It merely defines the mathematical offset/phase of the bins that will be used to process the + data. +*/ +QCPFinancialDataMap QCPFinancial::timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset) +{ + QCPFinancialDataMap map; + int count = qMin(time.size(), value.size()); + if (count == 0) + return QCPFinancialDataMap(); + + QCPFinancialData currentBinData(0, value.first(), value.first(), value.first(), value.first()); + int currentBinIndex = qFloor((time.first()-timeBinOffset)/timeBinSize+0.5); + for (int i=0; i currentBinData.high) currentBinData.high = value.at(i); + if (i == count-1) // last data point is in current bin, finalize bin: + { + currentBinData.close = value.at(i); + currentBinData.key = timeBinOffset+(index)*timeBinSize; + map.insert(currentBinData.key, currentBinData); + } + } else // data point not anymore in current bin, set close of old and open of new bin, and add old to map: + { + // finalize current bin: + currentBinData.close = value.at(i-1); + currentBinData.key = timeBinOffset+(index-1)*timeBinSize; + map.insert(currentBinData.key, currentBinData); + // start next bin: + currentBinIndex = index; + currentBinData.open = value.at(i); + currentBinData.high = value.at(i); + currentBinData.low = value.at(i); + } + } + + return map; +} + +/* inherits documentation from base class */ +void QCPFinancial::draw(QCPPainter *painter) +{ + // get visible data range: + QCPFinancialDataMap::const_iterator lower, upper; // note that upper is the actual upper point, and not 1 step after the upper point + getVisibleDataBounds(lower, upper); + if (lower == mData->constEnd() || upper == mData->constEnd()) + return; + + // draw visible data range according to configured style: + switch (mChartStyle) + { + case QCPFinancial::csOhlc: + drawOhlcPlot(painter, lower, upper+1); break; + case QCPFinancial::csCandlestick: + drawCandlestickPlot(painter, lower, upper+1); break; + } +} + +/* inherits documentation from base class */ +void QCPFinancial::drawLegendIcon(QCPPainter *painter, const QRectF &rect) const +{ + painter->setAntialiasing(false); // legend icon especially of csCandlestick looks better without antialiasing + if (mChartStyle == csOhlc) + { + if (mTwoColored) + { + // draw upper left half icon with positive color: + painter->setBrush(mBrushPositive); + painter->setPen(mPenPositive); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); + painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); + painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); + painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); + // draw bottom right hald icon with negative color: + painter->setBrush(mBrushNegative); + painter->setPen(mPenNegative); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); + painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); + painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); + painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); + } else + { + painter->setBrush(mBrush); + painter->setPen(mPen); + painter->drawLine(QLineF(0, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); + painter->drawLine(QLineF(rect.width()*0.2, rect.height()*0.3, rect.width()*0.2, rect.height()*0.5).translated(rect.topLeft())); + painter->drawLine(QLineF(rect.width()*0.8, rect.height()*0.5, rect.width()*0.8, rect.height()*0.7).translated(rect.topLeft())); + } + } else if (mChartStyle == csCandlestick) + { + if (mTwoColored) + { + // draw upper left half icon with positive color: + painter->setBrush(mBrushPositive); + painter->setPen(mPenPositive); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.topLeft().toPoint())); + painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); + painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); + painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); + // draw bottom right hald icon with negative color: + painter->setBrush(mBrushNegative); + painter->setPen(mPenNegative); + painter->setClipRegion(QRegion(QPolygon() << rect.bottomLeft().toPoint() << rect.topRight().toPoint() << rect.bottomRight().toPoint())); + painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); + painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); + painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); + } else + { + painter->setBrush(mBrush); + painter->setPen(mPen); + painter->drawLine(QLineF(0, rect.height()*0.5, rect.width()*0.25, rect.height()*0.5).translated(rect.topLeft())); + painter->drawLine(QLineF(rect.width()*0.75, rect.height()*0.5, rect.width(), rect.height()*0.5).translated(rect.topLeft())); + painter->drawRect(QRectF(rect.width()*0.25, rect.height()*0.25, rect.width()*0.5, rect.height()*0.5).translated(rect.topLeft())); + } + } +} + +/* inherits documentation from base class */ +QCPRange QCPFinancial::getKeyRange(bool &foundRange, QCPAbstractPlottable::SignDomain inSignDomain) const +{ + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + + double current; + QCPFinancialDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + current = it.value().key; + if (inSignDomain == sdBoth || (inSignDomain == sdNegative && current < 0) || (inSignDomain == sdPositive && current > 0)) + { + if (current < range.lower || !haveLower) + { + range.lower = current; + haveLower = true; + } + if (current > range.upper || !haveUpper) + { + range.upper = current; + haveUpper = true; + } + } + ++it; + } + // determine exact range by including width of bars/flags: + if (haveLower && mKeyAxis) + range.lower = range.lower-mWidth*0.5; + if (haveUpper && mKeyAxis) + range.upper = range.upper+mWidth*0.5; + foundRange = haveLower && haveUpper; + return range; +} + +/* inherits documentation from base class */ +QCPRange QCPFinancial::getValueRange(bool &foundRange, QCPAbstractPlottable::SignDomain inSignDomain) const +{ + QCPRange range; + bool haveLower = false; + bool haveUpper = false; + + QCPFinancialDataMap::const_iterator it = mData->constBegin(); + while (it != mData->constEnd()) + { + // high: + if (inSignDomain == sdBoth || (inSignDomain == sdNegative && it.value().high < 0) || (inSignDomain == sdPositive && it.value().high > 0)) + { + if (it.value().high < range.lower || !haveLower) + { + range.lower = it.value().high; + haveLower = true; + } + if (it.value().high > range.upper || !haveUpper) + { + range.upper = it.value().high; + haveUpper = true; + } + } + // low: + if (inSignDomain == sdBoth || (inSignDomain == sdNegative && it.value().low < 0) || (inSignDomain == sdPositive && it.value().low > 0)) + { + if (it.value().low < range.lower || !haveLower) + { + range.lower = it.value().low; + haveLower = true; + } + if (it.value().low > range.upper || !haveUpper) + { + range.upper = it.value().low; + haveUpper = true; + } + } + ++it; + } + + foundRange = haveLower && haveUpper; + return range; +} + +/*! \internal + + Draws the data from \a begin to \a end as OHLC bars with the provided \a painter. + + This method is a helper function for \ref draw. It is used when the chart style is \ref csOhlc. +*/ +void QCPFinancial::drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + + QPen linePen; + + if (keyAxis->orientation() == Qt::Horizontal) + { + for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) + { + if (mSelected) + linePen = mSelectedPen; + else if (mTwoColored) + linePen = it.value().close >= it.value().open ? mPenPositive : mPenNegative; + else + linePen = mPen; + painter->setPen(linePen); + double keyPixel = keyAxis->coordToPixel(it.value().key); + double openPixel = valueAxis->coordToPixel(it.value().open); + double closePixel = valueAxis->coordToPixel(it.value().close); + // draw backbone: + painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().low))); + // draw open: + double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); // sign of this makes sure open/close are on correct sides + painter->drawLine(QPointF(keyPixel-keyWidthPixels, openPixel), QPointF(keyPixel, openPixel)); + // draw close: + painter->drawLine(QPointF(keyPixel, closePixel), QPointF(keyPixel+keyWidthPixels, closePixel)); + } + } else + { + for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) + { + if (mSelected) + linePen = mSelectedPen; + else if (mTwoColored) + linePen = it.value().close >= it.value().open ? mPenPositive : mPenNegative; + else + linePen = mPen; + painter->setPen(linePen); + double keyPixel = keyAxis->coordToPixel(it.value().key); + double openPixel = valueAxis->coordToPixel(it.value().open); + double closePixel = valueAxis->coordToPixel(it.value().close); + // draw backbone: + painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().low), keyPixel)); + // draw open: + double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); // sign of this makes sure open/close are on correct sides + painter->drawLine(QPointF(openPixel, keyPixel-keyWidthPixels), QPointF(openPixel, keyPixel)); + // draw close: + painter->drawLine(QPointF(closePixel, keyPixel), QPointF(closePixel, keyPixel+keyWidthPixels)); + } + } +} + +/*! \internal + + Draws the data from \a begin to \a end as Candlesticks with the provided \a painter. + + This method is a helper function for \ref draw. It is used when the chart style is \ref csCandlestick. +*/ +void QCPFinancial::drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return; } + + QPen linePen; + QBrush boxBrush; + + if (keyAxis->orientation() == Qt::Horizontal) + { + for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) + { + if (mSelected) + { + linePen = mSelectedPen; + boxBrush = mSelectedBrush; + } else if (mTwoColored) + { + if (it.value().close >= it.value().open) + { + linePen = mPenPositive; + boxBrush = mBrushPositive; + } else + { + linePen = mPenNegative; + boxBrush = mBrushNegative; + } + } else + { + linePen = mPen; + boxBrush = mBrush; + } + painter->setPen(linePen); + painter->setBrush(boxBrush); + double keyPixel = keyAxis->coordToPixel(it.value().key); + double openPixel = valueAxis->coordToPixel(it.value().open); + double closePixel = valueAxis->coordToPixel(it.value().close); + // draw high: + painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it.value().open, it.value().close)))); + // draw low: + painter->drawLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it.value().open, it.value().close)))); + // draw open-close box: + double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); + painter->drawRect(QRectF(QPointF(keyPixel-keyWidthPixels, closePixel), QPointF(keyPixel+keyWidthPixels, openPixel))); + } + } else // keyAxis->orientation() == Qt::Vertical + { + for (QCPFinancialDataMap::const_iterator it = begin; it != end; ++it) + { + if (mSelected) + { + linePen = mSelectedPen; + boxBrush = mSelectedBrush; + } else if (mTwoColored) + { + if (it.value().close >= it.value().open) + { + linePen = mPenPositive; + boxBrush = mBrushPositive; + } else + { + linePen = mPenNegative; + boxBrush = mBrushNegative; + } + } else + { + linePen = mPen; + boxBrush = mBrush; + } + painter->setPen(linePen); + painter->setBrush(boxBrush); + double keyPixel = keyAxis->coordToPixel(it.value().key); + double openPixel = valueAxis->coordToPixel(it.value().open); + double closePixel = valueAxis->coordToPixel(it.value().close); + // draw high: + painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)), keyPixel)); + // draw low: + painter->drawLine(QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().close)), keyPixel)); + // draw open-close box: + double keyWidthPixels = keyPixel-keyAxis->coordToPixel(it.value().key-mWidth*0.5); + painter->drawRect(QRectF(QPointF(closePixel, keyPixel-keyWidthPixels), QPointF(openPixel, keyPixel+keyWidthPixels))); + } + } +} + +/*! \internal + + This method is a helper function for \ref selectTest. It is used to test for selection when the + chart style is \ref csOhlc. It only tests against the data points between \a begin and \a end. +*/ +double QCPFinancial::ohlcSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } + + double minDistSqr = std::numeric_limits::max(); + QCPFinancialDataMap::const_iterator it; + if (keyAxis->orientation() == Qt::Horizontal) + { + for (it = begin; it != end; ++it) + { + double keyPixel = keyAxis->coordToPixel(it.value().key); + // calculate distance to backbone: + double currentDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), pos); + if (currentDistSqr < minDistSqr) + minDistSqr = currentDistSqr; + } + } else // keyAxis->orientation() == Qt::Vertical + { + for (it = begin; it != end; ++it) + { + double keyPixel = keyAxis->coordToPixel(it.value().key); + // calculate distance to backbone: + double currentDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), pos); + if (currentDistSqr < minDistSqr) + minDistSqr = currentDistSqr; + } + } + return qSqrt(minDistSqr); +} + +/*! \internal + + This method is a helper function for \ref selectTest. It is used to test for selection when the + chart style is \ref csCandlestick. It only tests against the data points between \a begin and \a + end. +*/ +double QCPFinancial::candlestickSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const +{ + QCPAxis *keyAxis = mKeyAxis.data(); + QCPAxis *valueAxis = mValueAxis.data(); + if (!keyAxis || !valueAxis) { qDebug() << Q_FUNC_INFO << "invalid key or value axis"; return -1; } + + double minDistSqr = std::numeric_limits::max(); + QCPFinancialDataMap::const_iterator it; + if (keyAxis->orientation() == Qt::Horizontal) + { + for (it = begin; it != end; ++it) + { + double currentDistSqr; + // determine whether pos is in open-close-box: + QCPRange boxKeyRange(it.value().key-mWidth*0.5, it.value().key+mWidth*0.5); + QCPRange boxValueRange(it.value().close, it.value().open); + double posKey, posValue; + pixelsToCoords(pos, posKey, posValue); + if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box + { + currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; + } else + { + // calculate distance to high/low lines: + double keyPixel = keyAxis->coordToPixel(it.value().key); + double highLineDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().high)), QPointF(keyPixel, valueAxis->coordToPixel(qMax(it.value().open, it.value().close))), pos); + double lowLineDistSqr = distSqrToLine(QPointF(keyPixel, valueAxis->coordToPixel(it.value().low)), QPointF(keyPixel, valueAxis->coordToPixel(qMin(it.value().open, it.value().close))), pos); + currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); + } + if (currentDistSqr < minDistSqr) + minDistSqr = currentDistSqr; + } + } else // keyAxis->orientation() == Qt::Vertical + { + for (it = begin; it != end; ++it) + { + double currentDistSqr; + // determine whether pos is in open-close-box: + QCPRange boxKeyRange(it.value().key-mWidth*0.5, it.value().key+mWidth*0.5); + QCPRange boxValueRange(it.value().close, it.value().open); + double posKey, posValue; + pixelsToCoords(pos, posKey, posValue); + if (boxKeyRange.contains(posKey) && boxValueRange.contains(posValue)) // is in open-close-box + { + currentDistSqr = mParentPlot->selectionTolerance()*0.99 * mParentPlot->selectionTolerance()*0.99; + } else + { + // calculate distance to high/low lines: + double keyPixel = keyAxis->coordToPixel(it.value().key); + double highLineDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().high), keyPixel), QPointF(valueAxis->coordToPixel(qMax(it.value().open, it.value().close)), keyPixel), pos); + double lowLineDistSqr = distSqrToLine(QPointF(valueAxis->coordToPixel(it.value().low), keyPixel), QPointF(valueAxis->coordToPixel(qMin(it.value().open, it.value().close)), keyPixel), pos); + currentDistSqr = qMin(highLineDistSqr, lowLineDistSqr); + } + if (currentDistSqr < minDistSqr) + minDistSqr = currentDistSqr; + } + } + return qSqrt(minDistSqr); +} + +/*! \internal + + called by the drawing methods to determine which data (key) range is visible at the current key + axis range setting, so only that needs to be processed. + + \a lower returns an iterator to the lowest data point that needs to be taken into account when + plotting. Note that in order to get a clean plot all the way to the edge of the axis rect, \a + lower may still be just outside the visible range. + + \a upper returns an iterator to the highest data point. Same as before, \a upper may also lie + just outside of the visible range. + + if the plottable contains no data, both \a lower and \a upper point to constEnd. + + \see QCPGraph::getVisibleDataBounds +*/ +void QCPFinancial::getVisibleDataBounds(QCPFinancialDataMap::const_iterator &lower, QCPFinancialDataMap::const_iterator &upper) const +{ + if (!mKeyAxis) { qDebug() << Q_FUNC_INFO << "invalid key axis"; return; } + if (mData->isEmpty()) + { + lower = mData->constEnd(); + upper = mData->constEnd(); + return; + } + + // get visible data range as QMap iterators + QCPFinancialDataMap::const_iterator lbound = mData->lowerBound(mKeyAxis.data()->range().lower); + QCPFinancialDataMap::const_iterator ubound = mData->upperBound(mKeyAxis.data()->range().upper); + bool lowoutlier = lbound != mData->constBegin(); // indicates whether there exist points below axis range + bool highoutlier = ubound != mData->constEnd(); // indicates whether there exist points above axis range + + lower = (lowoutlier ? lbound-1 : lbound); // data point range that will be actually drawn + upper = (highoutlier ? ubound : ubound-1); // data point range that will be actually drawn +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemStraightLine +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemStraightLine + \brief A straight line that spans infinitely in both directions + + \image html QCPItemStraightLine.png "Straight line example. Blue dotted circles are anchors, solid blue discs are positions." + + It has two positions, \a point1 and \a point2, which define the straight line. +*/ + +/*! + Creates a straight line item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemStraightLine::QCPItemStraightLine(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + point1(createPosition("point1")), + point2(createPosition("point2")) +{ + point1->setCoords(0, 0); + point2->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue,2)); +} + +QCPItemStraightLine::~QCPItemStraightLine() +{ +} + +/*! + Sets the pen that will be used to draw the line + + \see setSelectedPen +*/ +void QCPItemStraightLine::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw the line when selected + + \see setPen, setSelected +*/ +void QCPItemStraightLine::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/* inherits documentation from base class */ +double QCPItemStraightLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + return distToStraightLine(QVector2D(point1->pixelPoint()), QVector2D(point2->pixelPoint()-point1->pixelPoint()), QVector2D(pos)); +} + +/* inherits documentation from base class */ +void QCPItemStraightLine::draw(QCPPainter *painter) +{ + QVector2D start(point1->pixelPoint()); + QVector2D end(point2->pixelPoint()); + // get visible segment of straight line inside clipRect: + double clipPad = mainPen().widthF(); + QLineF line = getRectClippedStraightLine(start, end-start, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); + // paint visible segment, if existent: + if (!line.isNull()) + { + painter->setPen(mainPen()); + painter->drawLine(line); + } +} + +/*! \internal + + finds the shortest distance of \a point to the straight line defined by the base point \a + base and the direction vector \a vec. + + This is a helper function for \ref selectTest. +*/ +double QCPItemStraightLine::distToStraightLine(const QVector2D &base, const QVector2D &vec, const QVector2D &point) const +{ + return qAbs((base.y()-point.y())*vec.x()-(base.x()-point.x())*vec.y())/vec.length(); +} + +/*! \internal + + Returns the section of the straight line defined by \a base and direction vector \a + vec, that is visible in the specified \a rect. + + This is a helper function for \ref draw. +*/ +QLineF QCPItemStraightLine::getRectClippedStraightLine(const QVector2D &base, const QVector2D &vec, const QRect &rect) const +{ + double bx, by; + double gamma; + QLineF result; + if (vec.x() == 0 && vec.y() == 0) + return result; + if (qFuzzyIsNull(vec.x())) // line is vertical + { + // check top of rect: + bx = rect.left(); + by = rect.top(); + gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); + if (gamma >= 0 && gamma <= rect.width()) + result.setLine(bx+gamma, rect.top(), bx+gamma, rect.bottom()); // no need to check bottom because we know line is vertical + } else if (qFuzzyIsNull(vec.y())) // line is horizontal + { + // check left of rect: + bx = rect.left(); + by = rect.top(); + gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); + if (gamma >= 0 && gamma <= rect.height()) + result.setLine(rect.left(), by+gamma, rect.right(), by+gamma); // no need to check right because we know line is horizontal + } else // line is skewed + { + QList pointVectors; + // check top of rect: + bx = rect.left(); + by = rect.top(); + gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); + if (gamma >= 0 && gamma <= rect.width()) + pointVectors.append(QVector2D(bx+gamma, by)); + // check bottom of rect: + bx = rect.left(); + by = rect.bottom(); + gamma = base.x()-bx + (by-base.y())*vec.x()/vec.y(); + if (gamma >= 0 && gamma <= rect.width()) + pointVectors.append(QVector2D(bx+gamma, by)); + // check left of rect: + bx = rect.left(); + by = rect.top(); + gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); + if (gamma >= 0 && gamma <= rect.height()) + pointVectors.append(QVector2D(bx, by+gamma)); + // check right of rect: + bx = rect.right(); + by = rect.top(); + gamma = base.y()-by + (bx-base.x())*vec.y()/vec.x(); + if (gamma >= 0 && gamma <= rect.height()) + pointVectors.append(QVector2D(bx, by+gamma)); + + // evaluate points: + if (pointVectors.size() == 2) + { + result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); + } else if (pointVectors.size() > 2) + { + // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: + double distSqrMax = 0; + QVector2D pv1, pv2; + for (int i=0; i distSqrMax) + { + pv1 = pointVectors.at(i); + pv2 = pointVectors.at(k); + distSqrMax = distSqr; + } + } + } + result.setPoints(pv1.toPointF(), pv2.toPointF()); + } + } + return result; +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the + item is not selected and mSelectedPen when it is. +*/ +QPen QCPItemStraightLine::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemLine +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemLine + \brief A line from one point to another + + \image html QCPItemLine.png "Line example. Blue dotted circles are anchors, solid blue discs are positions." + + It has two positions, \a start and \a end, which define the end points of the line. + + With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an arrow. +*/ + +/*! + Creates a line item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemLine::QCPItemLine(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + start(createPosition("start")), + end(createPosition("end")) +{ + start->setCoords(0, 0); + end->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue,2)); +} + +QCPItemLine::~QCPItemLine() +{ +} + +/*! + Sets the pen that will be used to draw the line + + \see setSelectedPen +*/ +void QCPItemLine::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw the line when selected + + \see setPen, setSelected +*/ +void QCPItemLine::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + Sets the line ending style of the head. The head corresponds to the \a end position. + + Note that due to the overloaded QCPLineEnding constructor, you may directly specify + a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode + + \see setTail +*/ +void QCPItemLine::setHead(const QCPLineEnding &head) +{ + mHead = head; +} + +/*! + Sets the line ending style of the tail. The tail corresponds to the \a start position. + + Note that due to the overloaded QCPLineEnding constructor, you may directly specify + a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode + + \see setHead +*/ +void QCPItemLine::setTail(const QCPLineEnding &tail) +{ + mTail = tail; +} + +/* inherits documentation from base class */ +double QCPItemLine::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + return qSqrt(distSqrToLine(start->pixelPoint(), end->pixelPoint(), pos)); +} + +/* inherits documentation from base class */ +void QCPItemLine::draw(QCPPainter *painter) +{ + QVector2D startVec(start->pixelPoint()); + QVector2D endVec(end->pixelPoint()); + if (startVec.toPoint() == endVec.toPoint()) + return; + // get visible segment of straight line inside clipRect: + double clipPad = qMax(mHead.boundingDistance(), mTail.boundingDistance()); + clipPad = qMax(clipPad, (double)mainPen().widthF()); + QLineF line = getRectClippedLine(startVec, endVec, clipRect().adjusted(-clipPad, -clipPad, clipPad, clipPad)); + // paint visible segment, if existent: + if (!line.isNull()) + { + painter->setPen(mainPen()); + painter->drawLine(line); + painter->setBrush(Qt::SolidPattern); + if (mTail.style() != QCPLineEnding::esNone) + mTail.draw(painter, startVec, startVec-endVec); + if (mHead.style() != QCPLineEnding::esNone) + mHead.draw(painter, endVec, endVec-startVec); + } +} + +/*! \internal + + Returns the section of the line defined by \a start and \a end, that is visible in the specified + \a rect. + + This is a helper function for \ref draw. +*/ +QLineF QCPItemLine::getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const +{ + bool containsStart = rect.contains(start.x(), start.y()); + bool containsEnd = rect.contains(end.x(), end.y()); + if (containsStart && containsEnd) + return QLineF(start.toPointF(), end.toPointF()); + + QVector2D base = start; + QVector2D vec = end-start; + double bx, by; + double gamma, mu; + QLineF result; + QList pointVectors; + + if (!qFuzzyIsNull(vec.y())) // line is not horizontal + { + // check top of rect: + bx = rect.left(); + by = rect.top(); + mu = (by-base.y())/vec.y(); + if (mu >= 0 && mu <= 1) + { + gamma = base.x()-bx + mu*vec.x(); + if (gamma >= 0 && gamma <= rect.width()) + pointVectors.append(QVector2D(bx+gamma, by)); + } + // check bottom of rect: + bx = rect.left(); + by = rect.bottom(); + mu = (by-base.y())/vec.y(); + if (mu >= 0 && mu <= 1) + { + gamma = base.x()-bx + mu*vec.x(); + if (gamma >= 0 && gamma <= rect.width()) + pointVectors.append(QVector2D(bx+gamma, by)); + } + } + if (!qFuzzyIsNull(vec.x())) // line is not vertical + { + // check left of rect: + bx = rect.left(); + by = rect.top(); + mu = (bx-base.x())/vec.x(); + if (mu >= 0 && mu <= 1) + { + gamma = base.y()-by + mu*vec.y(); + if (gamma >= 0 && gamma <= rect.height()) + pointVectors.append(QVector2D(bx, by+gamma)); + } + // check right of rect: + bx = rect.right(); + by = rect.top(); + mu = (bx-base.x())/vec.x(); + if (mu >= 0 && mu <= 1) + { + gamma = base.y()-by + mu*vec.y(); + if (gamma >= 0 && gamma <= rect.height()) + pointVectors.append(QVector2D(bx, by+gamma)); + } + } + + if (containsStart) + pointVectors.append(start); + if (containsEnd) + pointVectors.append(end); + + // evaluate points: + if (pointVectors.size() == 2) + { + result.setPoints(pointVectors.at(0).toPointF(), pointVectors.at(1).toPointF()); + } else if (pointVectors.size() > 2) + { + // line probably goes through corner of rect, and we got two points there. single out the point pair with greatest distance: + double distSqrMax = 0; + QVector2D pv1, pv2; + for (int i=0; i distSqrMax) + { + pv1 = pointVectors.at(i); + pv2 = pointVectors.at(k); + distSqrMax = distSqr; + } + } + } + result.setPoints(pv1.toPointF(), pv2.toPointF()); + } + return result; +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the + item is not selected and mSelectedPen when it is. +*/ +QPen QCPItemLine::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemCurve +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemCurve + \brief A curved line from one point to another + + \image html QCPItemCurve.png "Curve example. Blue dotted circles are anchors, solid blue discs are positions." + + It has four positions, \a start and \a end, which define the end points of the line, and two + control points which define the direction the line exits from the start and the direction from + which it approaches the end: \a startDir and \a endDir. + + With \ref setHead and \ref setTail you may set different line ending styles, e.g. to create an + arrow. + + Often it is desirable for the control points to stay at fixed relative positions to the start/end + point. This can be achieved by setting the parent anchor e.g. of \a startDir simply to \a start, + and then specify the desired pixel offset with QCPItemPosition::setCoords on \a startDir. +*/ + +/*! + Creates a curve item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemCurve::QCPItemCurve(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + start(createPosition("start")), + startDir(createPosition("startDir")), + endDir(createPosition("endDir")), + end(createPosition("end")) +{ + start->setCoords(0, 0); + startDir->setCoords(0.5, 0); + endDir->setCoords(0, 0.5); + end->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue,2)); +} + +QCPItemCurve::~QCPItemCurve() +{ +} + +/*! + Sets the pen that will be used to draw the line + + \see setSelectedPen +*/ +void QCPItemCurve::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw the line when selected + + \see setPen, setSelected +*/ +void QCPItemCurve::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + Sets the line ending style of the head. The head corresponds to the \a end position. + + Note that due to the overloaded QCPLineEnding constructor, you may directly specify + a QCPLineEnding::EndingStyle here, e.g. \code setHead(QCPLineEnding::esSpikeArrow) \endcode + + \see setTail +*/ +void QCPItemCurve::setHead(const QCPLineEnding &head) +{ + mHead = head; +} + +/*! + Sets the line ending style of the tail. The tail corresponds to the \a start position. + + Note that due to the overloaded QCPLineEnding constructor, you may directly specify + a QCPLineEnding::EndingStyle here, e.g. \code setTail(QCPLineEnding::esSpikeArrow) \endcode + + \see setHead +*/ +void QCPItemCurve::setTail(const QCPLineEnding &tail) +{ + mTail = tail; +} + +/* inherits documentation from base class */ +double QCPItemCurve::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + QPointF startVec(start->pixelPoint()); + QPointF startDirVec(startDir->pixelPoint()); + QPointF endDirVec(endDir->pixelPoint()); + QPointF endVec(end->pixelPoint()); + + QPainterPath cubicPath(startVec); + cubicPath.cubicTo(startDirVec, endDirVec, endVec); + + QPolygonF polygon = cubicPath.toSubpathPolygons().first(); + double minDistSqr = std::numeric_limits::max(); + for (int i=1; ipixelPoint()); + QPointF startDirVec(startDir->pixelPoint()); + QPointF endDirVec(endDir->pixelPoint()); + QPointF endVec(end->pixelPoint()); + if (QVector2D(endVec-startVec).length() > 1e10f) // too large curves cause crash + return; + + QPainterPath cubicPath(startVec); + cubicPath.cubicTo(startDirVec, endDirVec, endVec); + + // paint visible segment, if existent: + QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); + QRect cubicRect = cubicPath.controlPointRect().toRect(); + if (cubicRect.isEmpty()) // may happen when start and end exactly on same x or y position + cubicRect.adjust(0, 0, 1, 1); + if (clip.intersects(cubicRect)) + { + painter->setPen(mainPen()); + painter->drawPath(cubicPath); + painter->setBrush(Qt::SolidPattern); + if (mTail.style() != QCPLineEnding::esNone) + mTail.draw(painter, QVector2D(startVec), M_PI-cubicPath.angleAtPercent(0)/180.0*M_PI); + if (mHead.style() != QCPLineEnding::esNone) + mHead.draw(painter, QVector2D(endVec), -cubicPath.angleAtPercent(1)/180.0*M_PI); + } +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the + item is not selected and mSelectedPen when it is. +*/ +QPen QCPItemCurve::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemRect +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemRect + \brief A rectangle + + \image html QCPItemRect.png "Rectangle example. Blue dotted circles are anchors, solid blue discs are positions." + + It has two positions, \a topLeft and \a bottomRight, which define the rectangle. +*/ + +/*! + Creates a rectangle item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemRect::QCPItemRect(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + topLeft(createPosition("topLeft")), + bottomRight(createPosition("bottomRight")), + top(createAnchor("top", aiTop)), + topRight(createAnchor("topRight", aiTopRight)), + right(createAnchor("right", aiRight)), + bottom(createAnchor("bottom", aiBottom)), + bottomLeft(createAnchor("bottomLeft", aiBottomLeft)), + left(createAnchor("left", aiLeft)) +{ + topLeft->setCoords(0, 1); + bottomRight->setCoords(1, 0); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue,2)); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); +} + +QCPItemRect::~QCPItemRect() +{ +} + +/*! + Sets the pen that will be used to draw the line of the rectangle + + \see setSelectedPen, setBrush +*/ +void QCPItemRect::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw the line of the rectangle when selected + + \see setPen, setSelected +*/ +void QCPItemRect::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + Sets the brush that will be used to fill the rectangle. To disable filling, set \a brush to + Qt::NoBrush. + + \see setSelectedBrush, setPen +*/ +void QCPItemRect::setBrush(const QBrush &brush) +{ + mBrush = brush; +} + +/*! + Sets the brush that will be used to fill the rectangle when selected. To disable filling, set \a + brush to Qt::NoBrush. + + \see setBrush +*/ +void QCPItemRect::setSelectedBrush(const QBrush &brush) +{ + mSelectedBrush = brush; +} + +/* inherits documentation from base class */ +double QCPItemRect::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()).normalized(); + bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; + return rectSelectTest(rect, pos, filledRect); +} + +/* inherits documentation from base class */ +void QCPItemRect::draw(QCPPainter *painter) +{ + QPointF p1 = topLeft->pixelPoint(); + QPointF p2 = bottomRight->pixelPoint(); + if (p1.toPoint() == p2.toPoint()) + return; + QRectF rect = QRectF(p1, p2).normalized(); + double clipPad = mainPen().widthF(); + QRectF boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); + if (boundingRect.intersects(clipRect())) // only draw if bounding rect of rect item is visible in cliprect + { + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + painter->drawRect(rect); + } +} + +/* inherits documentation from base class */ +QPointF QCPItemRect::anchorPixelPoint(int anchorId) const +{ + QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); + switch (anchorId) + { + case aiTop: return (rect.topLeft()+rect.topRight())*0.5; + case aiTopRight: return rect.topRight(); + case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; + case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; + case aiBottomLeft: return rect.bottomLeft(); + case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected + and mSelectedPen when it is. +*/ +QPen QCPItemRect::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + +/*! \internal + + Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item + is not selected and mSelectedBrush when it is. +*/ +QBrush QCPItemRect::mainBrush() const +{ + return mSelected ? mSelectedBrush : mBrush; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemText +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemText + \brief A text label + + \image html QCPItemText.png "Text example. Blue dotted circles are anchors, solid blue discs are positions." + + Its position is defined by the member \a position and the setting of \ref setPositionAlignment. + The latter controls which part of the text rect shall be aligned with \a position. + + The text alignment itself (i.e. left, center, right) can be controlled with \ref + setTextAlignment. + + The text may be rotated around the \a position point with \ref setRotation. +*/ + +/*! + Creates a text item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemText::QCPItemText(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + position(createPosition("position")), + topLeft(createAnchor("topLeft", aiTopLeft)), + top(createAnchor("top", aiTop)), + topRight(createAnchor("topRight", aiTopRight)), + right(createAnchor("right", aiRight)), + bottomRight(createAnchor("bottomRight", aiBottomRight)), + bottom(createAnchor("bottom", aiBottom)), + bottomLeft(createAnchor("bottomLeft", aiBottomLeft)), + left(createAnchor("left", aiLeft)) +{ + position->setCoords(0, 0); + + setRotation(0); + setTextAlignment(Qt::AlignTop|Qt::AlignHCenter); + setPositionAlignment(Qt::AlignCenter); + setText("text"); + + setPen(Qt::NoPen); + setSelectedPen(Qt::NoPen); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); + setColor(Qt::black); + setSelectedColor(Qt::blue); +} + +QCPItemText::~QCPItemText() +{ +} + +/*! + Sets the color of the text. +*/ +void QCPItemText::setColor(const QColor &color) +{ + mColor = color; +} + +/*! + Sets the color of the text that will be used when the item is selected. +*/ +void QCPItemText::setSelectedColor(const QColor &color) +{ + mSelectedColor = color; +} + +/*! + Sets the pen that will be used do draw a rectangular border around the text. To disable the + border, set \a pen to Qt::NoPen. + + \see setSelectedPen, setBrush, setPadding +*/ +void QCPItemText::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used do draw a rectangular border around the text, when the item is + selected. To disable the border, set \a pen to Qt::NoPen. + + \see setPen +*/ +void QCPItemText::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + Sets the brush that will be used do fill the background of the text. To disable the + background, set \a brush to Qt::NoBrush. + + \see setSelectedBrush, setPen, setPadding +*/ +void QCPItemText::setBrush(const QBrush &brush) +{ + mBrush = brush; +} + +/*! + Sets the brush that will be used do fill the background of the text, when the item is selected. To disable the + background, set \a brush to Qt::NoBrush. + + \see setBrush +*/ +void QCPItemText::setSelectedBrush(const QBrush &brush) +{ + mSelectedBrush = brush; +} + +/*! + Sets the font of the text. + + \see setSelectedFont, setColor +*/ +void QCPItemText::setFont(const QFont &font) +{ + mFont = font; +} + +/*! + Sets the font of the text that will be used when the item is selected. + + \see setFont +*/ +void QCPItemText::setSelectedFont(const QFont &font) +{ + mSelectedFont = font; +} + +/*! + Sets the text that will be displayed. Multi-line texts are supported by inserting a line break + character, e.g. '\n'. + + \see setFont, setColor, setTextAlignment +*/ +void QCPItemText::setText(const QString &text) +{ + mText = text; +} + +/*! + Sets which point of the text rect shall be aligned with \a position. + + Examples: + \li If \a alignment is Qt::AlignHCenter | Qt::AlignTop, the text will be positioned such + that the top of the text rect will be horizontally centered on \a position. + \li If \a alignment is Qt::AlignLeft | Qt::AlignBottom, \a position will indicate the + bottom left corner of the text rect. + + If you want to control the alignment of (multi-lined) text within the text rect, use \ref + setTextAlignment. +*/ +void QCPItemText::setPositionAlignment(Qt::Alignment alignment) +{ + mPositionAlignment = alignment; +} + +/*! + Controls how (multi-lined) text is aligned inside the text rect (typically Qt::AlignLeft, Qt::AlignCenter or Qt::AlignRight). +*/ +void QCPItemText::setTextAlignment(Qt::Alignment alignment) +{ + mTextAlignment = alignment; +} + +/*! + Sets the angle in degrees by which the text (and the text rectangle, if visible) will be rotated + around \a position. +*/ +void QCPItemText::setRotation(double degrees) +{ + mRotation = degrees; +} + +/*! + Sets the distance between the border of the text rectangle and the text. The appearance (and + visibility) of the text rectangle can be controlled with \ref setPen and \ref setBrush. +*/ +void QCPItemText::setPadding(const QMargins &padding) +{ + mPadding = padding; +} + +/* inherits documentation from base class */ +double QCPItemText::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + // The rect may be rotated, so we transform the actual clicked pos to the rotated + // coordinate system, so we can use the normal rectSelectTest function for non-rotated rects: + QPointF positionPixels(position->pixelPoint()); + QTransform inputTransform; + inputTransform.translate(positionPixels.x(), positionPixels.y()); + inputTransform.rotate(-mRotation); + inputTransform.translate(-positionPixels.x(), -positionPixels.y()); + QPointF rotatedPos = inputTransform.map(pos); + QFontMetrics fontMetrics(mFont); + QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); + QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); + QPointF textPos = getTextDrawPoint(positionPixels, textBoxRect, mPositionAlignment); + textBoxRect.moveTopLeft(textPos.toPoint()); + + return rectSelectTest(textBoxRect, rotatedPos, true); +} + +/* inherits documentation from base class */ +void QCPItemText::draw(QCPPainter *painter) +{ + QPointF pos(position->pixelPoint()); + QTransform transform = painter->transform(); + transform.translate(pos.x(), pos.y()); + if (!qFuzzyIsNull(mRotation)) + transform.rotate(mRotation); + painter->setFont(mainFont()); + QRect textRect = painter->fontMetrics().boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); + QRect textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); + QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation + textRect.moveTopLeft(textPos.toPoint()+QPoint(mPadding.left(), mPadding.top())); + textBoxRect.moveTopLeft(textPos.toPoint()); + double clipPad = mainPen().widthF(); + QRect boundingRect = textBoxRect.adjusted(-clipPad, -clipPad, clipPad, clipPad); + if (transform.mapRect(boundingRect).intersects(painter->transform().mapRect(clipRect()))) + { + painter->setTransform(transform); + if ((mainBrush().style() != Qt::NoBrush && mainBrush().color().alpha() != 0) || + (mainPen().style() != Qt::NoPen && mainPen().color().alpha() != 0)) + { + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + painter->drawRect(textBoxRect); + } + painter->setBrush(Qt::NoBrush); + painter->setPen(QPen(mainColor())); + painter->drawText(textRect, Qt::TextDontClip|mTextAlignment, mText); + } +} + +/* inherits documentation from base class */ +QPointF QCPItemText::anchorPixelPoint(int anchorId) const +{ + // get actual rect points (pretty much copied from draw function): + QPointF pos(position->pixelPoint()); + QTransform transform; + transform.translate(pos.x(), pos.y()); + if (!qFuzzyIsNull(mRotation)) + transform.rotate(mRotation); + QFontMetrics fontMetrics(mainFont()); + QRect textRect = fontMetrics.boundingRect(0, 0, 0, 0, Qt::TextDontClip|mTextAlignment, mText); + QRectF textBoxRect = textRect.adjusted(-mPadding.left(), -mPadding.top(), mPadding.right(), mPadding.bottom()); + QPointF textPos = getTextDrawPoint(QPointF(0, 0), textBoxRect, mPositionAlignment); // 0, 0 because the transform does the translation + textBoxRect.moveTopLeft(textPos.toPoint()); + QPolygonF rectPoly = transform.map(QPolygonF(textBoxRect)); + + switch (anchorId) + { + case aiTopLeft: return rectPoly.at(0); + case aiTop: return (rectPoly.at(0)+rectPoly.at(1))*0.5; + case aiTopRight: return rectPoly.at(1); + case aiRight: return (rectPoly.at(1)+rectPoly.at(2))*0.5; + case aiBottomRight: return rectPoly.at(2); + case aiBottom: return (rectPoly.at(2)+rectPoly.at(3))*0.5; + case aiBottomLeft: return rectPoly.at(3); + case aiLeft: return (rectPoly.at(3)+rectPoly.at(0))*0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); +} + +/*! \internal + + Returns the point that must be given to the QPainter::drawText function (which expects the top + left point of the text rect), according to the position \a pos, the text bounding box \a rect and + the requested \a positionAlignment. + + For example, if \a positionAlignment is Qt::AlignLeft | Qt::AlignBottom the returned point + will be shifted upward by the height of \a rect, starting from \a pos. So if the text is finally + drawn at that point, the lower left corner of the resulting text rect is at \a pos. +*/ +QPointF QCPItemText::getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const +{ + if (positionAlignment == 0 || positionAlignment == (Qt::AlignLeft|Qt::AlignTop)) + return pos; + + QPointF result = pos; // start at top left + if (positionAlignment.testFlag(Qt::AlignHCenter)) + result.rx() -= rect.width()/2.0; + else if (positionAlignment.testFlag(Qt::AlignRight)) + result.rx() -= rect.width(); + if (positionAlignment.testFlag(Qt::AlignVCenter)) + result.ry() -= rect.height()/2.0; + else if (positionAlignment.testFlag(Qt::AlignBottom)) + result.ry() -= rect.height(); + return result; +} + +/*! \internal + + Returns the font that should be used for drawing text. Returns mFont when the item is not selected + and mSelectedFont when it is. +*/ +QFont QCPItemText::mainFont() const +{ + return mSelected ? mSelectedFont : mFont; +} + +/*! \internal + + Returns the color that should be used for drawing text. Returns mColor when the item is not + selected and mSelectedColor when it is. +*/ +QColor QCPItemText::mainColor() const +{ + return mSelected ? mSelectedColor : mColor; +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected + and mSelectedPen when it is. +*/ +QPen QCPItemText::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + +/*! \internal + + Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item + is not selected and mSelectedBrush when it is. +*/ +QBrush QCPItemText::mainBrush() const +{ + return mSelected ? mSelectedBrush : mBrush; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemEllipse +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemEllipse + \brief An ellipse + + \image html QCPItemEllipse.png "Ellipse example. Blue dotted circles are anchors, solid blue discs are positions." + + It has two positions, \a topLeft and \a bottomRight, which define the rect the ellipse will be drawn in. +*/ + +/*! + Creates an ellipse item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemEllipse::QCPItemEllipse(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + topLeft(createPosition("topLeft")), + bottomRight(createPosition("bottomRight")), + topLeftRim(createAnchor("topLeftRim", aiTopLeftRim)), + top(createAnchor("top", aiTop)), + topRightRim(createAnchor("topRightRim", aiTopRightRim)), + right(createAnchor("right", aiRight)), + bottomRightRim(createAnchor("bottomRightRim", aiBottomRightRim)), + bottom(createAnchor("bottom", aiBottom)), + bottomLeftRim(createAnchor("bottomLeftRim", aiBottomLeftRim)), + left(createAnchor("left", aiLeft)), + center(createAnchor("center", aiCenter)) +{ + topLeft->setCoords(0, 1); + bottomRight->setCoords(1, 0); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); +} + +QCPItemEllipse::~QCPItemEllipse() +{ +} + +/*! + Sets the pen that will be used to draw the line of the ellipse + + \see setSelectedPen, setBrush +*/ +void QCPItemEllipse::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw the line of the ellipse when selected + + \see setPen, setSelected +*/ +void QCPItemEllipse::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + Sets the brush that will be used to fill the ellipse. To disable filling, set \a brush to + Qt::NoBrush. + + \see setSelectedBrush, setPen +*/ +void QCPItemEllipse::setBrush(const QBrush &brush) +{ + mBrush = brush; +} + +/*! + Sets the brush that will be used to fill the ellipse when selected. To disable filling, set \a + brush to Qt::NoBrush. + + \see setBrush +*/ +void QCPItemEllipse::setSelectedBrush(const QBrush &brush) +{ + mSelectedBrush = brush; +} + +/* inherits documentation from base class */ +double QCPItemEllipse::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + double result = -1; + QPointF p1 = topLeft->pixelPoint(); + QPointF p2 = bottomRight->pixelPoint(); + QPointF center((p1+p2)/2.0); + double a = qAbs(p1.x()-p2.x())/2.0; + double b = qAbs(p1.y()-p2.y())/2.0; + double x = pos.x()-center.x(); + double y = pos.y()-center.y(); + + // distance to border: + double c = 1.0/qSqrt(x*x/(a*a)+y*y/(b*b)); + result = qAbs(c-1)*qSqrt(x*x+y*y); + // filled ellipse, allow click inside to count as hit: + if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) + { + if (x*x/(a*a) + y*y/(b*b) <= 1) + result = mParentPlot->selectionTolerance()*0.99; + } + return result; +} + +/* inherits documentation from base class */ +void QCPItemEllipse::draw(QCPPainter *painter) +{ + QPointF p1 = topLeft->pixelPoint(); + QPointF p2 = bottomRight->pixelPoint(); + if (p1.toPoint() == p2.toPoint()) + return; + QRectF ellipseRect = QRectF(p1, p2).normalized(); + QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); + if (ellipseRect.intersects(clip)) // only draw if bounding rect of ellipse is visible in cliprect + { + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); +#ifdef __EXCEPTIONS + try // drawEllipse sometimes throws exceptions if ellipse is too big + { +#endif + painter->drawEllipse(ellipseRect); +#ifdef __EXCEPTIONS + } catch (...) + { + qDebug() << Q_FUNC_INFO << "Item too large for memory, setting invisible"; + setVisible(false); + } +#endif + } +} + +/* inherits documentation from base class */ +QPointF QCPItemEllipse::anchorPixelPoint(int anchorId) const +{ + QRectF rect = QRectF(topLeft->pixelPoint(), bottomRight->pixelPoint()); + switch (anchorId) + { + case aiTopLeftRim: return rect.center()+(rect.topLeft()-rect.center())*1/qSqrt(2); + case aiTop: return (rect.topLeft()+rect.topRight())*0.5; + case aiTopRightRim: return rect.center()+(rect.topRight()-rect.center())*1/qSqrt(2); + case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; + case aiBottomRightRim: return rect.center()+(rect.bottomRight()-rect.center())*1/qSqrt(2); + case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; + case aiBottomLeftRim: return rect.center()+(rect.bottomLeft()-rect.center())*1/qSqrt(2); + case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5; + case aiCenter: return (rect.topLeft()+rect.bottomRight())*0.5; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected + and mSelectedPen when it is. +*/ +QPen QCPItemEllipse::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + +/*! \internal + + Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item + is not selected and mSelectedBrush when it is. +*/ +QBrush QCPItemEllipse::mainBrush() const +{ + return mSelected ? mSelectedBrush : mBrush; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemPixmap +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemPixmap + \brief An arbitrary pixmap + + \image html QCPItemPixmap.png "Pixmap example. Blue dotted circles are anchors, solid blue discs are positions." + + It has two positions, \a topLeft and \a bottomRight, which define the rectangle the pixmap will + be drawn in. Depending on the scale setting (\ref setScaled), the pixmap will be either scaled to + fit the rectangle or be drawn aligned to the topLeft position. + + If scaling is enabled and \a topLeft is further to the bottom/right than \a bottomRight (as shown + on the right side of the example image), the pixmap will be flipped in the respective + orientations. +*/ + +/*! + Creates a rectangle item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemPixmap::QCPItemPixmap(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + topLeft(createPosition("topLeft")), + bottomRight(createPosition("bottomRight")), + top(createAnchor("top", aiTop)), + topRight(createAnchor("topRight", aiTopRight)), + right(createAnchor("right", aiRight)), + bottom(createAnchor("bottom", aiBottom)), + bottomLeft(createAnchor("bottomLeft", aiBottomLeft)), + left(createAnchor("left", aiLeft)) +{ + topLeft->setCoords(0, 1); + bottomRight->setCoords(1, 0); + + setPen(Qt::NoPen); + setSelectedPen(QPen(Qt::blue)); + setScaled(false, Qt::KeepAspectRatio); +} + +QCPItemPixmap::~QCPItemPixmap() +{ +} + +/*! + Sets the pixmap that will be displayed. +*/ +void QCPItemPixmap::setPixmap(const QPixmap &pixmap) +{ + mPixmap = pixmap; + if (mPixmap.isNull()) + qDebug() << Q_FUNC_INFO << "pixmap is null"; +} + +/*! + Sets whether the pixmap will be scaled to fit the rectangle defined by the \a topLeft and \a + bottomRight positions. +*/ +void QCPItemPixmap::setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode) +{ + mScaled = scaled; + mAspectRatioMode = aspectRatioMode; + updateScaledPixmap(); +} + +/*! + Sets the pen that will be used to draw a border around the pixmap. + + \see setSelectedPen, setBrush +*/ +void QCPItemPixmap::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw a border around the pixmap when selected + + \see setPen, setSelected +*/ +void QCPItemPixmap::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/* inherits documentation from base class */ +double QCPItemPixmap::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + return rectSelectTest(getFinalRect(), pos, true); +} + +/* inherits documentation from base class */ +void QCPItemPixmap::draw(QCPPainter *painter) +{ + bool flipHorz = false; + bool flipVert = false; + QRect rect = getFinalRect(&flipHorz, &flipVert); + double clipPad = mainPen().style() == Qt::NoPen ? 0 : mainPen().widthF(); + QRect boundingRect = rect.adjusted(-clipPad, -clipPad, clipPad, clipPad); + if (boundingRect.intersects(clipRect())) + { + updateScaledPixmap(rect, flipHorz, flipVert); + painter->drawPixmap(rect.topLeft(), mScaled ? mScaledPixmap : mPixmap); + QPen pen = mainPen(); + if (pen.style() != Qt::NoPen) + { + painter->setPen(pen); + painter->setBrush(Qt::NoBrush); + painter->drawRect(rect); + } + } +} + +/* inherits documentation from base class */ +QPointF QCPItemPixmap::anchorPixelPoint(int anchorId) const +{ + bool flipHorz; + bool flipVert; + QRect rect = getFinalRect(&flipHorz, &flipVert); + // we actually want denormal rects (negative width/height) here, so restore + // the flipped state: + if (flipHorz) + rect.adjust(rect.width(), 0, -rect.width(), 0); + if (flipVert) + rect.adjust(0, rect.height(), 0, -rect.height()); + + switch (anchorId) + { + case aiTop: return (rect.topLeft()+rect.topRight())*0.5; + case aiTopRight: return rect.topRight(); + case aiRight: return (rect.topRight()+rect.bottomRight())*0.5; + case aiBottom: return (rect.bottomLeft()+rect.bottomRight())*0.5; + case aiBottomLeft: return rect.bottomLeft(); + case aiLeft: return (rect.topLeft()+rect.bottomLeft())*0.5;; + } + + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); +} + +/*! \internal + + Creates the buffered scaled image (\a mScaledPixmap) to fit the specified \a finalRect. The + parameters \a flipHorz and \a flipVert control whether the resulting image shall be flipped + horizontally or vertically. (This is used when \a topLeft is further to the bottom/right than \a + bottomRight.) + + This function only creates the scaled pixmap when the buffered pixmap has a different size than + the expected result, so calling this function repeatedly, e.g. in the \ref draw function, does + not cause expensive rescaling every time. + + If scaling is disabled, sets mScaledPixmap to a null QPixmap. +*/ +void QCPItemPixmap::updateScaledPixmap(QRect finalRect, bool flipHorz, bool flipVert) +{ + if (mPixmap.isNull()) + return; + + if (mScaled) + { + if (finalRect.isNull()) + finalRect = getFinalRect(&flipHorz, &flipVert); + if (finalRect.size() != mScaledPixmap.size()) + { + mScaledPixmap = mPixmap.scaled(finalRect.size(), mAspectRatioMode, Qt::SmoothTransformation); + if (flipHorz || flipVert) + mScaledPixmap = QPixmap::fromImage(mScaledPixmap.toImage().mirrored(flipHorz, flipVert)); + } + } else if (!mScaledPixmap.isNull()) + mScaledPixmap = QPixmap(); +} + +/*! \internal + + Returns the final (tight) rect the pixmap is drawn in, depending on the current item positions + and scaling settings. + + The output parameters \a flippedHorz and \a flippedVert return whether the pixmap should be drawn + flipped horizontally or vertically in the returned rect. (The returned rect itself is always + normalized, i.e. the top left corner of the rect is actually further to the top/left than the + bottom right corner). This is the case when the item position \a topLeft is further to the + bottom/right than \a bottomRight. + + If scaling is disabled, returns a rect with size of the original pixmap and the top left corner + aligned with the item position \a topLeft. The position \a bottomRight is ignored. +*/ +QRect QCPItemPixmap::getFinalRect(bool *flippedHorz, bool *flippedVert) const +{ + QRect result; + bool flipHorz = false; + bool flipVert = false; + QPoint p1 = topLeft->pixelPoint().toPoint(); + QPoint p2 = bottomRight->pixelPoint().toPoint(); + if (p1 == p2) + return QRect(p1, QSize(0, 0)); + if (mScaled) + { + QSize newSize = QSize(p2.x()-p1.x(), p2.y()-p1.y()); + QPoint topLeft = p1; + if (newSize.width() < 0) + { + flipHorz = true; + newSize.rwidth() *= -1; + topLeft.setX(p2.x()); + } + if (newSize.height() < 0) + { + flipVert = true; + newSize.rheight() *= -1; + topLeft.setY(p2.y()); + } + QSize scaledSize = mPixmap.size(); + scaledSize.scale(newSize, mAspectRatioMode); + result = QRect(topLeft, scaledSize); + } else + { + result = QRect(p1, mPixmap.size()); + } + if (flippedHorz) + *flippedHorz = flipHorz; + if (flippedVert) + *flippedVert = flipVert; + return result; +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected + and mSelectedPen when it is. +*/ +QPen QCPItemPixmap::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemTracer +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemTracer + \brief Item that sticks to QCPGraph data points + + \image html QCPItemTracer.png "Tracer example. Blue dotted circles are anchors, solid blue discs are positions." + + The tracer can be connected with a QCPGraph via \ref setGraph. Then it will automatically adopt + the coordinate axes of the graph and update its \a position to be on the graph's data. This means + the key stays controllable via \ref setGraphKey, but the value will follow the graph data. If a + QCPGraph is connected, note that setting the coordinates of the tracer item directly via \a + position will have no effect because they will be overriden in the next redraw (this is when the + coordinate update happens). + + If the specified key in \ref setGraphKey is outside the key bounds of the graph, the tracer will + stay at the corresponding end of the graph. + + With \ref setInterpolating you may specify whether the tracer may only stay exactly on data + points or whether it interpolates data points linearly, if given a key that lies between two data + points of the graph. + + The tracer has different visual styles, see \ref setStyle. It is also possible to make the tracer + have no own visual appearance (set the style to \ref tsNone), and just connect other item + positions to the tracer \a position (used as an anchor) via \ref + QCPItemPosition::setParentAnchor. + + \note The tracer position is only automatically updated upon redraws. So when the data of the + graph changes and immediately afterwards (without a redraw) the a position coordinates of the + tracer are retrieved, they will not reflect the updated data of the graph. In this case \ref + updatePosition must be called manually, prior to reading the tracer coordinates. +*/ + +/*! + Creates a tracer item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemTracer::QCPItemTracer(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + position(createPosition("position")), + mGraph(0) +{ + position->setCoords(0, 0); + + setBrush(Qt::NoBrush); + setSelectedBrush(Qt::NoBrush); + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); + setStyle(tsCrosshair); + setSize(6); + setInterpolating(false); + setGraphKey(0); +} + +QCPItemTracer::~QCPItemTracer() +{ +} + +/*! + Sets the pen that will be used to draw the line of the tracer + + \see setSelectedPen, setBrush +*/ +void QCPItemTracer::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw the line of the tracer when selected + + \see setPen, setSelected +*/ +void QCPItemTracer::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + Sets the brush that will be used to draw any fills of the tracer + + \see setSelectedBrush, setPen +*/ +void QCPItemTracer::setBrush(const QBrush &brush) +{ + mBrush = brush; +} + +/*! + Sets the brush that will be used to draw any fills of the tracer, when selected. + + \see setBrush, setSelected +*/ +void QCPItemTracer::setSelectedBrush(const QBrush &brush) +{ + mSelectedBrush = brush; +} + +/*! + Sets the size of the tracer in pixels, if the style supports setting a size (e.g. \ref tsSquare + does, \ref tsCrosshair does not). +*/ +void QCPItemTracer::setSize(double size) +{ + mSize = size; +} + +/*! + Sets the style/visual appearance of the tracer. + + If you only want to use the tracer \a position as an anchor for other items, set \a style to + \ref tsNone. +*/ +void QCPItemTracer::setStyle(QCPItemTracer::TracerStyle style) +{ + mStyle = style; +} + +/*! + Sets the QCPGraph this tracer sticks to. The tracer \a position will be set to type + QCPItemPosition::ptPlotCoords and the axes will be set to the axes of \a graph. + + To free the tracer from any graph, set \a graph to 0. The tracer \a position can then be placed + freely like any other item position. This is the state the tracer will assume when its graph gets + deleted while still attached to it. + + \see setGraphKey +*/ +void QCPItemTracer::setGraph(QCPGraph *graph) +{ + if (graph) + { + if (graph->parentPlot() == mParentPlot) + { + position->setType(QCPItemPosition::ptPlotCoords); + position->setAxes(graph->keyAxis(), graph->valueAxis()); + mGraph = graph; + updatePosition(); + } else + qDebug() << Q_FUNC_INFO << "graph isn't in same QCustomPlot instance as this item"; + } else + { + mGraph = 0; + } +} + +/*! + Sets the key of the graph's data point the tracer will be positioned at. This is the only free + coordinate of a tracer when attached to a graph. + + Depending on \ref setInterpolating, the tracer will be either positioned on the data point + closest to \a key, or will stay exactly at \a key and interpolate the value linearly. + + \see setGraph, setInterpolating +*/ +void QCPItemTracer::setGraphKey(double key) +{ + mGraphKey = key; +} + +/*! + Sets whether the value of the graph's data points shall be interpolated, when positioning the + tracer. + + If \a enabled is set to false and a key is given with \ref setGraphKey, the tracer is placed on + the data point of the graph which is closest to the key, but which is not necessarily exactly + there. If \a enabled is true, the tracer will be positioned exactly at the specified key, and + the appropriate value will be interpolated from the graph's data points linearly. + + \see setGraph, setGraphKey +*/ +void QCPItemTracer::setInterpolating(bool enabled) +{ + mInterpolating = enabled; +} + +/* inherits documentation from base class */ +double QCPItemTracer::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + QPointF center(position->pixelPoint()); + double w = mSize/2.0; + QRect clip = clipRect(); + switch (mStyle) + { + case tsNone: return -1; + case tsPlus: + { + if (clipRect().intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) + return qSqrt(qMin(distSqrToLine(center+QPointF(-w, 0), center+QPointF(w, 0), pos), + distSqrToLine(center+QPointF(0, -w), center+QPointF(0, w), pos))); + break; + } + case tsCrosshair: + { + return qSqrt(qMin(distSqrToLine(QPointF(clip.left(), center.y()), QPointF(clip.right(), center.y()), pos), + distSqrToLine(QPointF(center.x(), clip.top()), QPointF(center.x(), clip.bottom()), pos))); + } + case tsCircle: + { + if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) + { + // distance to border: + double centerDist = QVector2D(center-pos).length(); + double circleLine = w; + double result = qAbs(centerDist-circleLine); + // filled ellipse, allow click inside to count as hit: + if (result > mParentPlot->selectionTolerance()*0.99 && mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0) + { + if (centerDist <= circleLine) + result = mParentPlot->selectionTolerance()*0.99; + } + return result; + } + break; + } + case tsSquare: + { + if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) + { + QRectF rect = QRectF(center-QPointF(w, w), center+QPointF(w, w)); + bool filledRect = mBrush.style() != Qt::NoBrush && mBrush.color().alpha() != 0; + return rectSelectTest(rect, pos, filledRect); + } + break; + } + } + return -1; +} + +/* inherits documentation from base class */ +void QCPItemTracer::draw(QCPPainter *painter) +{ + updatePosition(); + if (mStyle == tsNone) + return; + + painter->setPen(mainPen()); + painter->setBrush(mainBrush()); + QPointF center(position->pixelPoint()); + double w = mSize/2.0; + QRect clip = clipRect(); + switch (mStyle) + { + case tsNone: return; + case tsPlus: + { + if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) + { + painter->drawLine(QLineF(center+QPointF(-w, 0), center+QPointF(w, 0))); + painter->drawLine(QLineF(center+QPointF(0, -w), center+QPointF(0, w))); + } + break; + } + case tsCrosshair: + { + if (center.y() > clip.top() && center.y() < clip.bottom()) + painter->drawLine(QLineF(clip.left(), center.y(), clip.right(), center.y())); + if (center.x() > clip.left() && center.x() < clip.right()) + painter->drawLine(QLineF(center.x(), clip.top(), center.x(), clip.bottom())); + break; + } + case tsCircle: + { + if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) + painter->drawEllipse(center, w, w); + break; + } + case tsSquare: + { + if (clip.intersects(QRectF(center-QPointF(w, w), center+QPointF(w, w)).toRect())) + painter->drawRect(QRectF(center-QPointF(w, w), center+QPointF(w, w))); + break; + } + } +} + +/*! + If the tracer is connected with a graph (\ref setGraph), this function updates the tracer's \a + position to reside on the graph data, depending on the configured key (\ref setGraphKey). + + It is called automatically on every redraw and normally doesn't need to be called manually. One + exception is when you want to read the tracer coordinates via \a position and are not sure that + the graph's data (or the tracer key with \ref setGraphKey) hasn't changed since the last redraw. + In that situation, call this function before accessing \a position, to make sure you don't get + out-of-date coordinates. + + If there is no graph set on this tracer, this function does nothing. +*/ +void QCPItemTracer::updatePosition() +{ + if (mGraph) + { + if (mParentPlot->hasPlottable(mGraph)) + { + if (mGraph->data()->size() > 1) + { + QCPDataMap::const_iterator first = mGraph->data()->constBegin(); + QCPDataMap::const_iterator last = mGraph->data()->constEnd()-1; + if (mGraphKey < first.key()) + position->setCoords(first.key(), first.value().value); + else if (mGraphKey > last.key()) + position->setCoords(last.key(), last.value().value); + else + { + QCPDataMap::const_iterator it = mGraph->data()->lowerBound(mGraphKey); + if (it != first) // mGraphKey is somewhere between iterators + { + QCPDataMap::const_iterator prevIt = it-1; + if (mInterpolating) + { + // interpolate between iterators around mGraphKey: + double slope = 0; + if (!qFuzzyCompare((double)it.key(), (double)prevIt.key())) + slope = (it.value().value-prevIt.value().value)/(it.key()-prevIt.key()); + position->setCoords(mGraphKey, (mGraphKey-prevIt.key())*slope+prevIt.value().value); + } else + { + // find iterator with key closest to mGraphKey: + if (mGraphKey < (prevIt.key()+it.key())*0.5) + it = prevIt; + position->setCoords(it.key(), it.value().value); + } + } else // mGraphKey is exactly on first iterator + position->setCoords(it.key(), it.value().value); + } + } else if (mGraph->data()->size() == 1) + { + QCPDataMap::const_iterator it = mGraph->data()->constBegin(); + position->setCoords(it.key(), it.value().value); + } else + qDebug() << Q_FUNC_INFO << "graph has no data"; + } else + qDebug() << Q_FUNC_INFO << "graph not contained in QCustomPlot instance (anymore)"; + } +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the item is not selected + and mSelectedPen when it is. +*/ +QPen QCPItemTracer::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + +/*! \internal + + Returns the brush that should be used for drawing fills of the item. Returns mBrush when the item + is not selected and mSelectedBrush when it is. +*/ +QBrush QCPItemTracer::mainBrush() const +{ + return mSelected ? mSelectedBrush : mBrush; +} + + +//////////////////////////////////////////////////////////////////////////////////////////////////// +//////////////////// QCPItemBracket +//////////////////////////////////////////////////////////////////////////////////////////////////// + +/*! \class QCPItemBracket + \brief A bracket for referencing/highlighting certain parts in the plot. + + \image html QCPItemBracket.png "Bracket example. Blue dotted circles are anchors, solid blue discs are positions." + + It has two positions, \a left and \a right, which define the span of the bracket. If \a left is + actually farther to the left than \a right, the bracket is opened to the bottom, as shown in the + example image. + + The bracket supports multiple styles via \ref setStyle. The length, i.e. how far the bracket + stretches away from the embraced span, can be controlled with \ref setLength. + + \image html QCPItemBracket-length.png +
Demonstrating the effect of different values for \ref setLength, for styles \ref + bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
+ + It provides an anchor \a center, to allow connection of other items, e.g. an arrow (QCPItemLine + or QCPItemCurve) or a text label (QCPItemText), to the bracket. +*/ + +/*! + Creates a bracket item and sets default values. + + The constructed item can be added to the plot with QCustomPlot::addItem. +*/ +QCPItemBracket::QCPItemBracket(QCustomPlot *parentPlot) : + QCPAbstractItem(parentPlot), + left(createPosition("left")), + right(createPosition("right")), + center(createAnchor("center", aiCenter)) +{ + left->setCoords(0, 0); + right->setCoords(1, 1); + + setPen(QPen(Qt::black)); + setSelectedPen(QPen(Qt::blue, 2)); + setLength(8); + setStyle(bsCalligraphic); +} + +QCPItemBracket::~QCPItemBracket() +{ +} + +/*! + Sets the pen that will be used to draw the bracket. + + Note that when the style is \ref bsCalligraphic, only the color will be taken from the pen, the + stroke and width are ignored. To change the apparent stroke width of a calligraphic bracket, use + \ref setLength, which has a similar effect. + + \see setSelectedPen +*/ +void QCPItemBracket::setPen(const QPen &pen) +{ + mPen = pen; +} + +/*! + Sets the pen that will be used to draw the bracket when selected + + \see setPen, setSelected +*/ +void QCPItemBracket::setSelectedPen(const QPen &pen) +{ + mSelectedPen = pen; +} + +/*! + Sets the \a length in pixels how far the bracket extends in the direction towards the embraced + span of the bracket (i.e. perpendicular to the left-right-direction) + + \image html QCPItemBracket-length.png +
Demonstrating the effect of different values for \ref setLength, for styles \ref + bsCalligraphic and \ref bsSquare. Anchors and positions are displayed for reference.
+*/ +void QCPItemBracket::setLength(double length) +{ + mLength = length; +} + +/*! + Sets the style of the bracket, i.e. the shape/visual appearance. + + \see setPen +*/ +void QCPItemBracket::setStyle(QCPItemBracket::BracketStyle style) +{ + mStyle = style; +} + +/* inherits documentation from base class */ +double QCPItemBracket::selectTest(const QPointF &pos, bool onlySelectable, QVariant *details) const +{ + Q_UNUSED(details) + if (onlySelectable && !mSelectable) + return -1; + + QVector2D leftVec(left->pixelPoint()); + QVector2D rightVec(right->pixelPoint()); + if (leftVec.toPoint() == rightVec.toPoint()) + return -1; + + QVector2D widthVec = (rightVec-leftVec)*0.5f; + QVector2D lengthVec(-widthVec.y(), widthVec.x()); + lengthVec = lengthVec.normalized()*mLength; + QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; + + return qSqrt(distSqrToLine((centerVec-widthVec).toPointF(), (centerVec+widthVec).toPointF(), pos)); +} + +/* inherits documentation from base class */ +void QCPItemBracket::draw(QCPPainter *painter) +{ + QVector2D leftVec(left->pixelPoint()); + QVector2D rightVec(right->pixelPoint()); + if (leftVec.toPoint() == rightVec.toPoint()) + return; + + QVector2D widthVec = (rightVec-leftVec)*0.5f; + QVector2D lengthVec(-widthVec.y(), widthVec.x()); + lengthVec = lengthVec.normalized()*mLength; + QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; + + QPolygon boundingPoly; + boundingPoly << leftVec.toPoint() << rightVec.toPoint() + << (rightVec-lengthVec).toPoint() << (leftVec-lengthVec).toPoint(); + QRect clip = clipRect().adjusted(-mainPen().widthF(), -mainPen().widthF(), mainPen().widthF(), mainPen().widthF()); + if (clip.intersects(boundingPoly.boundingRect())) + { + painter->setPen(mainPen()); + switch (mStyle) + { + case bsSquare: + { + painter->drawLine((centerVec+widthVec).toPointF(), (centerVec-widthVec).toPointF()); + painter->drawLine((centerVec+widthVec).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); + painter->drawLine((centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); + break; + } + case bsRound: + { + painter->setBrush(Qt::NoBrush); + QPainterPath path; + path.moveTo((centerVec+widthVec+lengthVec).toPointF()); + path.cubicTo((centerVec+widthVec).toPointF(), (centerVec+widthVec).toPointF(), centerVec.toPointF()); + path.cubicTo((centerVec-widthVec).toPointF(), (centerVec-widthVec).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); + painter->drawPath(path); + break; + } + case bsCurly: + { + painter->setBrush(Qt::NoBrush); + QPainterPath path; + path.moveTo((centerVec+widthVec+lengthVec).toPointF()); + path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+lengthVec).toPointF(), centerVec.toPointF()); + path.cubicTo((centerVec-0.4f*widthVec+lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); + painter->drawPath(path); + break; + } + case bsCalligraphic: + { + painter->setPen(Qt::NoPen); + painter->setBrush(QBrush(mainPen().color())); + QPainterPath path; + path.moveTo((centerVec+widthVec+lengthVec).toPointF()); + + path.cubicTo((centerVec+widthVec-lengthVec*0.8f).toPointF(), (centerVec+0.4f*widthVec+0.8f*lengthVec).toPointF(), centerVec.toPointF()); + path.cubicTo((centerVec-0.4f*widthVec+0.8f*lengthVec).toPointF(), (centerVec-widthVec-lengthVec*0.8f).toPointF(), (centerVec-widthVec+lengthVec).toPointF()); + + path.cubicTo((centerVec-widthVec-lengthVec*0.5f).toPointF(), (centerVec-0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+lengthVec*0.2f).toPointF()); + path.cubicTo((centerVec+0.2f*widthVec+1.2f*lengthVec).toPointF(), (centerVec+widthVec-lengthVec*0.5f).toPointF(), (centerVec+widthVec+lengthVec).toPointF()); + + painter->drawPath(path); + break; + } + } + } +} + +/* inherits documentation from base class */ +QPointF QCPItemBracket::anchorPixelPoint(int anchorId) const +{ + QVector2D leftVec(left->pixelPoint()); + QVector2D rightVec(right->pixelPoint()); + if (leftVec.toPoint() == rightVec.toPoint()) + return leftVec.toPointF(); + + QVector2D widthVec = (rightVec-leftVec)*0.5f; + QVector2D lengthVec(-widthVec.y(), widthVec.x()); + lengthVec = lengthVec.normalized()*mLength; + QVector2D centerVec = (rightVec+leftVec)*0.5f-lengthVec; + + switch (anchorId) + { + case aiCenter: + return centerVec.toPointF(); + } + qDebug() << Q_FUNC_INFO << "invalid anchorId" << anchorId; + return QPointF(); +} + +/*! \internal + + Returns the pen that should be used for drawing lines. Returns mPen when the + item is not selected and mSelectedPen when it is. +*/ +QPen QCPItemBracket::mainPen() const +{ + return mSelected ? mSelectedPen : mPen; +} + diff --git a/src/qt/qcustomplot.h b/src/qt/qcustomplot.h new file mode 100644 index 0000000..338f43f --- /dev/null +++ b/src/qt/qcustomplot.h @@ -0,0 +1,3764 @@ +/*************************************************************************** +** ** +** QCustomPlot, an easy to use, modern plotting widget for Qt ** +** Copyright (C) 2011, 2012, 2013, 2014 Emanuel Eichhammer ** +** ** +** This program is free software: you can redistribute it and/or modify ** +** it under the terms of the GNU General Public License as published by ** +** the Free Software Foundation, either version 3 of the License, or ** +** (at your option) any later version. ** +** ** +** This program is distributed in the hope that it will be useful, ** +** but WITHOUT ANY WARRANTY; without even the implied warranty of ** +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** +** GNU General Public License for more details. ** +** ** +** You should have received a copy of the GNU General Public License ** +** along with this program. If not, see http://www.gnu.org/licenses/. ** +** ** +**************************************************************************** +** Author: Emanuel Eichhammer ** +** Website/Contact: http://www.qcustomplot.com/ ** +** Date: 11.10.14 ** +** Version: 1.3.0-beta ** +****************************************************************************/ + +#ifndef QCUSTOMPLOT_H +#define QCUSTOMPLOT_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if QT_VERSION < QT_VERSION_CHECK(5, 0, 0) +# include +# include +# include +#else +# include +# include +#endif + +class QCPPainter; +class QCustomPlot; +class QCPLayerable; +class QCPLayoutElement; +class QCPLayout; +class QCPAxis; +class QCPAxisRect; +class QCPAxisPainterPrivate; +class QCPAbstractPlottable; +class QCPGraph; +class QCPAbstractItem; +class QCPItemPosition; +class QCPLayer; +class QCPPlotTitle; +class QCPLegend; +class QCPAbstractLegendItem; +class QCPColorMap; +class QCPColorScale; +class QCPBars; + + +/*! \file */ + + +// decl definitions for shared library compilation/usage: +#if defined(QCUSTOMPLOT_COMPILE_LIBRARY) +# define QCP_LIB_DECL Q_DECL_EXPORT +#elif defined(QCUSTOMPLOT_USE_LIBRARY) +# define QCP_LIB_DECL Q_DECL_IMPORT +#else +# define QCP_LIB_DECL +#endif + +/*! + The QCP Namespace contains general enums and QFlags used throughout the QCustomPlot library +*/ +namespace QCP +{ +/*! + Defines the sides of a rectangular entity to which margins can be applied. + + \see QCPLayoutElement::setAutoMargins, QCPAxisRect::setAutoMargins +*/ +enum MarginSide { msLeft = 0x01 ///< 0x01 left margin + ,msRight = 0x02 ///< 0x02 right margin + ,msTop = 0x04 ///< 0x04 top margin + ,msBottom = 0x08 ///< 0x08 bottom margin + ,msAll = 0xFF ///< 0xFF all margins + ,msNone = 0x00 ///< 0x00 no margin + }; +Q_DECLARE_FLAGS(MarginSides, MarginSide) + +/*! + Defines what objects of a plot can be forcibly drawn antialiased/not antialiased. If an object is + neither forcibly drawn antialiased nor forcibly drawn not antialiased, it is up to the respective + element how it is drawn. Typically it provides a \a setAntialiased function for this. + + \c AntialiasedElements is a flag of or-combined elements of this enum type. + + \see QCustomPlot::setAntialiasedElements, QCustomPlot::setNotAntialiasedElements +*/ +enum AntialiasedElement { aeAxes = 0x0001 ///< 0x0001 Axis base line and tick marks + ,aeGrid = 0x0002 ///< 0x0002 Grid lines + ,aeSubGrid = 0x0004 ///< 0x0004 Sub grid lines + ,aeLegend = 0x0008 ///< 0x0008 Legend box + ,aeLegendItems = 0x0010 ///< 0x0010 Legend items + ,aePlottables = 0x0020 ///< 0x0020 Main lines of plottables (excluding error bars, see element \ref aeErrorBars) + ,aeItems = 0x0040 ///< 0x0040 Main lines of items + ,aeScatters = 0x0080 ///< 0x0080 Scatter symbols of plottables (excluding scatter symbols of type ssPixmap) + ,aeErrorBars = 0x0100 ///< 0x0100 Error bars + ,aeFills = 0x0200 ///< 0x0200 Borders of fills (e.g. under or between graphs) + ,aeZeroLine = 0x0400 ///< 0x0400 Zero-lines, see \ref QCPGrid::setZeroLinePen + ,aeAll = 0xFFFF ///< 0xFFFF All elements + ,aeNone = 0x0000 ///< 0x0000 No elements + }; +Q_DECLARE_FLAGS(AntialiasedElements, AntialiasedElement) + +/*! + Defines plotting hints that control various aspects of the quality and speed of plotting. + + \see QCustomPlot::setPlottingHints +*/ +enum PlottingHint { phNone = 0x000 ///< 0x000 No hints are set + ,phFastPolylines = 0x001 ///< 0x001 Graph/Curve lines are drawn with a faster method. This reduces the quality + ///< especially of the line segment joins. (Only relevant for solid line pens.) + ,phForceRepaint = 0x002 ///< 0x002 causes an immediate repaint() instead of a soft update() when QCustomPlot::replot() is called with parameter \ref QCustomPlot::rpHint. + ///< This is set by default to prevent the plot from freezing on fast consecutive replots (e.g. user drags ranges with mouse). + ,phCacheLabels = 0x004 ///< 0x004 axis (tick) labels will be cached as pixmaps, increasing replot performance. + }; +Q_DECLARE_FLAGS(PlottingHints, PlottingHint) + +/*! + Defines the mouse interactions possible with QCustomPlot. + + \c Interactions is a flag of or-combined elements of this enum type. + + \see QCustomPlot::setInteractions +*/ +enum Interaction { iRangeDrag = 0x001 ///< 0x001 Axis ranges are draggable (see \ref QCPAxisRect::setRangeDrag, \ref QCPAxisRect::setRangeDragAxes) + ,iRangeZoom = 0x002 ///< 0x002 Axis ranges are zoomable with the mouse wheel (see \ref QCPAxisRect::setRangeZoom, \ref QCPAxisRect::setRangeZoomAxes) + ,iMultiSelect = 0x004 ///< 0x004 The user can select multiple objects by holding the modifier set by \ref QCustomPlot::setMultiSelectModifier while clicking + ,iSelectPlottables = 0x008 ///< 0x008 Plottables are selectable (e.g. graphs, curves, bars,... see QCPAbstractPlottable) + ,iSelectAxes = 0x010 ///< 0x010 Axes are selectable (or parts of them, see QCPAxis::setSelectableParts) + ,iSelectLegend = 0x020 ///< 0x020 Legends are selectable (or their child items, see QCPLegend::setSelectableParts) + ,iSelectItems = 0x040 ///< 0x040 Items are selectable (Rectangles, Arrows, Textitems, etc. see \ref QCPAbstractItem) + ,iSelectOther = 0x080 ///< 0x080 All other objects are selectable (e.g. your own derived layerables, the plot title,...) + }; +Q_DECLARE_FLAGS(Interactions, Interaction) + +/*! \internal + + Returns whether the specified \a value is considered an invalid data value for plottables (i.e. + is \e nan or \e +/-inf). This function is used to check data validity upon replots, when the + compiler flag \c QCUSTOMPLOT_CHECK_DATA is set. +*/ +inline bool isInvalidData(double value) +{ + return qIsNaN(value) || qIsInf(value); +} + +/*! \internal + \overload + + Checks two arguments instead of one. +*/ +inline bool isInvalidData(double value1, double value2) +{ + return isInvalidData(value1) || isInvalidData(value2); +} + +/*! \internal + + Sets the specified \a side of \a margins to \a value + + \see getMarginValue +*/ +inline void setMarginValue(QMargins &margins, QCP::MarginSide side, int value) +{ + switch (side) + { + case QCP::msLeft: margins.setLeft(value); break; + case QCP::msRight: margins.setRight(value); break; + case QCP::msTop: margins.setTop(value); break; + case QCP::msBottom: margins.setBottom(value); break; + case QCP::msAll: margins = QMargins(value, value, value, value); break; + default: break; + } +} + +/*! \internal + + Returns the value of the specified \a side of \a margins. If \a side is \ref QCP::msNone or + \ref QCP::msAll, returns 0. + + \see setMarginValue +*/ +inline int getMarginValue(const QMargins &margins, QCP::MarginSide side) +{ + switch (side) + { + case QCP::msLeft: return margins.left(); + case QCP::msRight: return margins.right(); + case QCP::msTop: return margins.top(); + case QCP::msBottom: return margins.bottom(); + default: break; + } + return 0; +} + +} // end of namespace QCP + +Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::AntialiasedElements) +Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::PlottingHints) +Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::MarginSides) +Q_DECLARE_OPERATORS_FOR_FLAGS(QCP::Interactions) + + +class QCP_LIB_DECL QCPScatterStyle +{ + Q_GADGET +public: + /*! + Defines the shape used for scatter points. + + On plottables/items that draw scatters, the sizes of these visualizations (with exception of + \ref ssDot and \ref ssPixmap) can be controlled with the \ref setSize function. Scatters are + drawn with the pen and brush specified with \ref setPen and \ref setBrush. + */ + Q_ENUMS(ScatterShape) + enum ScatterShape { ssNone ///< no scatter symbols are drawn (e.g. in QCPGraph, data only represented with lines) + ,ssDot ///< \enumimage{ssDot.png} a single pixel (use \ref ssDisc or \ref ssCircle if you want a round shape with a certain radius) + ,ssCross ///< \enumimage{ssCross.png} a cross + ,ssPlus ///< \enumimage{ssPlus.png} a plus + ,ssCircle ///< \enumimage{ssCircle.png} a circle + ,ssDisc ///< \enumimage{ssDisc.png} a circle which is filled with the pen's color (not the brush as with ssCircle) + ,ssSquare ///< \enumimage{ssSquare.png} a square + ,ssDiamond ///< \enumimage{ssDiamond.png} a diamond + ,ssStar ///< \enumimage{ssStar.png} a star with eight arms, i.e. a combination of cross and plus + ,ssTriangle ///< \enumimage{ssTriangle.png} an equilateral triangle, standing on baseline + ,ssTriangleInverted ///< \enumimage{ssTriangleInverted.png} an equilateral triangle, standing on corner + ,ssCrossSquare ///< \enumimage{ssCrossSquare.png} a square with a cross inside + ,ssPlusSquare ///< \enumimage{ssPlusSquare.png} a square with a plus inside + ,ssCrossCircle ///< \enumimage{ssCrossCircle.png} a circle with a cross inside + ,ssPlusCircle ///< \enumimage{ssPlusCircle.png} a circle with a plus inside + ,ssPeace ///< \enumimage{ssPeace.png} a circle, with one vertical and two downward diagonal lines + ,ssPixmap ///< a custom pixmap specified by \ref setPixmap, centered on the data point coordinates + ,ssCustom ///< custom painter operations are performed per scatter (As QPainterPath, see \ref setCustomPath) + }; + + QCPScatterStyle(); + QCPScatterStyle(ScatterShape shape, double size=6); + QCPScatterStyle(ScatterShape shape, const QColor &color, double size); + QCPScatterStyle(ScatterShape shape, const QColor &color, const QColor &fill, double size); + QCPScatterStyle(ScatterShape shape, const QPen &pen, const QBrush &brush, double size); + QCPScatterStyle(const QPixmap &pixmap); + QCPScatterStyle(const QPainterPath &customPath, const QPen &pen, const QBrush &brush=Qt::NoBrush, double size=6); + + // getters: + double size() const { return mSize; } + ScatterShape shape() const { return mShape; } + QPen pen() const { return mPen; } + QBrush brush() const { return mBrush; } + QPixmap pixmap() const { return mPixmap; } + QPainterPath customPath() const { return mCustomPath; } + + // setters: + void setSize(double size); + void setShape(ScatterShape shape); + void setPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setPixmap(const QPixmap &pixmap); + void setCustomPath(const QPainterPath &customPath); + + // non-property methods: + bool isNone() const { return mShape == ssNone; } + bool isPenDefined() const { return mPenDefined; } + void applyTo(QCPPainter *painter, const QPen &defaultPen) const; + void drawShape(QCPPainter *painter, QPointF pos) const; + void drawShape(QCPPainter *painter, double x, double y) const; + +protected: + // property members: + double mSize; + ScatterShape mShape; + QPen mPen; + QBrush mBrush; + QPixmap mPixmap; + QPainterPath mCustomPath; + + // non-property members: + bool mPenDefined; +}; +Q_DECLARE_TYPEINFO(QCPScatterStyle, Q_MOVABLE_TYPE); + + +class QCP_LIB_DECL QCPPainter : public QPainter +{ + Q_GADGET +public: + /*! + Defines special modes the painter can operate in. They disable or enable certain subsets of features/fixes/workarounds, + depending on whether they are wanted on the respective output device. + */ + enum PainterMode { pmDefault = 0x00 ///< 0x00 Default mode for painting on screen devices + ,pmVectorized = 0x01 ///< 0x01 Mode for vectorized painting (e.g. PDF export). For example, this prevents some antialiasing fixes. + ,pmNoCaching = 0x02 ///< 0x02 Mode for all sorts of exports (e.g. PNG, PDF,...). For example, this prevents using cached pixmap labels + ,pmNonCosmetic = 0x04 ///< 0x04 Turns pen widths 0 to 1, i.e. disables cosmetic pens. (A cosmetic pen is always drawn with width 1 pixel in the vector image/pdf viewer, independent of zoom.) + }; + Q_FLAGS(PainterMode PainterModes) + Q_DECLARE_FLAGS(PainterModes, PainterMode) + + QCPPainter(); + QCPPainter(QPaintDevice *device); + ~QCPPainter(); + + // getters: + bool antialiasing() const { return testRenderHint(QPainter::Antialiasing); } + PainterModes modes() const { return mModes; } + + // setters: + void setAntialiasing(bool enabled); + void setMode(PainterMode mode, bool enabled=true); + void setModes(PainterModes modes); + + // methods hiding non-virtual base class functions (QPainter bug workarounds): + bool begin(QPaintDevice *device); + void setPen(const QPen &pen); + void setPen(const QColor &color); + void setPen(Qt::PenStyle penStyle); + void drawLine(const QLineF &line); + void drawLine(const QPointF &p1, const QPointF &p2) {drawLine(QLineF(p1, p2));} + void save(); + void restore(); + + // non-virtual methods: + void makeNonCosmetic(); + +protected: + // property members: + PainterModes mModes; + bool mIsAntialiasing; + + // non-property members: + QStack mAntialiasingStack; +}; +Q_DECLARE_OPERATORS_FOR_FLAGS(QCPPainter::PainterModes) + + +class QCP_LIB_DECL QCPLayer : public QObject +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) + Q_PROPERTY(QString name READ name) + Q_PROPERTY(int index READ index) + Q_PROPERTY(QList children READ children) + Q_PROPERTY(bool visible READ visible WRITE setVisible) + /// \endcond +public: + QCPLayer(QCustomPlot* parentPlot, const QString &layerName); + ~QCPLayer(); + + // getters: + QCustomPlot *parentPlot() const { return mParentPlot; } + QString name() const { return mName; } + int index() const { return mIndex; } + QList children() const { return mChildren; } + bool visible() const { return mVisible; } + + // setters: + void setVisible(bool visible); + +protected: + // property members: + QCustomPlot *mParentPlot; + QString mName; + int mIndex; + QList mChildren; + bool mVisible; + + // non-virtual methods: + void addChild(QCPLayerable *layerable, bool prepend); + void removeChild(QCPLayerable *layerable); + +private: + Q_DISABLE_COPY(QCPLayer) + + friend class QCustomPlot; + friend class QCPLayerable; +}; + +class QCP_LIB_DECL QCPLayerable : public QObject +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(bool visible READ visible WRITE setVisible) + Q_PROPERTY(QCustomPlot* parentPlot READ parentPlot) + Q_PROPERTY(QCPLayerable* parentLayerable READ parentLayerable) + Q_PROPERTY(QCPLayer* layer READ layer WRITE setLayer NOTIFY layerChanged) + Q_PROPERTY(bool antialiased READ antialiased WRITE setAntialiased) + /// \endcond +public: + QCPLayerable(QCustomPlot *plot, QString targetLayer="", QCPLayerable *parentLayerable=0); + ~QCPLayerable(); + + // getters: + bool visible() const { return mVisible; } + QCustomPlot *parentPlot() const { return mParentPlot; } + QCPLayerable *parentLayerable() const { return mParentLayerable.data(); } + QCPLayer *layer() const { return mLayer; } + bool antialiased() const { return mAntialiased; } + + // setters: + void setVisible(bool on); + Q_SLOT bool setLayer(QCPLayer *layer); + bool setLayer(const QString &layerName); + void setAntialiased(bool enabled); + + // introduced virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + // non-property methods: + bool realVisibility() const; + +signals: + void layerChanged(QCPLayer *newLayer); + +protected: + // property members: + bool mVisible; + QCustomPlot *mParentPlot; + QPointer mParentLayerable; + QCPLayer *mLayer; + bool mAntialiased; + + // introduced virtual methods: + virtual void parentPlotInitialized(QCustomPlot *parentPlot); + virtual QCP::Interaction selectionCategory() const; + virtual QRect clipRect() const; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const = 0; + virtual void draw(QCPPainter *painter) = 0; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // non-property methods: + void initializeParentPlot(QCustomPlot *parentPlot); + void setParentLayerable(QCPLayerable* parentLayerable); + bool moveToLayer(QCPLayer *layer, bool prepend); + void applyAntialiasingHint(QCPPainter *painter, bool localAntialiased, QCP::AntialiasedElement overrideElement) const; + +private: + Q_DISABLE_COPY(QCPLayerable) + + friend class QCustomPlot; + friend class QCPAxisRect; +}; + + +class QCP_LIB_DECL QCPRange +{ +public: + double lower, upper; + + QCPRange(); + QCPRange(double lower, double upper); + + bool operator==(const QCPRange& other) const { return lower == other.lower && upper == other.upper; } + bool operator!=(const QCPRange& other) const { return !(*this == other); } + + QCPRange &operator+=(const double& value) { lower+=value; upper+=value; return *this; } + QCPRange &operator-=(const double& value) { lower-=value; upper-=value; return *this; } + QCPRange &operator*=(const double& value) { lower*=value; upper*=value; return *this; } + QCPRange &operator/=(const double& value) { lower/=value; upper/=value; return *this; } + friend inline const QCPRange operator+(const QCPRange&, double); + friend inline const QCPRange operator+(double, const QCPRange&); + friend inline const QCPRange operator-(const QCPRange& range, double value); + friend inline const QCPRange operator*(const QCPRange& range, double value); + friend inline const QCPRange operator*(double value, const QCPRange& range); + friend inline const QCPRange operator/(const QCPRange& range, double value); + + double size() const; + double center() const; + void normalize(); + void expand(const QCPRange &otherRange); + QCPRange expanded(const QCPRange &otherRange) const; + QCPRange sanitizedForLogScale() const; + QCPRange sanitizedForLinScale() const; + bool contains(double value) const; + + static bool validRange(double lower, double upper); + static bool validRange(const QCPRange &range); + static const double minRange; //1e-280; + static const double maxRange; //1e280; + +}; +Q_DECLARE_TYPEINFO(QCPRange, Q_MOVABLE_TYPE); + +/* documentation of inline functions */ + +/*! \fn QCPRange &QCPRange::operator+=(const double& value) + + Adds \a value to both boundaries of the range. +*/ + +/*! \fn QCPRange &QCPRange::operator-=(const double& value) + + Subtracts \a value from both boundaries of the range. +*/ + +/*! \fn QCPRange &QCPRange::operator*=(const double& value) + + Multiplies both boundaries of the range by \a value. +*/ + +/*! \fn QCPRange &QCPRange::operator/=(const double& value) + + Divides both boundaries of the range by \a value. +*/ + +/* end documentation of inline functions */ + +/*! + Adds \a value to both boundaries of the range. +*/ +inline const QCPRange operator+(const QCPRange& range, double value) +{ + QCPRange result(range); + result += value; + return result; +} + +/*! + Adds \a value to both boundaries of the range. +*/ +inline const QCPRange operator+(double value, const QCPRange& range) +{ + QCPRange result(range); + result += value; + return result; +} + +/*! + Subtracts \a value from both boundaries of the range. +*/ +inline const QCPRange operator-(const QCPRange& range, double value) +{ + QCPRange result(range); + result -= value; + return result; +} + +/*! + Multiplies both boundaries of the range by \a value. +*/ +inline const QCPRange operator*(const QCPRange& range, double value) +{ + QCPRange result(range); + result *= value; + return result; +} + +/*! + Multiplies both boundaries of the range by \a value. +*/ +inline const QCPRange operator*(double value, const QCPRange& range) +{ + QCPRange result(range); + result *= value; + return result; +} + +/*! + Divides both boundaries of the range by \a value. +*/ +inline const QCPRange operator/(const QCPRange& range, double value) +{ + QCPRange result(range); + result /= value; + return result; +} + + +class QCP_LIB_DECL QCPMarginGroup : public QObject +{ + Q_OBJECT +public: + QCPMarginGroup(QCustomPlot *parentPlot); + ~QCPMarginGroup(); + + // non-virtual methods: + QList elements(QCP::MarginSide side) const { return mChildren.value(side); } + bool isEmpty() const; + void clear(); + +protected: + // non-property members: + QCustomPlot *mParentPlot; + QHash > mChildren; + + // non-virtual methods: + int commonMargin(QCP::MarginSide side) const; + void addChild(QCP::MarginSide side, QCPLayoutElement *element); + void removeChild(QCP::MarginSide side, QCPLayoutElement *element); + +private: + Q_DISABLE_COPY(QCPMarginGroup) + + friend class QCPLayoutElement; +}; + + +class QCP_LIB_DECL QCPLayoutElement : public QCPLayerable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCPLayout* layout READ layout) + Q_PROPERTY(QRect rect READ rect) + Q_PROPERTY(QRect outerRect READ outerRect WRITE setOuterRect) + Q_PROPERTY(QMargins margins READ margins WRITE setMargins) + Q_PROPERTY(QMargins minimumMargins READ minimumMargins WRITE setMinimumMargins) + Q_PROPERTY(QSize minimumSize READ minimumSize WRITE setMinimumSize) + Q_PROPERTY(QSize maximumSize READ maximumSize WRITE setMaximumSize) + /// \endcond +public: + /*! + Defines the phases of the update process, that happens just before a replot. At each phase, + \ref update is called with the according UpdatePhase value. + */ + enum UpdatePhase { upPreparation ///< Phase used for any type of preparation that needs to be done before margin calculation and layout + ,upMargins ///< Phase in which the margins are calculated and set + ,upLayout ///< Final phase in which the layout system places the rects of the elements + }; + Q_ENUMS(UpdatePhase) + + explicit QCPLayoutElement(QCustomPlot *parentPlot=0); + virtual ~QCPLayoutElement(); + + // getters: + QCPLayout *layout() const { return mParentLayout; } + QRect rect() const { return mRect; } + QRect outerRect() const { return mOuterRect; } + QMargins margins() const { return mMargins; } + QMargins minimumMargins() const { return mMinimumMargins; } + QCP::MarginSides autoMargins() const { return mAutoMargins; } + QSize minimumSize() const { return mMinimumSize; } + QSize maximumSize() const { return mMaximumSize; } + QCPMarginGroup *marginGroup(QCP::MarginSide side) const { return mMarginGroups.value(side, (QCPMarginGroup*)0); } + QHash marginGroups() const { return mMarginGroups; } + + // setters: + void setOuterRect(const QRect &rect); + void setMargins(const QMargins &margins); + void setMinimumMargins(const QMargins &margins); + void setAutoMargins(QCP::MarginSides sides); + void setMinimumSize(const QSize &size); + void setMinimumSize(int width, int height); + void setMaximumSize(const QSize &size); + void setMaximumSize(int width, int height); + void setMarginGroup(QCP::MarginSides sides, QCPMarginGroup *group); + + // introduced virtual methods: + virtual void update(UpdatePhase phase); + virtual QSize minimumSizeHint() const; + virtual QSize maximumSizeHint() const; + virtual QList elements(bool recursive) const; + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + +protected: + // property members: + QCPLayout *mParentLayout; + QSize mMinimumSize, mMaximumSize; + QRect mRect, mOuterRect; + QMargins mMargins, mMinimumMargins; + QCP::MarginSides mAutoMargins; + QHash mMarginGroups; + + // introduced virtual methods: + virtual int calculateAutoMargin(QCP::MarginSide side); + // events: + virtual void mousePressEvent(QMouseEvent *event) {Q_UNUSED(event)} + virtual void mouseMoveEvent(QMouseEvent *event) {Q_UNUSED(event)} + virtual void mouseReleaseEvent(QMouseEvent *event) {Q_UNUSED(event)} + virtual void mouseDoubleClickEvent(QMouseEvent *event) {Q_UNUSED(event)} + virtual void wheelEvent(QWheelEvent *event) {Q_UNUSED(event)} + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const { Q_UNUSED(painter) } + virtual void draw(QCPPainter *painter) { Q_UNUSED(painter) } + virtual void parentPlotInitialized(QCustomPlot *parentPlot); + +private: + Q_DISABLE_COPY(QCPLayoutElement) + + friend class QCustomPlot; + friend class QCPLayout; + friend class QCPMarginGroup; +}; + + +class QCP_LIB_DECL QCPLayout : public QCPLayoutElement +{ + Q_OBJECT +public: + explicit QCPLayout(); + + // reimplemented virtual methods: + virtual void update(UpdatePhase phase); + virtual QList elements(bool recursive) const; + + // introduced virtual methods: + virtual int elementCount() const = 0; + virtual QCPLayoutElement* elementAt(int index) const = 0; + virtual QCPLayoutElement* takeAt(int index) = 0; + virtual bool take(QCPLayoutElement* element) = 0; + virtual void simplify(); + + // non-virtual methods: + bool removeAt(int index); + bool remove(QCPLayoutElement* element); + void clear(); + +protected: + // introduced virtual methods: + virtual void updateLayout(); + + // non-virtual methods: + void sizeConstraintsChanged() const; + void adoptElement(QCPLayoutElement *el); + void releaseElement(QCPLayoutElement *el); + QVector getSectionSizes(QVector maxSizes, QVector minSizes, QVector stretchFactors, int totalSize) const; + +private: + Q_DISABLE_COPY(QCPLayout) + friend class QCPLayoutElement; +}; + + +class QCP_LIB_DECL QCPLayoutGrid : public QCPLayout +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(int rowCount READ rowCount) + Q_PROPERTY(int columnCount READ columnCount) + Q_PROPERTY(QList columnStretchFactors READ columnStretchFactors WRITE setColumnStretchFactors) + Q_PROPERTY(QList rowStretchFactors READ rowStretchFactors WRITE setRowStretchFactors) + Q_PROPERTY(int columnSpacing READ columnSpacing WRITE setColumnSpacing) + Q_PROPERTY(int rowSpacing READ rowSpacing WRITE setRowSpacing) + /// \endcond +public: + explicit QCPLayoutGrid(); + virtual ~QCPLayoutGrid(); + + // getters: + int rowCount() const; + int columnCount() const; + QList columnStretchFactors() const { return mColumnStretchFactors; } + QList rowStretchFactors() const { return mRowStretchFactors; } + int columnSpacing() const { return mColumnSpacing; } + int rowSpacing() const { return mRowSpacing; } + + // setters: + void setColumnStretchFactor(int column, double factor); + void setColumnStretchFactors(const QList &factors); + void setRowStretchFactor(int row, double factor); + void setRowStretchFactors(const QList &factors); + void setColumnSpacing(int pixels); + void setRowSpacing(int pixels); + + // reimplemented virtual methods: + virtual void updateLayout(); + virtual int elementCount() const; + virtual QCPLayoutElement* elementAt(int index) const; + virtual QCPLayoutElement* takeAt(int index); + virtual bool take(QCPLayoutElement* element); + virtual QList elements(bool recursive) const; + virtual void simplify(); + virtual QSize minimumSizeHint() const; + virtual QSize maximumSizeHint() const; + + // non-virtual methods: + QCPLayoutElement *element(int row, int column) const; + bool addElement(int row, int column, QCPLayoutElement *element); + bool hasElement(int row, int column); + void expandTo(int newRowCount, int newColumnCount); + void insertRow(int newIndex); + void insertColumn(int newIndex); + +protected: + // property members: + QList > mElements; + QList mColumnStretchFactors; + QList mRowStretchFactors; + int mColumnSpacing, mRowSpacing; + + // non-virtual methods: + void getMinimumRowColSizes(QVector *minColWidths, QVector *minRowHeights) const; + void getMaximumRowColSizes(QVector *maxColWidths, QVector *maxRowHeights) const; + +private: + Q_DISABLE_COPY(QCPLayoutGrid) +}; + + +class QCP_LIB_DECL QCPLayoutInset : public QCPLayout +{ + Q_OBJECT +public: + /*! + Defines how the placement and sizing is handled for a certain element in a QCPLayoutInset. + */ + enum InsetPlacement { ipFree ///< The element may be positioned/sized arbitrarily, see \ref setInsetRect + ,ipBorderAligned ///< The element is aligned to one of the layout sides, see \ref setInsetAlignment + }; + + explicit QCPLayoutInset(); + virtual ~QCPLayoutInset(); + + // getters: + InsetPlacement insetPlacement(int index) const; + Qt::Alignment insetAlignment(int index) const; + QRectF insetRect(int index) const; + + // setters: + void setInsetPlacement(int index, InsetPlacement placement); + void setInsetAlignment(int index, Qt::Alignment alignment); + void setInsetRect(int index, const QRectF &rect); + + // reimplemented virtual methods: + virtual void updateLayout(); + virtual int elementCount() const; + virtual QCPLayoutElement* elementAt(int index) const; + virtual QCPLayoutElement* takeAt(int index); + virtual bool take(QCPLayoutElement* element); + virtual void simplify() {} + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + // non-virtual methods: + void addElement(QCPLayoutElement *element, Qt::Alignment alignment); + void addElement(QCPLayoutElement *element, const QRectF &rect); + +protected: + // property members: + QList mElements; + QList mInsetPlacement; + QList mInsetAlignment; + QList mInsetRect; + +private: + Q_DISABLE_COPY(QCPLayoutInset) +}; + + +class QCP_LIB_DECL QCPLineEnding +{ + Q_GADGET +public: + /*! + Defines the type of ending decoration for line-like items, e.g. an arrow. + + \image html QCPLineEnding.png + + The width and length of these decorations can be controlled with the functions \ref setWidth + and \ref setLength. Some decorations like \ref esDisc, \ref esSquare, \ref esDiamond and \ref esBar only + support a width, the length property is ignored. + + \see QCPItemLine::setHead, QCPItemLine::setTail, QCPItemCurve::setHead, QCPItemCurve::setTail, QCPAxis::setLowerEnding, QCPAxis::setUpperEnding + */ + Q_ENUMS(EndingStyle) + enum EndingStyle { esNone ///< No ending decoration + ,esFlatArrow ///< A filled arrow head with a straight/flat back (a triangle) + ,esSpikeArrow ///< A filled arrow head with an indented back + ,esLineArrow ///< A non-filled arrow head with open back + ,esDisc ///< A filled circle + ,esSquare ///< A filled square + ,esDiamond ///< A filled diamond (45° rotated square) + ,esBar ///< A bar perpendicular to the line + ,esHalfBar ///< A bar perpendicular to the line, pointing out to only one side (to which side can be changed with \ref setInverted) + ,esSkewedBar ///< A bar that is skewed (skew controllable via \ref setLength) + }; + + QCPLineEnding(); + QCPLineEnding(EndingStyle style, double width=8, double length=10, bool inverted=false); + + // getters: + EndingStyle style() const { return mStyle; } + double width() const { return mWidth; } + double length() const { return mLength; } + bool inverted() const { return mInverted; } + + // setters: + void setStyle(EndingStyle style); + void setWidth(double width); + void setLength(double length); + void setInverted(bool inverted); + + // non-property methods: + double boundingDistance() const; + double realLength() const; + void draw(QCPPainter *painter, const QVector2D &pos, const QVector2D &dir) const; + void draw(QCPPainter *painter, const QVector2D &pos, double angle) const; + +protected: + // property members: + EndingStyle mStyle; + double mWidth, mLength; + bool mInverted; +}; +Q_DECLARE_TYPEINFO(QCPLineEnding, Q_MOVABLE_TYPE); + + +class QCP_LIB_DECL QCPGrid :public QCPLayerable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(bool subGridVisible READ subGridVisible WRITE setSubGridVisible) + Q_PROPERTY(bool antialiasedSubGrid READ antialiasedSubGrid WRITE setAntialiasedSubGrid) + Q_PROPERTY(bool antialiasedZeroLine READ antialiasedZeroLine WRITE setAntialiasedZeroLine) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen subGridPen READ subGridPen WRITE setSubGridPen) + Q_PROPERTY(QPen zeroLinePen READ zeroLinePen WRITE setZeroLinePen) + /// \endcond +public: + QCPGrid(QCPAxis *parentAxis); + + // getters: + bool subGridVisible() const { return mSubGridVisible; } + bool antialiasedSubGrid() const { return mAntialiasedSubGrid; } + bool antialiasedZeroLine() const { return mAntialiasedZeroLine; } + QPen pen() const { return mPen; } + QPen subGridPen() const { return mSubGridPen; } + QPen zeroLinePen() const { return mZeroLinePen; } + + // setters: + void setSubGridVisible(bool visible); + void setAntialiasedSubGrid(bool enabled); + void setAntialiasedZeroLine(bool enabled); + void setPen(const QPen &pen); + void setSubGridPen(const QPen &pen); + void setZeroLinePen(const QPen &pen); + +protected: + // property members: + bool mSubGridVisible; + bool mAntialiasedSubGrid, mAntialiasedZeroLine; + QPen mPen, mSubGridPen, mZeroLinePen; + // non-property members: + QCPAxis *mParentAxis; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + virtual void draw(QCPPainter *painter); + + // non-virtual methods: + void drawGridLines(QCPPainter *painter) const; + void drawSubGridLines(QCPPainter *painter) const; + + friend class QCPAxis; +}; + + +class QCP_LIB_DECL QCPAxis : public QCPLayerable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(AxisType axisType READ axisType) + Q_PROPERTY(QCPAxisRect* axisRect READ axisRect) + Q_PROPERTY(ScaleType scaleType READ scaleType WRITE setScaleType NOTIFY scaleTypeChanged) + Q_PROPERTY(double scaleLogBase READ scaleLogBase WRITE setScaleLogBase) + Q_PROPERTY(QCPRange range READ range WRITE setRange NOTIFY rangeChanged) + Q_PROPERTY(bool rangeReversed READ rangeReversed WRITE setRangeReversed) + Q_PROPERTY(bool autoTicks READ autoTicks WRITE setAutoTicks) + Q_PROPERTY(int autoTickCount READ autoTickCount WRITE setAutoTickCount) + Q_PROPERTY(bool autoTickLabels READ autoTickLabels WRITE setAutoTickLabels) + Q_PROPERTY(bool autoTickStep READ autoTickStep WRITE setAutoTickStep) + Q_PROPERTY(bool autoSubTicks READ autoSubTicks WRITE setAutoSubTicks) + Q_PROPERTY(bool ticks READ ticks WRITE setTicks) + Q_PROPERTY(bool tickLabels READ tickLabels WRITE setTickLabels) + Q_PROPERTY(int tickLabelPadding READ tickLabelPadding WRITE setTickLabelPadding) + Q_PROPERTY(LabelType tickLabelType READ tickLabelType WRITE setTickLabelType) + Q_PROPERTY(QFont tickLabelFont READ tickLabelFont WRITE setTickLabelFont) + Q_PROPERTY(QColor tickLabelColor READ tickLabelColor WRITE setTickLabelColor) + Q_PROPERTY(double tickLabelRotation READ tickLabelRotation WRITE setTickLabelRotation) + Q_PROPERTY(LabelSide tickLabelSide READ tickLabelSide WRITE setTickLabelSide) + Q_PROPERTY(QString dateTimeFormat READ dateTimeFormat WRITE setDateTimeFormat) + Q_PROPERTY(Qt::TimeSpec dateTimeSpec READ dateTimeSpec WRITE setDateTimeSpec) + Q_PROPERTY(QString numberFormat READ numberFormat WRITE setNumberFormat) + Q_PROPERTY(int numberPrecision READ numberPrecision WRITE setNumberPrecision) + Q_PROPERTY(double tickStep READ tickStep WRITE setTickStep) + Q_PROPERTY(QVector tickVector READ tickVector WRITE setTickVector) + Q_PROPERTY(QVector tickVectorLabels READ tickVectorLabels WRITE setTickVectorLabels) + Q_PROPERTY(int tickLengthIn READ tickLengthIn WRITE setTickLengthIn) + Q_PROPERTY(int tickLengthOut READ tickLengthOut WRITE setTickLengthOut) + Q_PROPERTY(int subTickCount READ subTickCount WRITE setSubTickCount) + Q_PROPERTY(int subTickLengthIn READ subTickLengthIn WRITE setSubTickLengthIn) + Q_PROPERTY(int subTickLengthOut READ subTickLengthOut WRITE setSubTickLengthOut) + Q_PROPERTY(QPen basePen READ basePen WRITE setBasePen) + Q_PROPERTY(QPen tickPen READ tickPen WRITE setTickPen) + Q_PROPERTY(QPen subTickPen READ subTickPen WRITE setSubTickPen) + Q_PROPERTY(QFont labelFont READ labelFont WRITE setLabelFont) + Q_PROPERTY(QColor labelColor READ labelColor WRITE setLabelColor) + Q_PROPERTY(QString label READ label WRITE setLabel) + Q_PROPERTY(int labelPadding READ labelPadding WRITE setLabelPadding) + Q_PROPERTY(int padding READ padding WRITE setPadding) + Q_PROPERTY(int offset READ offset WRITE setOffset) + Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectionChanged) + Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectableChanged) + Q_PROPERTY(QFont selectedTickLabelFont READ selectedTickLabelFont WRITE setSelectedTickLabelFont) + Q_PROPERTY(QFont selectedLabelFont READ selectedLabelFont WRITE setSelectedLabelFont) + Q_PROPERTY(QColor selectedTickLabelColor READ selectedTickLabelColor WRITE setSelectedTickLabelColor) + Q_PROPERTY(QColor selectedLabelColor READ selectedLabelColor WRITE setSelectedLabelColor) + Q_PROPERTY(QPen selectedBasePen READ selectedBasePen WRITE setSelectedBasePen) + Q_PROPERTY(QPen selectedTickPen READ selectedTickPen WRITE setSelectedTickPen) + Q_PROPERTY(QPen selectedSubTickPen READ selectedSubTickPen WRITE setSelectedSubTickPen) + Q_PROPERTY(QCPLineEnding lowerEnding READ lowerEnding WRITE setLowerEnding) + Q_PROPERTY(QCPLineEnding upperEnding READ upperEnding WRITE setUpperEnding) + Q_PROPERTY(QCPGrid* grid READ grid) + /// \endcond +public: + /*! + Defines at which side of the axis rect the axis will appear. This also affects how the tick + marks are drawn, on which side the labels are placed etc. + */ + enum AxisType { atLeft = 0x01 ///< 0x01 Axis is vertical and on the left side of the axis rect + ,atRight = 0x02 ///< 0x02 Axis is vertical and on the right side of the axis rect + ,atTop = 0x04 ///< 0x04 Axis is horizontal and on the top side of the axis rect + ,atBottom = 0x08 ///< 0x08 Axis is horizontal and on the bottom side of the axis rect + }; + Q_FLAGS(AxisType AxisTypes) + Q_DECLARE_FLAGS(AxisTypes, AxisType) + /*! + When automatic tick label generation is enabled (\ref setAutoTickLabels), defines how the + coordinate of the tick is interpreted, i.e. translated into a string. + + \see setTickLabelType + */ + enum LabelType { ltNumber ///< Tick coordinate is regarded as normal number and will be displayed as such. (see \ref setNumberFormat) + ,ltDateTime ///< Tick coordinate is regarded as a date/time (seconds since 1970-01-01T00:00:00 UTC) and will be displayed and formatted as such. (for details, see \ref setDateTimeFormat) + }; + Q_ENUMS(LabelType) + /*! + Defines on which side of the axis the tick labels (numbers) shall appear. + + \see setTickLabelSide + */ + enum LabelSide { lsInside ///< Tick labels will be displayed inside the axis rect and clipped to the inner axis rect + ,lsOutside ///< Tick labels will be displayed outside the axis rect + }; + Q_ENUMS(LabelSide) + /*! + Defines the scale of an axis. + \see setScaleType + */ + enum ScaleType { stLinear ///< Linear scaling + ,stLogarithmic ///< Logarithmic scaling with correspondingly transformed plots and (major) tick marks at every base power (see \ref setScaleLogBase). + }; + Q_ENUMS(ScaleType) + /*! + Defines the selectable parts of an axis. + \see setSelectableParts, setSelectedParts + */ + enum SelectablePart { spNone = 0 ///< None of the selectable parts + ,spAxis = 0x001 ///< The axis backbone and tick marks + ,spTickLabels = 0x002 ///< Tick labels (numbers) of this axis (as a whole, not individually) + ,spAxisLabel = 0x004 ///< The axis label + }; + Q_FLAGS(SelectablePart SelectableParts) + Q_DECLARE_FLAGS(SelectableParts, SelectablePart) + + explicit QCPAxis(QCPAxisRect *parent, AxisType type); + virtual ~QCPAxis(); + + // getters: + AxisType axisType() const { return mAxisType; } + QCPAxisRect *axisRect() const { return mAxisRect; } + ScaleType scaleType() const { return mScaleType; } + double scaleLogBase() const { return mScaleLogBase; } + const QCPRange range() const { return mRange; } + bool rangeReversed() const { return mRangeReversed; } + bool autoTicks() const { return mAutoTicks; } + int autoTickCount() const { return mAutoTickCount; } + bool autoTickLabels() const { return mAutoTickLabels; } + bool autoTickStep() const { return mAutoTickStep; } + bool autoSubTicks() const { return mAutoSubTicks; } + bool ticks() const { return mTicks; } + bool tickLabels() const { return mTickLabels; } + int tickLabelPadding() const; + LabelType tickLabelType() const { return mTickLabelType; } + QFont tickLabelFont() const { return mTickLabelFont; } + QColor tickLabelColor() const { return mTickLabelColor; } + double tickLabelRotation() const; + LabelSide tickLabelSide() const; + QString dateTimeFormat() const { return mDateTimeFormat; } + Qt::TimeSpec dateTimeSpec() const { return mDateTimeSpec; } + QString numberFormat() const; + int numberPrecision() const { return mNumberPrecision; } + double tickStep() const { return mTickStep; } + QVector tickVector() const { return mTickVector; } + QVector tickVectorLabels() const { return mTickVectorLabels; } + int tickLengthIn() const; + int tickLengthOut() const; + int subTickCount() const { return mSubTickCount; } + int subTickLengthIn() const; + int subTickLengthOut() const; + QPen basePen() const { return mBasePen; } + QPen tickPen() const { return mTickPen; } + QPen subTickPen() const { return mSubTickPen; } + QFont labelFont() const { return mLabelFont; } + QColor labelColor() const { return mLabelColor; } + QString label() const { return mLabel; } + int labelPadding() const; + int padding() const { return mPadding; } + int offset() const; + SelectableParts selectedParts() const { return mSelectedParts; } + SelectableParts selectableParts() const { return mSelectableParts; } + QFont selectedTickLabelFont() const { return mSelectedTickLabelFont; } + QFont selectedLabelFont() const { return mSelectedLabelFont; } + QColor selectedTickLabelColor() const { return mSelectedTickLabelColor; } + QColor selectedLabelColor() const { return mSelectedLabelColor; } + QPen selectedBasePen() const { return mSelectedBasePen; } + QPen selectedTickPen() const { return mSelectedTickPen; } + QPen selectedSubTickPen() const { return mSelectedSubTickPen; } + QCPLineEnding lowerEnding() const; + QCPLineEnding upperEnding() const; + QCPGrid *grid() const { return mGrid; } + + // setters: + Q_SLOT void setScaleType(QCPAxis::ScaleType type); + void setScaleLogBase(double base); + Q_SLOT void setRange(const QCPRange &range); + void setRange(double lower, double upper); + void setRange(double position, double size, Qt::AlignmentFlag alignment); + void setRangeLower(double lower); + void setRangeUpper(double upper); + void setRangeReversed(bool reversed); + void setAutoTicks(bool on); + void setAutoTickCount(int approximateCount); + void setAutoTickLabels(bool on); + void setAutoTickStep(bool on); + void setAutoSubTicks(bool on); + void setTicks(bool show); + void setTickLabels(bool show); + void setTickLabelPadding(int padding); + void setTickLabelType(LabelType type); + void setTickLabelFont(const QFont &font); + void setTickLabelColor(const QColor &color); + void setTickLabelRotation(double degrees); + void setTickLabelSide(LabelSide side); + void setDateTimeFormat(const QString &format); + void setDateTimeSpec(const Qt::TimeSpec &timeSpec); + void setNumberFormat(const QString &formatCode); + void setNumberPrecision(int precision); + void setTickStep(double step); + void setTickVector(const QVector &vec); + void setTickVectorLabels(const QVector &vec); + void setTickLength(int inside, int outside=0); + void setTickLengthIn(int inside); + void setTickLengthOut(int outside); + void setSubTickCount(int count); + void setSubTickLength(int inside, int outside=0); + void setSubTickLengthIn(int inside); + void setSubTickLengthOut(int outside); + void setBasePen(const QPen &pen); + void setTickPen(const QPen &pen); + void setSubTickPen(const QPen &pen); + void setLabelFont(const QFont &font); + void setLabelColor(const QColor &color); + void setLabel(const QString &str); + void setLabelPadding(int padding); + void setPadding(int padding); + void setOffset(int offset); + void setSelectedTickLabelFont(const QFont &font); + void setSelectedLabelFont(const QFont &font); + void setSelectedTickLabelColor(const QColor &color); + void setSelectedLabelColor(const QColor &color); + void setSelectedBasePen(const QPen &pen); + void setSelectedTickPen(const QPen &pen); + void setSelectedSubTickPen(const QPen &pen); + Q_SLOT void setSelectableParts(const QCPAxis::SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const QCPAxis::SelectableParts &selectedParts); + void setLowerEnding(const QCPLineEnding &ending); + void setUpperEnding(const QCPLineEnding &ending); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + // non-property methods: + Qt::Orientation orientation() const { return mOrientation; } + void moveRange(double diff); + void scaleRange(double factor, double center); + void setScaleRatio(const QCPAxis *otherAxis, double ratio=1.0); + void rescale(bool onlyVisiblePlottables=false); + double pixelToCoord(double value) const; + double coordToPixel(double value) const; + SelectablePart getPartAt(const QPointF &pos) const; + QList plottables() const; + QList graphs() const; + QList items() const; + + static AxisType marginSideToAxisType(QCP::MarginSide side); + static Qt::Orientation orientation(AxisType type) { return type==atBottom||type==atTop ? Qt::Horizontal : Qt::Vertical; } + static AxisType opposite(AxisType type); + +signals: + void ticksRequest(); + void rangeChanged(const QCPRange &newRange); + void rangeChanged(const QCPRange &newRange, const QCPRange &oldRange); + void scaleTypeChanged(QCPAxis::ScaleType scaleType); + void selectionChanged(const QCPAxis::SelectableParts &parts); + void selectableChanged(const QCPAxis::SelectableParts &parts); + +protected: + // property members: + // axis base: + AxisType mAxisType; + QCPAxisRect *mAxisRect; + //int mOffset; // in QCPAxisPainter + int mPadding; + Qt::Orientation mOrientation; + SelectableParts mSelectableParts, mSelectedParts; + QPen mBasePen, mSelectedBasePen; + //QCPLineEnding mLowerEnding, mUpperEnding; // in QCPAxisPainter + // axis label: + //int mLabelPadding; // in QCPAxisPainter + QString mLabel; + QFont mLabelFont, mSelectedLabelFont; + QColor mLabelColor, mSelectedLabelColor; + // tick labels: + //int mTickLabelPadding; // in QCPAxisPainter + bool mTickLabels, mAutoTickLabels; + //double mTickLabelRotation; // in QCPAxisPainter + LabelType mTickLabelType; + QFont mTickLabelFont, mSelectedTickLabelFont; + QColor mTickLabelColor, mSelectedTickLabelColor; + QString mDateTimeFormat; + Qt::TimeSpec mDateTimeSpec; + int mNumberPrecision; + char mNumberFormatChar; + bool mNumberBeautifulPowers; + //bool mNumberMultiplyCross; // QCPAxisPainter + // ticks and subticks: + bool mTicks; + double mTickStep; + int mSubTickCount, mAutoTickCount; + bool mAutoTicks, mAutoTickStep, mAutoSubTicks; + //int mTickLengthIn, mTickLengthOut, mSubTickLengthIn, mSubTickLengthOut; // QCPAxisPainter + QPen mTickPen, mSelectedTickPen; + QPen mSubTickPen, mSelectedSubTickPen; + // scale and range: + QCPRange mRange; + bool mRangeReversed; + ScaleType mScaleType; + double mScaleLogBase, mScaleLogBaseLogInv; + + // non-property members: + QCPGrid *mGrid; + QCPAxisPainterPrivate *mAxisPainter; + int mLowestVisibleTick, mHighestVisibleTick; + QVector mTickVector; + QVector mTickVectorLabels; + QVector mSubTickVector; + bool mCachedMarginValid; + int mCachedMargin; + + // introduced virtual methods: + virtual void setupTickVectors(); + virtual void generateAutoTicks(); + virtual int calculateAutoSubTickCount(double tickStep) const; + virtual int calculateMargin(); + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + virtual void draw(QCPPainter *painter); + virtual QCP::Interaction selectionCategory() const; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // non-virtual methods: + void visibleTickBounds(int &lowIndex, int &highIndex) const; + double baseLog(double value) const; + double basePow(double value) const; + QPen getBasePen() const; + QPen getTickPen() const; + QPen getSubTickPen() const; + QFont getTickLabelFont() const; + QFont getLabelFont() const; + QColor getTickLabelColor() const; + QColor getLabelColor() const; + +private: + Q_DISABLE_COPY(QCPAxis) + + friend class QCustomPlot; + friend class QCPGrid; + friend class QCPAxisRect; +}; +Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::SelectableParts) +Q_DECLARE_OPERATORS_FOR_FLAGS(QCPAxis::AxisTypes) +Q_DECLARE_METATYPE(QCPAxis::SelectablePart) + + +class QCPAxisPainterPrivate +{ +public: + explicit QCPAxisPainterPrivate(QCustomPlot *parentPlot); + virtual ~QCPAxisPainterPrivate(); + + virtual void draw(QCPPainter *painter); + virtual int size() const; + void clearCache(); + + QRect axisSelectionBox() const { return mAxisSelectionBox; } + QRect tickLabelsSelectionBox() const { return mTickLabelsSelectionBox; } + QRect labelSelectionBox() const { return mLabelSelectionBox; } + + // public property members: + QCPAxis::AxisType type; + QPen basePen; + QCPLineEnding lowerEnding, upperEnding; // directly accessed by QCPAxis setters/getters + int labelPadding; // directly accessed by QCPAxis setters/getters + QFont labelFont; + QColor labelColor; + QString label; + int tickLabelPadding; // directly accessed by QCPAxis setters/getters + double tickLabelRotation; // directly accessed by QCPAxis setters/getters + QCPAxis::LabelSide tickLabelSide; // directly accessed by QCPAxis setters/getters + bool substituteExponent; + bool numberMultiplyCross; // directly accessed by QCPAxis setters/getters + int tickLengthIn, tickLengthOut, subTickLengthIn, subTickLengthOut; // directly accessed by QCPAxis setters/getters + QPen tickPen, subTickPen; + QFont tickLabelFont; + QColor tickLabelColor; + QRect axisRect, viewportRect; + double offset; // directly accessed by QCPAxis setters/getters + bool abbreviateDecimalPowers; + bool reversedEndings; + + QVector subTickPositions; + QVector tickPositions; + QVector tickLabels; + +protected: + struct CachedLabel + { + QPointF offset; + QPixmap pixmap; + }; + struct TickLabelData + { + QString basePart, expPart; + QRect baseBounds, expBounds, totalBounds, rotatedTotalBounds; + QFont baseFont, expFont; + }; + QCustomPlot *mParentPlot; + QByteArray mLabelParameterHash; // to determine whether mLabelCache needs to be cleared due to changed parameters + QCache mLabelCache; + QRect mAxisSelectionBox, mTickLabelsSelectionBox, mLabelSelectionBox; + + virtual QByteArray generateLabelParameterHash() const; + + virtual void placeTickLabel(QCPPainter *painter, double position, int distanceToAxis, const QString &text, QSize *tickLabelsSize); + virtual void drawTickLabel(QCPPainter *painter, double x, double y, const TickLabelData &labelData) const; + virtual TickLabelData getTickLabelData(const QFont &font, const QString &text) const; + virtual QPointF getTickLabelDrawOffset(const TickLabelData &labelData) const; + virtual void getMaxTickLabelSize(const QFont &font, const QString &text, QSize *tickLabelsSize) const; +}; + + +class QCP_LIB_DECL QCPAbstractPlottable : public QCPLayerable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QString name READ name WRITE setName) + Q_PROPERTY(bool antialiasedFill READ antialiasedFill WRITE setAntialiasedFill) + Q_PROPERTY(bool antialiasedScatters READ antialiasedScatters WRITE setAntialiasedScatters) + Q_PROPERTY(bool antialiasedErrorBars READ antialiasedErrorBars WRITE setAntialiasedErrorBars) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + Q_PROPERTY(QCPAxis* keyAxis READ keyAxis WRITE setKeyAxis) + Q_PROPERTY(QCPAxis* valueAxis READ valueAxis WRITE setValueAxis) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) + /// \endcond +public: + QCPAbstractPlottable(QCPAxis *keyAxis, QCPAxis *valueAxis); + + // getters: + QString name() const { return mName; } + bool antialiasedFill() const { return mAntialiasedFill; } + bool antialiasedScatters() const { return mAntialiasedScatters; } + bool antialiasedErrorBars() const { return mAntialiasedErrorBars; } + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + QBrush brush() const { return mBrush; } + QBrush selectedBrush() const { return mSelectedBrush; } + QCPAxis *keyAxis() const { return mKeyAxis.data(); } + QCPAxis *valueAxis() const { return mValueAxis.data(); } + bool selectable() const { return mSelectable; } + bool selected() const { return mSelected; } + + // setters: + void setName(const QString &name); + void setAntialiasedFill(bool enabled); + void setAntialiasedScatters(bool enabled); + void setAntialiasedErrorBars(bool enabled); + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + void setKeyAxis(QCPAxis *axis); + void setValueAxis(QCPAxis *axis); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // introduced virtual methods: + virtual void clearData() = 0; + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0; + virtual bool addToLegend(); + virtual bool removeFromLegend() const; + + // non-property methods: + void rescaleAxes(bool onlyEnlarge=false) const; + void rescaleKeyAxis(bool onlyEnlarge=false) const; + void rescaleValueAxis(bool onlyEnlarge=false) const; + +signals: + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + +protected: + /*! + Represents negative and positive sign domain for passing to \ref getKeyRange and \ref getValueRange. + */ + enum SignDomain { sdNegative ///< The negative sign domain, i.e. numbers smaller than zero + ,sdBoth ///< Both sign domains, including zero, i.e. all (rational) numbers + ,sdPositive ///< The positive sign domain, i.e. numbers greater than zero + }; + + // property members: + QString mName; + bool mAntialiasedFill, mAntialiasedScatters, mAntialiasedErrorBars; + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + QPointer mKeyAxis, mValueAxis; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + virtual QRect clipRect() const; + virtual void draw(QCPPainter *painter) = 0; + virtual QCP::Interaction selectionCategory() const; + void applyDefaultAntialiasingHint(QCPPainter *painter) const; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // introduced virtual methods: + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const = 0; + virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0; + virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const = 0; + + // non-virtual methods: + void coordsToPixels(double key, double value, double &x, double &y) const; + const QPointF coordsToPixels(double key, double value) const; + void pixelsToCoords(double x, double y, double &key, double &value) const; + void pixelsToCoords(const QPointF &pixelPos, double &key, double &value) const; + QPen mainPen() const; + QBrush mainBrush() const; + void applyFillAntialiasingHint(QCPPainter *painter) const; + void applyScattersAntialiasingHint(QCPPainter *painter) const; + void applyErrorBarsAntialiasingHint(QCPPainter *painter) const; + double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const; + +private: + Q_DISABLE_COPY(QCPAbstractPlottable) + + friend class QCustomPlot; + friend class QCPAxis; + friend class QCPPlottableLegendItem; +}; + + +class QCP_LIB_DECL QCPItemAnchor +{ +public: + QCPItemAnchor(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name, int anchorId=-1); + virtual ~QCPItemAnchor(); + + // getters: + QString name() const { return mName; } + virtual QPointF pixelPoint() const; + +protected: + // property members: + QString mName; + + // non-property members: + QCustomPlot *mParentPlot; + QCPAbstractItem *mParentItem; + int mAnchorId; + QSet mChildrenX, mChildrenY; + + // introduced virtual methods: + virtual QCPItemPosition *toQCPItemPosition() { return 0; } + + // non-virtual methods: + void addChildX(QCPItemPosition* pos); // called from pos when this anchor is set as parent + void removeChildX(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted + void addChildY(QCPItemPosition* pos); // called from pos when this anchor is set as parent + void removeChildY(QCPItemPosition *pos); // called from pos when its parent anchor is reset or pos deleted + +private: + Q_DISABLE_COPY(QCPItemAnchor) + + friend class QCPItemPosition; +}; + + + +class QCP_LIB_DECL QCPItemPosition : public QCPItemAnchor +{ +public: + /*! + Defines the ways an item position can be specified. Thus it defines what the numbers passed to + \ref setCoords actually mean. + + \see setType + */ + enum PositionType { ptAbsolute ///< Static positioning in pixels, starting from the top left corner of the viewport/widget. + ,ptViewportRatio ///< Static positioning given by a fraction of the viewport size. For example, if you call setCoords(0, 0), the position will be at the top + ///< left corner of the viewport/widget. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and + ///< vertically at the top of the viewport/widget, etc. + ,ptAxisRectRatio ///< Static positioning given by a fraction of the axis rect size (see \ref setAxisRect). For example, if you call setCoords(0, 0), the position will be at the top + ///< left corner of the axis rect. setCoords(1, 1) will be at the bottom right corner, setCoords(0.5, 0) will be horizontally centered and + ///< vertically at the top of the axis rect, etc. You can also go beyond the axis rect by providing negative coordinates or coordinates larger than 1. + ,ptPlotCoords ///< Dynamic positioning at a plot coordinate defined by two axes (see \ref setAxes). + }; + + QCPItemPosition(QCustomPlot *parentPlot, QCPAbstractItem *parentItem, const QString name); + virtual ~QCPItemPosition(); + + // getters: + PositionType type() const { return typeX(); } + PositionType typeX() const { return mPositionTypeX; } + PositionType typeY() const { return mPositionTypeY; } + QCPItemAnchor *parentAnchor() const { return parentAnchorX(); } + QCPItemAnchor *parentAnchorX() const { return mParentAnchorX; } + QCPItemAnchor *parentAnchorY() const { return mParentAnchorY; } + double key() const { return mKey; } + double value() const { return mValue; } + QPointF coords() const { return QPointF(mKey, mValue); } + QCPAxis *keyAxis() const { return mKeyAxis.data(); } + QCPAxis *valueAxis() const { return mValueAxis.data(); } + QCPAxisRect *axisRect() const; + virtual QPointF pixelPoint() const; + + // setters: + void setType(PositionType type); + void setTypeX(PositionType type); + void setTypeY(PositionType type); + bool setParentAnchor(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); + bool setParentAnchorX(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); + bool setParentAnchorY(QCPItemAnchor *parentAnchor, bool keepPixelPosition=false); + void setCoords(double key, double value); + void setCoords(const QPointF &coords); + void setAxes(QCPAxis* keyAxis, QCPAxis* valueAxis); + void setAxisRect(QCPAxisRect *axisRect); + void setPixelPoint(const QPointF &pixelPoint); + +protected: + // property members: + PositionType mPositionTypeX, mPositionTypeY; + QPointer mKeyAxis, mValueAxis; + QPointer mAxisRect; + double mKey, mValue; + QCPItemAnchor *mParentAnchorX, *mParentAnchorY; + + // reimplemented virtual methods: + virtual QCPItemPosition *toQCPItemPosition() { return this; } + +private: + Q_DISABLE_COPY(QCPItemPosition) + +}; + + +class QCP_LIB_DECL QCPAbstractItem : public QCPLayerable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(bool clipToAxisRect READ clipToAxisRect WRITE setClipToAxisRect) + Q_PROPERTY(QCPAxisRect* clipAxisRect READ clipAxisRect WRITE setClipAxisRect) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) + /// \endcond +public: + QCPAbstractItem(QCustomPlot *parentPlot); + virtual ~QCPAbstractItem(); + + // getters: + bool clipToAxisRect() const { return mClipToAxisRect; } + QCPAxisRect *clipAxisRect() const; + bool selectable() const { return mSelectable; } + bool selected() const { return mSelected; } + + // setters: + void setClipToAxisRect(bool clip); + void setClipAxisRect(QCPAxisRect *rect); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const = 0; + + // non-virtual methods: + QList positions() const { return mPositions; } + QList anchors() const { return mAnchors; } + QCPItemPosition *position(const QString &name) const; + QCPItemAnchor *anchor(const QString &name) const; + bool hasAnchor(const QString &name) const; + +signals: + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + +protected: + // property members: + bool mClipToAxisRect; + QPointer mClipAxisRect; + QList mPositions; + QList mAnchors; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + virtual QCP::Interaction selectionCategory() const; + virtual QRect clipRect() const; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + virtual void draw(QCPPainter *painter) = 0; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // introduced virtual methods: + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + double distSqrToLine(const QPointF &start, const QPointF &end, const QPointF &point) const; + double rectSelectTest(const QRectF &rect, const QPointF &pos, bool filledRect) const; + QCPItemPosition *createPosition(const QString &name); + QCPItemAnchor *createAnchor(const QString &name, int anchorId); + +private: + Q_DISABLE_COPY(QCPAbstractItem) + + friend class QCustomPlot; + friend class QCPItemAnchor; +}; + + +class QCP_LIB_DECL QCustomPlot : public QWidget +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QRect viewport READ viewport WRITE setViewport) + Q_PROPERTY(QPixmap background READ background WRITE setBackground) + Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) + Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) + Q_PROPERTY(QCPLayoutGrid* plotLayout READ plotLayout) + Q_PROPERTY(bool autoAddPlottableToLegend READ autoAddPlottableToLegend WRITE setAutoAddPlottableToLegend) + Q_PROPERTY(int selectionTolerance READ selectionTolerance WRITE setSelectionTolerance) + Q_PROPERTY(bool noAntialiasingOnDrag READ noAntialiasingOnDrag WRITE setNoAntialiasingOnDrag) + Q_PROPERTY(Qt::KeyboardModifier multiSelectModifier READ multiSelectModifier WRITE setMultiSelectModifier) + /// \endcond +public: + /*! + Defines how a layer should be inserted relative to an other layer. + + \see addLayer, moveLayer + */ + enum LayerInsertMode { limBelow ///< Layer is inserted below other layer + ,limAbove ///< Layer is inserted above other layer + }; + Q_ENUMS(LayerInsertMode) + + /*! + Defines with what timing the QCustomPlot surface is refreshed after a replot. + + \see replot + */ + enum RefreshPriority { rpImmediate ///< The QCustomPlot surface is immediately refreshed, by calling QWidget::repaint() after the replot + ,rpQueued ///< Queues the refresh such that it is performed at a slightly delayed point in time after the replot, by calling QWidget::update() after the replot + ,rpHint ///< Whether to use immediate repaint or queued update depends on whether the plotting hint \ref QCP::phForceRepaint is set, see \ref setPlottingHints. + }; + + explicit QCustomPlot(QWidget *parent = 0); + virtual ~QCustomPlot(); + + // getters: + QRect viewport() const { return mViewport; } + QPixmap background() const { return mBackgroundPixmap; } + bool backgroundScaled() const { return mBackgroundScaled; } + Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } + QCPLayoutGrid *plotLayout() const { return mPlotLayout; } + QCP::AntialiasedElements antialiasedElements() const { return mAntialiasedElements; } + QCP::AntialiasedElements notAntialiasedElements() const { return mNotAntialiasedElements; } + bool autoAddPlottableToLegend() const { return mAutoAddPlottableToLegend; } + const QCP::Interactions interactions() const { return mInteractions; } + int selectionTolerance() const { return mSelectionTolerance; } + bool noAntialiasingOnDrag() const { return mNoAntialiasingOnDrag; } + QCP::PlottingHints plottingHints() const { return mPlottingHints; } + Qt::KeyboardModifier multiSelectModifier() const { return mMultiSelectModifier; } + + // setters: + void setViewport(const QRect &rect); + void setBackground(const QPixmap &pm); + void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); + void setBackground(const QBrush &brush); + void setBackgroundScaled(bool scaled); + void setBackgroundScaledMode(Qt::AspectRatioMode mode); + void setAntialiasedElements(const QCP::AntialiasedElements &antialiasedElements); + void setAntialiasedElement(QCP::AntialiasedElement antialiasedElement, bool enabled=true); + void setNotAntialiasedElements(const QCP::AntialiasedElements ¬AntialiasedElements); + void setNotAntialiasedElement(QCP::AntialiasedElement notAntialiasedElement, bool enabled=true); + void setAutoAddPlottableToLegend(bool on); + void setInteractions(const QCP::Interactions &interactions); + void setInteraction(const QCP::Interaction &interaction, bool enabled=true); + void setSelectionTolerance(int pixels); + void setNoAntialiasingOnDrag(bool enabled); + void setPlottingHints(const QCP::PlottingHints &hints); + void setPlottingHint(QCP::PlottingHint hint, bool enabled=true); + void setMultiSelectModifier(Qt::KeyboardModifier modifier); + + // non-property methods: + // plottable interface: + QCPAbstractPlottable *plottable(int index); + QCPAbstractPlottable *plottable(); + bool addPlottable(QCPAbstractPlottable *plottable); + bool removePlottable(QCPAbstractPlottable *plottable); + bool removePlottable(int index); + int clearPlottables(); + int plottableCount() const; + QList selectedPlottables() const; + QCPAbstractPlottable *plottableAt(const QPointF &pos, bool onlySelectable=false) const; + bool hasPlottable(QCPAbstractPlottable *plottable) const; + + // specialized interface for QCPGraph: + QCPGraph *graph(int index) const; + QCPGraph *graph() const; + QCPGraph *addGraph(QCPAxis *keyAxis=0, QCPAxis *valueAxis=0); + bool removeGraph(QCPGraph *graph); + bool removeGraph(int index); + int clearGraphs(); + int graphCount() const; + QList selectedGraphs() const; + + // item interface: + QCPAbstractItem *item(int index) const; + QCPAbstractItem *item() const; + bool addItem(QCPAbstractItem* item); + bool removeItem(QCPAbstractItem *item); + bool removeItem(int index); + int clearItems(); + int itemCount() const; + QList selectedItems() const; + QCPAbstractItem *itemAt(const QPointF &pos, bool onlySelectable=false) const; + bool hasItem(QCPAbstractItem *item) const; + + // layer interface: + QCPLayer *layer(const QString &name) const; + QCPLayer *layer(int index) const; + QCPLayer *currentLayer() const; + bool setCurrentLayer(const QString &name); + bool setCurrentLayer(QCPLayer *layer); + int layerCount() const; + bool addLayer(const QString &name, QCPLayer *otherLayer=0, LayerInsertMode insertMode=limAbove); + bool removeLayer(QCPLayer *layer); + bool moveLayer(QCPLayer *layer, QCPLayer *otherLayer, LayerInsertMode insertMode=limAbove); + + // axis rect/layout interface: + int axisRectCount() const; + QCPAxisRect* axisRect(int index=0) const; + QList axisRects() const; + QCPLayoutElement* layoutElementAt(const QPointF &pos) const; + Q_SLOT void rescaleAxes(bool onlyVisiblePlottables=false); + + QList selectedAxes() const; + QList selectedLegends() const; + Q_SLOT void deselectAll(); + + bool savePdf(const QString &fileName, bool noCosmeticPen=false, int width=0, int height=0, const QString &pdfCreator="", const QString &pdfTitle=""); + bool savePng(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1); + bool saveJpg(const QString &fileName, int width=0, int height=0, double scale=1.0, int quality=-1); + bool saveBmp(const QString &fileName, int width=0, int height=0, double scale=1.0); + bool saveRastered(const QString &fileName, int width, int height, double scale, const char *format, int quality=-1); + QPixmap toPixmap(int width=0, int height=0, double scale=1.0); + void toPainter(QCPPainter *painter, int width=0, int height=0); + Q_SLOT void replot(QCustomPlot::RefreshPriority refreshPriority=QCustomPlot::rpHint); + + QCPAxis *xAxis, *yAxis, *xAxis2, *yAxis2; + QCPLegend *legend; + +signals: + void mouseDoubleClick(QMouseEvent *event); + void mousePress(QMouseEvent *event); + void mouseMove(QMouseEvent *event); + void mouseRelease(QMouseEvent *event); + void mouseWheel(QWheelEvent *event); + + void plottableClick(QCPAbstractPlottable *plottable, QMouseEvent *event); + void plottableDoubleClick(QCPAbstractPlottable *plottable, QMouseEvent *event); + void itemClick(QCPAbstractItem *item, QMouseEvent *event); + void itemDoubleClick(QCPAbstractItem *item, QMouseEvent *event); + void axisClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); + void axisDoubleClick(QCPAxis *axis, QCPAxis::SelectablePart part, QMouseEvent *event); + void legendClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); + void legendDoubleClick(QCPLegend *legend, QCPAbstractLegendItem *item, QMouseEvent *event); + void titleClick(QMouseEvent *event, QCPPlotTitle *title); + void titleDoubleClick(QMouseEvent *event, QCPPlotTitle *title); + + void selectionChangedByUser(); + void beforeReplot(); + void afterReplot(); + +protected: + // property members: + QRect mViewport; + QCPLayoutGrid *mPlotLayout; + bool mAutoAddPlottableToLegend; + QList mPlottables; + QList mGraphs; // extra list of plottables also in mPlottables that are of type QCPGraph + QList mItems; + QList mLayers; + QCP::AntialiasedElements mAntialiasedElements, mNotAntialiasedElements; + QCP::Interactions mInteractions; + int mSelectionTolerance; + bool mNoAntialiasingOnDrag; + QBrush mBackgroundBrush; + QPixmap mBackgroundPixmap; + QPixmap mScaledBackgroundPixmap; + bool mBackgroundScaled; + Qt::AspectRatioMode mBackgroundScaledMode; + QCPLayer *mCurrentLayer; + QCP::PlottingHints mPlottingHints; + Qt::KeyboardModifier mMultiSelectModifier; + + // non-property members: + QPixmap mPaintBuffer; + QPoint mMousePressPos; + QPointer mMouseEventElement; + bool mReplotting; + + // reimplemented virtual methods: + virtual QSize minimumSizeHint() const; + virtual QSize sizeHint() const; + virtual void paintEvent(QPaintEvent *event); + virtual void resizeEvent(QResizeEvent *event); + virtual void mouseDoubleClickEvent(QMouseEvent *event); + virtual void mousePressEvent(QMouseEvent *event); + virtual void mouseMoveEvent(QMouseEvent *event); + virtual void mouseReleaseEvent(QMouseEvent *event); + virtual void wheelEvent(QWheelEvent *event); + + // introduced virtual methods: + virtual void draw(QCPPainter *painter); + virtual void axisRemoved(QCPAxis *axis); + virtual void legendRemoved(QCPLegend *legend); + + // non-virtual methods: + void updateLayerIndices() const; + QCPLayerable *layerableAt(const QPointF &pos, bool onlySelectable, QVariant *selectionDetails=0) const; + void drawBackground(QCPPainter *painter); + + friend class QCPLegend; + friend class QCPAxis; + friend class QCPLayer; + friend class QCPAxisRect; +}; + + +class QCP_LIB_DECL QCPColorGradient +{ + Q_GADGET +public: + /*! + Defines the color spaces in which color interpolation between gradient stops can be performed. + + \see setColorInterpolation + */ + enum ColorInterpolation { ciRGB ///< Color channels red, green and blue are linearly interpolated + ,ciHSV ///< Color channels hue, saturation and value are linearly interpolated (The hue is interpolated over the shortest angle distance) + }; + Q_ENUMS(ColorInterpolation) + + /*! + Defines the available presets that can be loaded with \ref loadPreset. See the documentation + there for an image of the presets. + */ + enum GradientPreset { gpGrayscale ///< Continuous lightness from black to white (suited for non-biased data representation) + ,gpHot ///< Continuous lightness from black over firey colors to white (suited for non-biased data representation) + ,gpCold ///< Continuous lightness from black over icey colors to white (suited for non-biased data representation) + ,gpNight ///< Continuous lightness from black over weak blueish colors to white (suited for non-biased data representation) + ,gpCandy ///< Blue over pink to white + ,gpGeography ///< Colors suitable to represent different elevations on geographical maps + ,gpIon ///< Half hue spectrum from black over purple to blue and finally green (creates banding illusion but allows more precise magnitude estimates) + ,gpThermal ///< Colors suitable for thermal imaging, ranging from dark blue over purple to orange, yellow and white + ,gpPolar ///< Colors suitable to emphasize polarity around the center, with blue for negative, black in the middle and red for positive values + ,gpSpectrum ///< An approximation of the visible light spectrum (creates banding illusion but allows more precise magnitude estimates) + ,gpJet ///< Hue variation similar to a spectrum, often used in numerical visualization (creates banding illusion but allows more precise magnitude estimates) + ,gpHues ///< Full hue cycle, with highest and lowest color red (suitable for periodic data, such as angles and phases, see \ref setPeriodic) + }; + Q_ENUMS(GradientPreset) + + QCPColorGradient(GradientPreset preset=gpCold); + bool operator==(const QCPColorGradient &other) const; + bool operator!=(const QCPColorGradient &other) const { return !(*this == other); } + + // getters: + int levelCount() const { return mLevelCount; } + QMap colorStops() const { return mColorStops; } + ColorInterpolation colorInterpolation() const { return mColorInterpolation; } + bool periodic() const { return mPeriodic; } + + // setters: + void setLevelCount(int n); + void setColorStops(const QMap &colorStops); + void setColorStopAt(double position, const QColor &color); + void setColorInterpolation(ColorInterpolation interpolation); + void setPeriodic(bool enabled); + + // non-property methods: + void colorize(const double *data, const QCPRange &range, QRgb *scanLine, int n, int dataIndexFactor=1, bool logarithmic=false); + QRgb color(double position, const QCPRange &range, bool logarithmic=false); + void loadPreset(GradientPreset preset); + void clearColorStops(); + QCPColorGradient inverted() const; + +protected: + void updateColorBuffer(); + + // property members: + int mLevelCount; + QMap mColorStops; + ColorInterpolation mColorInterpolation; + bool mPeriodic; + + // non-property members: + QVector mColorBuffer; + bool mColorBufferInvalidated; +}; + + +class QCP_LIB_DECL QCPAxisRect : public QCPLayoutElement +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPixmap background READ background WRITE setBackground) + Q_PROPERTY(bool backgroundScaled READ backgroundScaled WRITE setBackgroundScaled) + Q_PROPERTY(Qt::AspectRatioMode backgroundScaledMode READ backgroundScaledMode WRITE setBackgroundScaledMode) + Q_PROPERTY(Qt::Orientations rangeDrag READ rangeDrag WRITE setRangeDrag) + Q_PROPERTY(Qt::Orientations rangeZoom READ rangeZoom WRITE setRangeZoom) + /// \endcond +public: + explicit QCPAxisRect(QCustomPlot *parentPlot, bool setupDefaultAxes=true); + virtual ~QCPAxisRect(); + + // getters: + QPixmap background() const { return mBackgroundPixmap; } + bool backgroundScaled() const { return mBackgroundScaled; } + Qt::AspectRatioMode backgroundScaledMode() const { return mBackgroundScaledMode; } + Qt::Orientations rangeDrag() const { return mRangeDrag; } + Qt::Orientations rangeZoom() const { return mRangeZoom; } + QCPAxis *rangeDragAxis(Qt::Orientation orientation); + QCPAxis *rangeZoomAxis(Qt::Orientation orientation); + double rangeZoomFactor(Qt::Orientation orientation); + + // setters: + void setBackground(const QPixmap &pm); + void setBackground(const QPixmap &pm, bool scaled, Qt::AspectRatioMode mode=Qt::KeepAspectRatioByExpanding); + void setBackground(const QBrush &brush); + void setBackgroundScaled(bool scaled); + void setBackgroundScaledMode(Qt::AspectRatioMode mode); + void setRangeDrag(Qt::Orientations orientations); + void setRangeZoom(Qt::Orientations orientations); + void setRangeDragAxes(QCPAxis *horizontal, QCPAxis *vertical); + void setRangeZoomAxes(QCPAxis *horizontal, QCPAxis *vertical); + void setRangeZoomFactor(double horizontalFactor, double verticalFactor); + void setRangeZoomFactor(double factor); + + // non-property methods: + int axisCount(QCPAxis::AxisType type) const; + QCPAxis *axis(QCPAxis::AxisType type, int index=0) const; + QList axes(QCPAxis::AxisTypes types) const; + QList axes() const; + QCPAxis *addAxis(QCPAxis::AxisType type); + QList addAxes(QCPAxis::AxisTypes types); + bool removeAxis(QCPAxis *axis); + QCPLayoutInset *insetLayout() const { return mInsetLayout; } + + void setupFullAxesBox(bool connectRanges=false); + QList plottables() const; + QList graphs() const; + QList items() const; + + // read-only interface imitating a QRect: + int left() const { return mRect.left(); } + int right() const { return mRect.right(); } + int top() const { return mRect.top(); } + int bottom() const { return mRect.bottom(); } + int width() const { return mRect.width(); } + int height() const { return mRect.height(); } + QSize size() const { return mRect.size(); } + QPoint topLeft() const { return mRect.topLeft(); } + QPoint topRight() const { return mRect.topRight(); } + QPoint bottomLeft() const { return mRect.bottomLeft(); } + QPoint bottomRight() const { return mRect.bottomRight(); } + QPoint center() const { return mRect.center(); } + + // reimplemented virtual methods: + virtual void update(UpdatePhase phase); + virtual QList elements(bool recursive) const; + +protected: + // property members: + QBrush mBackgroundBrush; + QPixmap mBackgroundPixmap; + QPixmap mScaledBackgroundPixmap; + bool mBackgroundScaled; + Qt::AspectRatioMode mBackgroundScaledMode; + QCPLayoutInset *mInsetLayout; + Qt::Orientations mRangeDrag, mRangeZoom; + QPointer mRangeDragHorzAxis, mRangeDragVertAxis, mRangeZoomHorzAxis, mRangeZoomVertAxis; + double mRangeZoomFactorHorz, mRangeZoomFactorVert; + // non-property members: + QCPRange mDragStartHorzRange, mDragStartVertRange; + QCP::AntialiasedElements mAADragBackup, mNotAADragBackup; + QPoint mDragStart; + bool mDragging; + QHash > mAxes; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + virtual void draw(QCPPainter *painter); + virtual int calculateAutoMargin(QCP::MarginSide side); + // events: + virtual void mousePressEvent(QMouseEvent *event); + virtual void mouseMoveEvent(QMouseEvent *event); + virtual void mouseReleaseEvent(QMouseEvent *event); + virtual void wheelEvent(QWheelEvent *event); + + // non-property methods: + void drawBackground(QCPPainter *painter); + void updateAxesOffset(QCPAxis::AxisType type); + +private: + Q_DISABLE_COPY(QCPAxisRect) + + friend class QCustomPlot; +}; + + +class QCP_LIB_DECL QCPAbstractLegendItem : public QCPLayoutElement +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCPLegend* parentLegend READ parentLegend) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectionChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectableChanged) + /// \endcond +public: + explicit QCPAbstractLegendItem(QCPLegend *parent); + + // getters: + QCPLegend *parentLegend() const { return mParentLegend; } + QFont font() const { return mFont; } + QColor textColor() const { return mTextColor; } + QFont selectedFont() const { return mSelectedFont; } + QColor selectedTextColor() const { return mSelectedTextColor; } + bool selectable() const { return mSelectable; } + bool selected() const { return mSelected; } + + // setters: + void setFont(const QFont &font); + void setTextColor(const QColor &color); + void setSelectedFont(const QFont &font); + void setSelectedTextColor(const QColor &color); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + +signals: + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + +protected: + // property members: + QCPLegend *mParentLegend; + QFont mFont; + QColor mTextColor; + QFont mSelectedFont; + QColor mSelectedTextColor; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + virtual QCP::Interaction selectionCategory() const; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + virtual QRect clipRect() const; + virtual void draw(QCPPainter *painter) = 0; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + +private: + Q_DISABLE_COPY(QCPAbstractLegendItem) + + friend class QCPLegend; +}; + + +class QCP_LIB_DECL QCPPlottableLegendItem : public QCPAbstractLegendItem +{ + Q_OBJECT +public: + QCPPlottableLegendItem(QCPLegend *parent, QCPAbstractPlottable *plottable); + + // getters: + QCPAbstractPlottable *plottable() { return mPlottable; } + +protected: + // property members: + QCPAbstractPlottable *mPlottable; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QSize minimumSizeHint() const; + + // non-virtual methods: + QPen getIconBorderPen() const; + QColor getTextColor() const; + QFont getFont() const; +}; + + +class QCP_LIB_DECL QCPLegend : public QCPLayoutGrid +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen borderPen READ borderPen WRITE setBorderPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QSize iconSize READ iconSize WRITE setIconSize) + Q_PROPERTY(int iconTextPadding READ iconTextPadding WRITE setIconTextPadding) + Q_PROPERTY(QPen iconBorderPen READ iconBorderPen WRITE setIconBorderPen) + Q_PROPERTY(SelectableParts selectableParts READ selectableParts WRITE setSelectableParts NOTIFY selectionChanged) + Q_PROPERTY(SelectableParts selectedParts READ selectedParts WRITE setSelectedParts NOTIFY selectableChanged) + Q_PROPERTY(QPen selectedBorderPen READ selectedBorderPen WRITE setSelectedBorderPen) + Q_PROPERTY(QPen selectedIconBorderPen READ selectedIconBorderPen WRITE setSelectedIconBorderPen) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + /// \endcond +public: + /*! + Defines the selectable parts of a legend + + \see setSelectedParts, setSelectableParts + */ + enum SelectablePart { spNone = 0x000 ///< 0x000 None + ,spLegendBox = 0x001 ///< 0x001 The legend box (frame) + ,spItems = 0x002 ///< 0x002 Legend items individually (see \ref selectedItems) + }; + Q_FLAGS(SelectablePart SelectableParts) + Q_DECLARE_FLAGS(SelectableParts, SelectablePart) + + explicit QCPLegend(); + virtual ~QCPLegend(); + + // getters: + QPen borderPen() const { return mBorderPen; } + QBrush brush() const { return mBrush; } + QFont font() const { return mFont; } + QColor textColor() const { return mTextColor; } + QSize iconSize() const { return mIconSize; } + int iconTextPadding() const { return mIconTextPadding; } + QPen iconBorderPen() const { return mIconBorderPen; } + SelectableParts selectableParts() const { return mSelectableParts; } + SelectableParts selectedParts() const; + QPen selectedBorderPen() const { return mSelectedBorderPen; } + QPen selectedIconBorderPen() const { return mSelectedIconBorderPen; } + QBrush selectedBrush() const { return mSelectedBrush; } + QFont selectedFont() const { return mSelectedFont; } + QColor selectedTextColor() const { return mSelectedTextColor; } + + // setters: + void setBorderPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setFont(const QFont &font); + void setTextColor(const QColor &color); + void setIconSize(const QSize &size); + void setIconSize(int width, int height); + void setIconTextPadding(int padding); + void setIconBorderPen(const QPen &pen); + Q_SLOT void setSelectableParts(const SelectableParts &selectableParts); + Q_SLOT void setSelectedParts(const SelectableParts &selectedParts); + void setSelectedBorderPen(const QPen &pen); + void setSelectedIconBorderPen(const QPen &pen); + void setSelectedBrush(const QBrush &brush); + void setSelectedFont(const QFont &font); + void setSelectedTextColor(const QColor &color); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + // non-virtual methods: + QCPAbstractLegendItem *item(int index) const; + QCPPlottableLegendItem *itemWithPlottable(const QCPAbstractPlottable *plottable) const; + int itemCount() const; + bool hasItem(QCPAbstractLegendItem *item) const; + bool hasItemWithPlottable(const QCPAbstractPlottable *plottable) const; + bool addItem(QCPAbstractLegendItem *item); + bool removeItem(int index); + bool removeItem(QCPAbstractLegendItem *item); + void clearItems(); + QList selectedItems() const; + +signals: + void selectionChanged(QCPLegend::SelectableParts parts); + void selectableChanged(QCPLegend::SelectableParts parts); + +protected: + // property members: + QPen mBorderPen, mIconBorderPen; + QBrush mBrush; + QFont mFont; + QColor mTextColor; + QSize mIconSize; + int mIconTextPadding; + SelectableParts mSelectedParts, mSelectableParts; + QPen mSelectedBorderPen, mSelectedIconBorderPen; + QBrush mSelectedBrush; + QFont mSelectedFont; + QColor mSelectedTextColor; + + // reimplemented virtual methods: + virtual void parentPlotInitialized(QCustomPlot *parentPlot); + virtual QCP::Interaction selectionCategory() const; + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + virtual void draw(QCPPainter *painter); + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // non-virtual methods: + QPen getBorderPen() const; + QBrush getBrush() const; + +private: + Q_DISABLE_COPY(QCPLegend) + + friend class QCustomPlot; + friend class QCPAbstractLegendItem; +}; +Q_DECLARE_OPERATORS_FOR_FLAGS(QCPLegend::SelectableParts) +Q_DECLARE_METATYPE(QCPLegend::SelectablePart) + + +class QCP_LIB_DECL QCPPlotTitle : public QCPLayoutElement +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QString text READ text WRITE setText) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QColor textColor READ textColor WRITE setTextColor) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QColor selectedTextColor READ selectedTextColor WRITE setSelectedTextColor) + Q_PROPERTY(bool selectable READ selectable WRITE setSelectable NOTIFY selectableChanged) + Q_PROPERTY(bool selected READ selected WRITE setSelected NOTIFY selectionChanged) + /// \endcond +public: + explicit QCPPlotTitle(QCustomPlot *parentPlot); + explicit QCPPlotTitle(QCustomPlot *parentPlot, const QString &text); + + // getters: + QString text() const { return mText; } + QFont font() const { return mFont; } + QColor textColor() const { return mTextColor; } + QFont selectedFont() const { return mSelectedFont; } + QColor selectedTextColor() const { return mSelectedTextColor; } + bool selectable() const { return mSelectable; } + bool selected() const { return mSelected; } + + // setters: + void setText(const QString &text); + void setFont(const QFont &font); + void setTextColor(const QColor &color); + void setSelectedFont(const QFont &font); + void setSelectedTextColor(const QColor &color); + Q_SLOT void setSelectable(bool selectable); + Q_SLOT void setSelected(bool selected); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + +signals: + void selectionChanged(bool selected); + void selectableChanged(bool selectable); + +protected: + // property members: + QString mText; + QFont mFont; + QColor mTextColor; + QFont mSelectedFont; + QColor mSelectedTextColor; + QRect mTextBoundingRect; + bool mSelectable, mSelected; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + virtual void draw(QCPPainter *painter); + virtual QSize minimumSizeHint() const; + virtual QSize maximumSizeHint() const; + // events: + virtual void selectEvent(QMouseEvent *event, bool additive, const QVariant &details, bool *selectionStateChanged); + virtual void deselectEvent(bool *selectionStateChanged); + + // non-virtual methods: + QFont mainFont() const; + QColor mainTextColor() const; + +private: + Q_DISABLE_COPY(QCPPlotTitle) +}; + + +class QCPColorScaleAxisRectPrivate : public QCPAxisRect +{ + Q_OBJECT +public: + explicit QCPColorScaleAxisRectPrivate(QCPColorScale *parentColorScale); +protected: + QCPColorScale *mParentColorScale; + QImage mGradientImage; + bool mGradientImageInvalidated; + // re-using some methods of QCPAxisRect to make them available to friend class QCPColorScale + using QCPAxisRect::calculateAutoMargin; + using QCPAxisRect::mousePressEvent; + using QCPAxisRect::mouseMoveEvent; + using QCPAxisRect::mouseReleaseEvent; + using QCPAxisRect::wheelEvent; + using QCPAxisRect::update; + virtual void draw(QCPPainter *painter); + void updateGradientImage(); + Q_SLOT void axisSelectionChanged(QCPAxis::SelectableParts selectedParts); + Q_SLOT void axisSelectableChanged(QCPAxis::SelectableParts selectableParts); + friend class QCPColorScale; +}; + + +class QCP_LIB_DECL QCPColorScale : public QCPLayoutElement +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCPAxis::AxisType type READ type WRITE setType) + Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) + Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) + Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) + Q_PROPERTY(QString label READ label WRITE setLabel) + Q_PROPERTY(int barWidth READ barWidth WRITE setBarWidth) + Q_PROPERTY(bool rangeDrag READ rangeDrag WRITE setRangeDrag) + Q_PROPERTY(bool rangeZoom READ rangeZoom WRITE setRangeZoom) + /// \endcond +public: + explicit QCPColorScale(QCustomPlot *parentPlot); + virtual ~QCPColorScale(); + + // getters: + QCPAxis *axis() const { return mColorAxis.data(); } + QCPAxis::AxisType type() const { return mType; } + QCPRange dataRange() const { return mDataRange; } + QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } + QCPColorGradient gradient() const { return mGradient; } + QString label() const; + int barWidth () const { return mBarWidth; } + bool rangeDrag() const; + bool rangeZoom() const; + + // setters: + void setType(QCPAxis::AxisType type); + Q_SLOT void setDataRange(const QCPRange &dataRange); + Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); + Q_SLOT void setGradient(const QCPColorGradient &gradient); + void setLabel(const QString &str); + void setBarWidth(int width); + void setRangeDrag(bool enabled); + void setRangeZoom(bool enabled); + + // non-property methods: + QList colorMaps() const; + void rescaleDataRange(bool onlyVisibleMaps); + + // reimplemented virtual methods: + virtual void update(UpdatePhase phase); + +signals: + void dataRangeChanged(QCPRange newRange); + void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + void gradientChanged(QCPColorGradient newGradient); + +protected: + // property members: + QCPAxis::AxisType mType; + QCPRange mDataRange; + QCPAxis::ScaleType mDataScaleType; + QCPColorGradient mGradient; + int mBarWidth; + + // non-property members: + QPointer mAxisRect; + QPointer mColorAxis; + + // reimplemented virtual methods: + virtual void applyDefaultAntialiasingHint(QCPPainter *painter) const; + // events: + virtual void mousePressEvent(QMouseEvent *event); + virtual void mouseMoveEvent(QMouseEvent *event); + virtual void mouseReleaseEvent(QMouseEvent *event); + virtual void wheelEvent(QWheelEvent *event); + +private: + Q_DISABLE_COPY(QCPColorScale) + + friend class QCPColorScaleAxisRectPrivate; +}; + + +/*! \file */ + + + +class QCP_LIB_DECL QCPData +{ +public: + QCPData(); + QCPData(double key, double value); + double key, value; + double keyErrorPlus, keyErrorMinus; + double valueErrorPlus, valueErrorMinus; +}; +Q_DECLARE_TYPEINFO(QCPData, Q_MOVABLE_TYPE); + +/*! \typedef QCPDataMap + Container for storing \ref QCPData items in a sorted fashion. The key of the map + is the key member of the QCPData instance. + + This is the container in which QCPGraph holds its data. + \see QCPData, QCPGraph::setData +*/ +typedef QMap QCPDataMap; +typedef QMapIterator QCPDataMapIterator; +typedef QMutableMapIterator QCPDataMutableMapIterator; + + +class QCP_LIB_DECL QCPGraph : public QCPAbstractPlottable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) + Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) + Q_PROPERTY(ErrorType errorType READ errorType WRITE setErrorType) + Q_PROPERTY(QPen errorPen READ errorPen WRITE setErrorPen) + Q_PROPERTY(double errorBarSize READ errorBarSize WRITE setErrorBarSize) + Q_PROPERTY(bool errorBarSkipSymbol READ errorBarSkipSymbol WRITE setErrorBarSkipSymbol) + Q_PROPERTY(QCPGraph* channelFillGraph READ channelFillGraph WRITE setChannelFillGraph) + Q_PROPERTY(bool adaptiveSampling READ adaptiveSampling WRITE setAdaptiveSampling) + /// \endcond +public: + /*! + Defines how the graph's line is represented visually in the plot. The line is drawn with the + current pen of the graph (\ref setPen). + \see setLineStyle + */ + enum LineStyle { lsNone ///< data points are not connected with any lines (e.g. data only represented + ///< with symbols according to the scatter style, see \ref setScatterStyle) + ,lsLine ///< data points are connected by a straight line + ,lsStepLeft ///< line is drawn as steps where the step height is the value of the left data point + ,lsStepRight ///< line is drawn as steps where the step height is the value of the right data point + ,lsStepCenter ///< line is drawn as steps where the step is in between two data points + ,lsImpulse ///< each data point is represented by a line parallel to the value axis, which reaches from the data point to the zero-value-line + }; + Q_ENUMS(LineStyle) + /*! + Defines what kind of error bars are drawn for each data point + */ + enum ErrorType { etNone ///< No error bars are shown + ,etKey ///< Error bars for the key dimension of the data point are shown + ,etValue ///< Error bars for the value dimension of the data point are shown + ,etBoth ///< Error bars for both key and value dimensions of the data point are shown + }; + Q_ENUMS(ErrorType) + + explicit QCPGraph(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPGraph(); + + // getters: + QCPDataMap *data() const { return mData; } + LineStyle lineStyle() const { return mLineStyle; } + QCPScatterStyle scatterStyle() const { return mScatterStyle; } + ErrorType errorType() const { return mErrorType; } + QPen errorPen() const { return mErrorPen; } + double errorBarSize() const { return mErrorBarSize; } + bool errorBarSkipSymbol() const { return mErrorBarSkipSymbol; } + QCPGraph *channelFillGraph() const { return mChannelFillGraph.data(); } + bool adaptiveSampling() const { return mAdaptiveSampling; } + + // setters: + void setData(QCPDataMap *data, bool copy=false); + void setData(const QVector &key, const QVector &value); + void setDataKeyError(const QVector &key, const QVector &value, const QVector &keyError); + void setDataKeyError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus); + void setDataValueError(const QVector &key, const QVector &value, const QVector &valueError); + void setDataValueError(const QVector &key, const QVector &value, const QVector &valueErrorMinus, const QVector &valueErrorPlus); + void setDataBothError(const QVector &key, const QVector &value, const QVector &keyError, const QVector &valueError); + void setDataBothError(const QVector &key, const QVector &value, const QVector &keyErrorMinus, const QVector &keyErrorPlus, const QVector &valueErrorMinus, const QVector &valueErrorPlus); + void setLineStyle(LineStyle ls); + void setScatterStyle(const QCPScatterStyle &style); + void setErrorType(ErrorType errorType); + void setErrorPen(const QPen &pen); + void setErrorBarSize(double size); + void setErrorBarSkipSymbol(bool enabled); + void setChannelFillGraph(QCPGraph *targetGraph); + void setAdaptiveSampling(bool enabled); + + // non-property methods: + void addData(const QCPDataMap &dataMap); + void addData(const QCPData &data); + void addData(double key, double value); + void addData(const QVector &keys, const QVector &values); + void removeDataBefore(double key); + void removeDataAfter(double key); + void removeData(double fromKey, double toKey); + void removeData(double key); + + // reimplemented virtual methods: + virtual void clearData(); + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + using QCPAbstractPlottable::rescaleAxes; + using QCPAbstractPlottable::rescaleKeyAxis; + using QCPAbstractPlottable::rescaleValueAxis; + void rescaleAxes(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface + void rescaleKeyAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface + void rescaleValueAxis(bool onlyEnlarge, bool includeErrorBars) const; // overloads base class interface + +protected: + // property members: + QCPDataMap *mData; + QPen mErrorPen; + LineStyle mLineStyle; + QCPScatterStyle mScatterStyle; + ErrorType mErrorType; + double mErrorBarSize; + bool mErrorBarSkipSymbol; + QPointer mChannelFillGraph; + bool mAdaptiveSampling; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; + virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface + virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain, bool includeErrors) const; // overloads base class interface + + // introduced virtual methods: + virtual void drawFill(QCPPainter *painter, QVector *lineData) const; + virtual void drawScatterPlot(QCPPainter *painter, QVector *scatterData) const; + virtual void drawLinePlot(QCPPainter *painter, QVector *lineData) const; + virtual void drawImpulsePlot(QCPPainter *painter, QVector *lineData) const; + + // non-virtual methods: + void getPreparedData(QVector *lineData, QVector *scatterData) const; + void getPlotData(QVector *lineData, QVector *scatterData) const; + void getScatterPlotData(QVector *scatterData) const; + void getLinePlotData(QVector *linePixelData, QVector *scatterData) const; + void getStepLeftPlotData(QVector *linePixelData, QVector *scatterData) const; + void getStepRightPlotData(QVector *linePixelData, QVector *scatterData) const; + void getStepCenterPlotData(QVector *linePixelData, QVector *scatterData) const; + void getImpulsePlotData(QVector *linePixelData, QVector *scatterData) const; + void drawError(QCPPainter *painter, double x, double y, const QCPData &data) const; + void getVisibleDataBounds(QCPDataMap::const_iterator &lower, QCPDataMap::const_iterator &upper) const; + int countDataInBounds(const QCPDataMap::const_iterator &lower, const QCPDataMap::const_iterator &upper, int maxCount) const; + void addFillBasePoints(QVector *lineData) const; + void removeFillBasePoints(QVector *lineData) const; + QPointF lowerFillBasePoint(double lowerKey) const; + QPointF upperFillBasePoint(double upperKey) const; + const QPolygonF getChannelFillPolygon(const QVector *lineData) const; + int findIndexBelowX(const QVector *data, double x) const; + int findIndexAboveX(const QVector *data, double x) const; + int findIndexBelowY(const QVector *data, double y) const; + int findIndexAboveY(const QVector *data, double y) const; + double pointDistance(const QPointF &pixelPoint) const; + + friend class QCustomPlot; + friend class QCPLegend; +}; + + +/*! \file */ + + + +class QCP_LIB_DECL QCPCurveData +{ +public: + QCPCurveData(); + QCPCurveData(double t, double key, double value); + double t, key, value; +}; +Q_DECLARE_TYPEINFO(QCPCurveData, Q_MOVABLE_TYPE); + +/*! \typedef QCPCurveDataMap + Container for storing \ref QCPCurveData items in a sorted fashion. The key of the map + is the t member of the QCPCurveData instance. + + This is the container in which QCPCurve holds its data. + \see QCPCurveData, QCPCurve::setData +*/ + +typedef QMap QCPCurveDataMap; +typedef QMapIterator QCPCurveDataMapIterator; +typedef QMutableMapIterator QCPCurveDataMutableMapIterator; + + +class QCP_LIB_DECL QCPCurve : public QCPAbstractPlottable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCPScatterStyle scatterStyle READ scatterStyle WRITE setScatterStyle) + Q_PROPERTY(LineStyle lineStyle READ lineStyle WRITE setLineStyle) + /// \endcond +public: + /*! + Defines how the curve's line is represented visually in the plot. The line is drawn with the + current pen of the curve (\ref setPen). + \see setLineStyle + */ + enum LineStyle { lsNone ///< No line is drawn between data points (e.g. only scatters) + ,lsLine ///< Data points are connected with a straight line + }; + explicit QCPCurve(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPCurve(); + + // getters: + QCPCurveDataMap *data() const { return mData; } + QCPScatterStyle scatterStyle() const { return mScatterStyle; } + LineStyle lineStyle() const { return mLineStyle; } + + // setters: + void setData(QCPCurveDataMap *data, bool copy=false); + void setData(const QVector &t, const QVector &key, const QVector &value); + void setData(const QVector &key, const QVector &value); + void setScatterStyle(const QCPScatterStyle &style); + void setLineStyle(LineStyle style); + + // non-property methods: + void addData(const QCPCurveDataMap &dataMap); + void addData(const QCPCurveData &data); + void addData(double t, double key, double value); + void addData(double key, double value); + void addData(const QVector &ts, const QVector &keys, const QVector &values); + void removeDataBefore(double t); + void removeDataAfter(double t); + void removeData(double fromt, double tot); + void removeData(double t); + + // reimplemented virtual methods: + virtual void clearData(); + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + +protected: + // property members: + QCPCurveDataMap *mData; + QCPScatterStyle mScatterStyle; + LineStyle mLineStyle; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; + virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + + // introduced virtual methods: + virtual void drawScatterPlot(QCPPainter *painter, const QVector *pointData) const; + + // non-virtual methods: + void getCurveData(QVector *lineData) const; + int getRegion(double x, double y, double rectLeft, double rectTop, double rectRight, double rectBottom) const; + QPointF getOptimizedPoint(int prevRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const; + QVector getOptimizedCornerPoints(int prevRegion, int currentRegion, double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom) const; + bool mayTraverse(int prevRegion, int currentRegion) const; + bool getTraverse(double prevKey, double prevValue, double key, double value, double rectLeft, double rectTop, double rectRight, double rectBottom, QPointF &crossA, QPointF &crossB) const; + void getTraverseCornerPoints(int prevRegion, int currentRegion, double rectLeft, double rectTop, double rectRight, double rectBottom, QVector &beforeTraverse, QVector &afterTraverse) const; + double pointDistance(const QPointF &pixelPoint) const; + + friend class QCustomPlot; + friend class QCPLegend; +}; + + +/*! \file */ + + + +class QCP_LIB_DECL QCPBarsGroup : public QObject +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(SpacingType spacingType READ spacingType WRITE setSpacingType) + Q_PROPERTY(double spacing READ spacing WRITE setSpacing) + /// \endcond +public: + /*! + Defines the ways the spacing between bars in the group can be specified. Thus it defines what + the number passed to \ref setSpacing actually means. + + \see setSpacingType, setSpacing + */ + enum SpacingType { stAbsolute ///< Bar spacing is in absolute pixels + ,stAxisRectRatio ///< Bar spacing is given by a fraction of the axis rect size + ,stPlotCoords ///< Bar spacing is in key coordinates and thus scales with the key axis range + }; + QCPBarsGroup(QCustomPlot *parentPlot); + ~QCPBarsGroup(); + + // getters: + SpacingType spacingType() const { return mSpacingType; } + double spacing() const { return mSpacing; } + + // setters: + void setSpacingType(SpacingType spacingType); + void setSpacing(double spacing); + + // non-virtual methods: + QList bars() const { return mBars; } + QCPBars* bars(int index) const; + int size() const { return mBars.size(); } + bool isEmpty() const { return mBars.isEmpty(); } + void clear(); + bool contains(QCPBars *bars) const { return mBars.contains(bars); } + void append(QCPBars *bars); + void insert(int i, QCPBars *bars); + void remove(QCPBars *bars); + +protected: + // non-property members: + QCustomPlot *mParentPlot; + SpacingType mSpacingType; + double mSpacing; + QList mBars; + + // non-virtual methods: + void registerBars(QCPBars *bars); + void unregisterBars(QCPBars *bars); + + // virtual methods: + double keyPixelOffset(const QCPBars *bars, double keyCoord); + double getPixelSpacing(const QCPBars *bars, double keyCoord); + +private: + Q_DISABLE_COPY(QCPBarsGroup) + + friend class QCPBars; +}; + + +class QCP_LIB_DECL QCPBarData +{ +public: + QCPBarData(); + QCPBarData(double key, double value); + double key, value; +}; +Q_DECLARE_TYPEINFO(QCPBarData, Q_MOVABLE_TYPE); + +/*! \typedef QCPBarDataMap + Container for storing \ref QCPBarData items in a sorted fashion. The key of the map + is the key member of the QCPBarData instance. + + This is the container in which QCPBars holds its data. + \see QCPBarData, QCPBars::setData +*/ +typedef QMap QCPBarDataMap; +typedef QMapIterator QCPBarDataMapIterator; +typedef QMutableMapIterator QCPBarDataMutableMapIterator; + + +class QCP_LIB_DECL QCPBars : public QCPAbstractPlottable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(double width READ width WRITE setWidth) + Q_PROPERTY(WidthType widthType READ widthType WRITE setWidthType) + Q_PROPERTY(QCPBarsGroup* barsGroup READ barsGroup WRITE setBarsGroup) + Q_PROPERTY(double baseValue READ baseValue WRITE setBaseValue) + Q_PROPERTY(QCPBars* barBelow READ barBelow) + Q_PROPERTY(QCPBars* barAbove READ barAbove) + /// \endcond +public: + /*! + Defines the ways the width of the bar can be specified. Thus it defines what the number passed + to \ref setWidth actually means. + + \see setWidthType, setWidth + */ + enum WidthType { wtAbsolute ///< Bar width is in absolute pixels + ,wtAxisRectRatio ///< Bar width is given by a fraction of the axis rect size + ,wtPlotCoords ///< Bar width is in key coordinates and thus scales with the key axis range + }; + Q_ENUMS(WidthType) + + explicit QCPBars(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPBars(); + + // getters: + double width() const { return mWidth; } + WidthType widthType() const { return mWidthType; } + QCPBarsGroup *barsGroup() const { return mBarsGroup; } + double baseValue() const { return mBaseValue; } + QCPBars *barBelow() const { return mBarBelow.data(); } + QCPBars *barAbove() const { return mBarAbove.data(); } + QCPBarDataMap *data() const { return mData; } + + // setters: + void setWidth(double width); + void setWidthType(WidthType widthType); + void setBarsGroup(QCPBarsGroup *barsGroup); + void setBaseValue(double baseValue); + void setData(QCPBarDataMap *data, bool copy=false); + void setData(const QVector &key, const QVector &value); + + // non-property methods: + void moveBelow(QCPBars *bars); + void moveAbove(QCPBars *bars); + void addData(const QCPBarDataMap &dataMap); + void addData(const QCPBarData &data); + void addData(double key, double value); + void addData(const QVector &keys, const QVector &values); + void removeDataBefore(double key); + void removeDataAfter(double key); + void removeData(double fromKey, double toKey); + void removeData(double key); + + // reimplemented virtual methods: + virtual void clearData(); + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + +protected: + // property members: + QCPBarDataMap *mData; + double mWidth; + WidthType mWidthType; + QCPBarsGroup *mBarsGroup; + double mBaseValue; + QPointer mBarBelow, mBarAbove; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; + virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + + // non-virtual methods: + void getVisibleDataBounds(QCPBarDataMap::const_iterator &lower, QCPBarDataMap::const_iterator &upperEnd) const; + QPolygonF getBarPolygon(double key, double value) const; + void getPixelWidth(double key, double &lower, double &upper) const; + double getStackedBaseValue(double key, bool positive) const; + static void connectBars(QCPBars* lower, QCPBars* upper); + + friend class QCustomPlot; + friend class QCPLegend; + friend class QCPBarsGroup; +}; + + +/*! \file */ + + + +class QCP_LIB_DECL QCPStatisticalBox : public QCPAbstractPlottable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(double key READ key WRITE setKey) + Q_PROPERTY(double minimum READ minimum WRITE setMinimum) + Q_PROPERTY(double lowerQuartile READ lowerQuartile WRITE setLowerQuartile) + Q_PROPERTY(double median READ median WRITE setMedian) + Q_PROPERTY(double upperQuartile READ upperQuartile WRITE setUpperQuartile) + Q_PROPERTY(double maximum READ maximum WRITE setMaximum) + Q_PROPERTY(QVector outliers READ outliers WRITE setOutliers) + Q_PROPERTY(double width READ width WRITE setWidth) + Q_PROPERTY(double whiskerWidth READ whiskerWidth WRITE setWhiskerWidth) + Q_PROPERTY(QPen whiskerPen READ whiskerPen WRITE setWhiskerPen) + Q_PROPERTY(QPen whiskerBarPen READ whiskerBarPen WRITE setWhiskerBarPen) + Q_PROPERTY(QPen medianPen READ medianPen WRITE setMedianPen) + Q_PROPERTY(QCPScatterStyle outlierStyle READ outlierStyle WRITE setOutlierStyle) + /// \endcond +public: + explicit QCPStatisticalBox(QCPAxis *keyAxis, QCPAxis *valueAxis); + + // getters: + double key() const { return mKey; } + double minimum() const { return mMinimum; } + double lowerQuartile() const { return mLowerQuartile; } + double median() const { return mMedian; } + double upperQuartile() const { return mUpperQuartile; } + double maximum() const { return mMaximum; } + QVector outliers() const { return mOutliers; } + double width() const { return mWidth; } + double whiskerWidth() const { return mWhiskerWidth; } + QPen whiskerPen() const { return mWhiskerPen; } + QPen whiskerBarPen() const { return mWhiskerBarPen; } + QPen medianPen() const { return mMedianPen; } + QCPScatterStyle outlierStyle() const { return mOutlierStyle; } + + // setters: + void setKey(double key); + void setMinimum(double value); + void setLowerQuartile(double value); + void setMedian(double value); + void setUpperQuartile(double value); + void setMaximum(double value); + void setOutliers(const QVector &values); + void setData(double key, double minimum, double lowerQuartile, double median, double upperQuartile, double maximum); + void setWidth(double width); + void setWhiskerWidth(double width); + void setWhiskerPen(const QPen &pen); + void setWhiskerBarPen(const QPen &pen); + void setMedianPen(const QPen &pen); + void setOutlierStyle(const QCPScatterStyle &style); + + // non-property methods: + virtual void clearData(); + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + +protected: + // property members: + QVector mOutliers; + double mKey, mMinimum, mLowerQuartile, mMedian, mUpperQuartile, mMaximum; + double mWidth; + double mWhiskerWidth; + QPen mWhiskerPen, mWhiskerBarPen, mMedianPen; + QCPScatterStyle mOutlierStyle; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; + virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + + // introduced virtual methods: + virtual void drawQuartileBox(QCPPainter *painter, QRectF *quartileBox=0) const; + virtual void drawMedian(QCPPainter *painter) const; + virtual void drawWhiskers(QCPPainter *painter) const; + virtual void drawOutliers(QCPPainter *painter) const; + + friend class QCustomPlot; + friend class QCPLegend; +}; + + +class QCP_LIB_DECL QCPColorMapData +{ +public: + QCPColorMapData(int keySize, int valueSize, const QCPRange &keyRange, const QCPRange &valueRange); + ~QCPColorMapData(); + QCPColorMapData(const QCPColorMapData &other); + QCPColorMapData &operator=(const QCPColorMapData &other); + + // getters: + int keySize() const { return mKeySize; } + int valueSize() const { return mValueSize; } + QCPRange keyRange() const { return mKeyRange; } + QCPRange valueRange() const { return mValueRange; } + QCPRange dataBounds() const { return mDataBounds; } + double data(double key, double value); + double cell(int keyIndex, int valueIndex); + + // setters: + void setSize(int keySize, int valueSize); + void setKeySize(int keySize); + void setValueSize(int valueSize); + void setRange(const QCPRange &keyRange, const QCPRange &valueRange); + void setKeyRange(const QCPRange &keyRange); + void setValueRange(const QCPRange &valueRange); + void setData(double key, double value, double z); + void setCell(int keyIndex, int valueIndex, double z); + + // non-property methods: + void recalculateDataBounds(); + void clear(); + void fill(double z); + bool isEmpty() const { return mIsEmpty; } + void coordToCell(double key, double value, int *keyIndex, int *valueIndex) const; + void cellToCoord(int keyIndex, int valueIndex, double *key, double *value) const; + +protected: + // property members: + int mKeySize, mValueSize; + QCPRange mKeyRange, mValueRange; + bool mIsEmpty; + // non-property members: + double *mData; + QCPRange mDataBounds; + bool mDataModified; + + friend class QCPColorMap; +}; + + +class QCP_LIB_DECL QCPColorMap : public QCPAbstractPlottable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QCPRange dataRange READ dataRange WRITE setDataRange NOTIFY dataRangeChanged) + Q_PROPERTY(QCPAxis::ScaleType dataScaleType READ dataScaleType WRITE setDataScaleType NOTIFY dataScaleTypeChanged) + Q_PROPERTY(QCPColorGradient gradient READ gradient WRITE setGradient NOTIFY gradientChanged) + Q_PROPERTY(bool interpolate READ interpolate WRITE setInterpolate) + Q_PROPERTY(bool tightBoundary READ tightBoundary WRITE setTightBoundary) + Q_PROPERTY(QCPColorScale* colorScale READ colorScale WRITE setColorScale) + /// \endcond +public: + explicit QCPColorMap(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPColorMap(); + + // getters: + QCPColorMapData *data() const { return mMapData; } + QCPRange dataRange() const { return mDataRange; } + QCPAxis::ScaleType dataScaleType() const { return mDataScaleType; } + bool interpolate() const { return mInterpolate; } + bool tightBoundary() const { return mTightBoundary; } + QCPColorGradient gradient() const { return mGradient; } + QCPColorScale *colorScale() const { return mColorScale.data(); } + + // setters: + void setData(QCPColorMapData *data, bool copy=false); + Q_SLOT void setDataRange(const QCPRange &dataRange); + Q_SLOT void setDataScaleType(QCPAxis::ScaleType scaleType); + Q_SLOT void setGradient(const QCPColorGradient &gradient); + void setInterpolate(bool enabled); + void setTightBoundary(bool enabled); + void setColorScale(QCPColorScale *colorScale); + + // non-property methods: + void rescaleDataRange(bool recalculateDataBounds=false); + Q_SLOT void updateLegendIcon(Qt::TransformationMode transformMode=Qt::SmoothTransformation, const QSize &thumbSize=QSize(32, 18)); + + // reimplemented virtual methods: + virtual void clearData(); + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + +signals: + void dataRangeChanged(QCPRange newRange); + void dataScaleTypeChanged(QCPAxis::ScaleType scaleType); + void gradientChanged(QCPColorGradient newGradient); + +protected: + // property members: + QCPRange mDataRange; + QCPAxis::ScaleType mDataScaleType; + QCPColorMapData *mMapData; + QCPColorGradient mGradient; + bool mInterpolate; + bool mTightBoundary; + QPointer mColorScale; + // non-property members: + QImage mMapImage; + QPixmap mLegendIcon; + bool mMapImageInvalidated; + + // introduced virtual methods: + virtual void updateMapImage(); + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; + virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + + friend class QCustomPlot; + friend class QCPLegend; +}; + + +/*! \file */ + + + +class QCP_LIB_DECL QCPFinancialData +{ +public: + QCPFinancialData(); + QCPFinancialData(double key, double open, double high, double low, double close); + double key, open, high, low, close; +}; +Q_DECLARE_TYPEINFO(QCPFinancialData, Q_MOVABLE_TYPE); + +/*! \typedef QCPFinancialDataMap + Container for storing \ref QCPFinancialData items in a sorted fashion. The key of the map + is the key member of the QCPFinancialData instance. + + This is the container in which QCPFinancial holds its data. + \see QCPFinancial, QCPFinancial::setData +*/ +typedef QMap QCPFinancialDataMap; +typedef QMapIterator QCPFinancialDataMapIterator; +typedef QMutableMapIterator QCPFinancialDataMutableMapIterator; + + +class QCP_LIB_DECL QCPFinancial : public QCPAbstractPlottable +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(ChartStyle chartStyle READ chartStyle WRITE setChartStyle) + Q_PROPERTY(double width READ width WRITE setWidth) + Q_PROPERTY(bool twoColored READ twoColored WRITE setTwoColored) + Q_PROPERTY(QBrush brushPositive READ brushPositive WRITE setBrushPositive) + Q_PROPERTY(QBrush brushNegative READ brushNegative WRITE setBrushNegative) + Q_PROPERTY(QPen penPositive READ penPositive WRITE setPenPositive) + Q_PROPERTY(QPen penNegative READ penNegative WRITE setPenNegative) + /// \endcond +public: + /*! + Defines the possible representations of OHLC data in the plot. + + \see setChartStyle + */ + enum ChartStyle { csOhlc ///< Open-High-Low-Close bar representation + ,csCandlestick ///< Candlestick representation + }; + Q_ENUMS(ChartStyle) + + explicit QCPFinancial(QCPAxis *keyAxis, QCPAxis *valueAxis); + virtual ~QCPFinancial(); + + // getters: + QCPFinancialDataMap *data() const { return mData; } + ChartStyle chartStyle() const { return mChartStyle; } + double width() const { return mWidth; } + bool twoColored() const { return mTwoColored; } + QBrush brushPositive() const { return mBrushPositive; } + QBrush brushNegative() const { return mBrushNegative; } + QPen penPositive() const { return mPenPositive; } + QPen penNegative() const { return mPenNegative; } + + + // setters: + void setData(QCPFinancialDataMap *data, bool copy=false); + void setData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close); + void setChartStyle(ChartStyle style); + void setWidth(double width); + void setTwoColored(bool twoColored); + void setBrushPositive(const QBrush &brush); + void setBrushNegative(const QBrush &brush); + void setPenPositive(const QPen &pen); + void setPenNegative(const QPen &pen); + + // non-property methods: + void addData(const QCPFinancialDataMap &dataMap); + void addData(const QCPFinancialData &data); + void addData(double key, double open, double high, double low, double close); + void addData(const QVector &key, const QVector &open, const QVector &high, const QVector &low, const QVector &close); + void removeDataBefore(double key); + void removeDataAfter(double key); + void removeData(double fromKey, double toKey); + void removeData(double key); + + // reimplemented virtual methods: + virtual void clearData(); + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + // static methods: + static QCPFinancialDataMap timeSeriesToOhlc(const QVector &time, const QVector &value, double timeBinSize, double timeBinOffset = 0); + +protected: + // property members: + QCPFinancialDataMap *mData; + ChartStyle mChartStyle; + double mWidth; + bool mTwoColored; + QBrush mBrushPositive, mBrushNegative; + QPen mPenPositive, mPenNegative; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual void drawLegendIcon(QCPPainter *painter, const QRectF &rect) const; + virtual QCPRange getKeyRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + virtual QCPRange getValueRange(bool &foundRange, SignDomain inSignDomain=sdBoth) const; + + // non-virtual methods: + void drawOhlcPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end); + void drawCandlestickPlot(QCPPainter *painter, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end); + double ohlcSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const; + double candlestickSelectTest(const QPointF &pos, const QCPFinancialDataMap::const_iterator &begin, const QCPFinancialDataMap::const_iterator &end) const; + void getVisibleDataBounds(QCPFinancialDataMap::const_iterator &lower, QCPFinancialDataMap::const_iterator &upper) const; + + friend class QCustomPlot; + friend class QCPLegend; +}; + + +class QCP_LIB_DECL QCPItemStraightLine : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + /// \endcond +public: + QCPItemStraightLine(QCustomPlot *parentPlot); + virtual ~QCPItemStraightLine(); + + // getters: + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const point1; + QCPItemPosition * const point2; + +protected: + // property members: + QPen mPen, mSelectedPen; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + + // non-virtual methods: + double distToStraightLine(const QVector2D &point1, const QVector2D &vec, const QVector2D &point) const; + QLineF getRectClippedStraightLine(const QVector2D &point1, const QVector2D &vec, const QRect &rect) const; + QPen mainPen() const; +}; + + +class QCP_LIB_DECL QCPItemLine : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) + Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) + /// \endcond +public: + QCPItemLine(QCustomPlot *parentPlot); + virtual ~QCPItemLine(); + + // getters: + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + QCPLineEnding head() const { return mHead; } + QCPLineEnding tail() const { return mTail; } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setHead(const QCPLineEnding &head); + void setTail(const QCPLineEnding &tail); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const start; + QCPItemPosition * const end; + +protected: + // property members: + QPen mPen, mSelectedPen; + QCPLineEnding mHead, mTail; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + + // non-virtual methods: + QLineF getRectClippedLine(const QVector2D &start, const QVector2D &end, const QRect &rect) const; + QPen mainPen() const; +}; + + +class QCP_LIB_DECL QCPItemCurve : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QCPLineEnding head READ head WRITE setHead) + Q_PROPERTY(QCPLineEnding tail READ tail WRITE setTail) + /// \endcond +public: + QCPItemCurve(QCustomPlot *parentPlot); + virtual ~QCPItemCurve(); + + // getters: + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + QCPLineEnding head() const { return mHead; } + QCPLineEnding tail() const { return mTail; } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setHead(const QCPLineEnding &head); + void setTail(const QCPLineEnding &tail); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const start; + QCPItemPosition * const startDir; + QCPItemPosition * const endDir; + QCPItemPosition * const end; + +protected: + // property members: + QPen mPen, mSelectedPen; + QCPLineEnding mHead, mTail; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + + // non-virtual methods: + QPen mainPen() const; +}; + + +class QCP_LIB_DECL QCPItemRect : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + /// \endcond +public: + QCPItemRect(QCustomPlot *parentPlot); + virtual ~QCPItemRect(); + + // getters: + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + QBrush brush() const { return mBrush; } + QBrush selectedBrush() const { return mSelectedBrush; } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const topLeft; + QCPItemPosition * const bottomRight; + QCPItemAnchor * const top; + QCPItemAnchor * const topRight; + QCPItemAnchor * const right; + QCPItemAnchor * const bottom; + QCPItemAnchor * const bottomLeft; + QCPItemAnchor * const left; + +protected: + enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + QPen mainPen() const; + QBrush mainBrush() const; +}; + + +class QCP_LIB_DECL QCPItemText : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QColor color READ color WRITE setColor) + Q_PROPERTY(QColor selectedColor READ selectedColor WRITE setSelectedColor) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + Q_PROPERTY(QFont font READ font WRITE setFont) + Q_PROPERTY(QFont selectedFont READ selectedFont WRITE setSelectedFont) + Q_PROPERTY(QString text READ text WRITE setText) + Q_PROPERTY(Qt::Alignment positionAlignment READ positionAlignment WRITE setPositionAlignment) + Q_PROPERTY(Qt::Alignment textAlignment READ textAlignment WRITE setTextAlignment) + Q_PROPERTY(double rotation READ rotation WRITE setRotation) + Q_PROPERTY(QMargins padding READ padding WRITE setPadding) + /// \endcond +public: + QCPItemText(QCustomPlot *parentPlot); + virtual ~QCPItemText(); + + // getters: + QColor color() const { return mColor; } + QColor selectedColor() const { return mSelectedColor; } + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + QBrush brush() const { return mBrush; } + QBrush selectedBrush() const { return mSelectedBrush; } + QFont font() const { return mFont; } + QFont selectedFont() const { return mSelectedFont; } + QString text() const { return mText; } + Qt::Alignment positionAlignment() const { return mPositionAlignment; } + Qt::Alignment textAlignment() const { return mTextAlignment; } + double rotation() const { return mRotation; } + QMargins padding() const { return mPadding; } + + // setters; + void setColor(const QColor &color); + void setSelectedColor(const QColor &color); + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + void setFont(const QFont &font); + void setSelectedFont(const QFont &font); + void setText(const QString &text); + void setPositionAlignment(Qt::Alignment alignment); + void setTextAlignment(Qt::Alignment alignment); + void setRotation(double degrees); + void setPadding(const QMargins &padding); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const position; + QCPItemAnchor * const topLeft; + QCPItemAnchor * const top; + QCPItemAnchor * const topRight; + QCPItemAnchor * const right; + QCPItemAnchor * const bottomRight; + QCPItemAnchor * const bottom; + QCPItemAnchor * const bottomLeft; + QCPItemAnchor * const left; + +protected: + enum AnchorIndex {aiTopLeft, aiTop, aiTopRight, aiRight, aiBottomRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + QColor mColor, mSelectedColor; + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + QFont mFont, mSelectedFont; + QString mText; + Qt::Alignment mPositionAlignment; + Qt::Alignment mTextAlignment; + double mRotation; + QMargins mPadding; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + QPointF getTextDrawPoint(const QPointF &pos, const QRectF &rect, Qt::Alignment positionAlignment) const; + QFont mainFont() const; + QColor mainColor() const; + QPen mainPen() const; + QBrush mainBrush() const; +}; + + +class QCP_LIB_DECL QCPItemEllipse : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + /// \endcond +public: + QCPItemEllipse(QCustomPlot *parentPlot); + virtual ~QCPItemEllipse(); + + // getters: + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + QBrush brush() const { return mBrush; } + QBrush selectedBrush() const { return mSelectedBrush; } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const topLeft; + QCPItemPosition * const bottomRight; + QCPItemAnchor * const topLeftRim; + QCPItemAnchor * const top; + QCPItemAnchor * const topRightRim; + QCPItemAnchor * const right; + QCPItemAnchor * const bottomRightRim; + QCPItemAnchor * const bottom; + QCPItemAnchor * const bottomLeftRim; + QCPItemAnchor * const left; + QCPItemAnchor * const center; + +protected: + enum AnchorIndex {aiTopLeftRim, aiTop, aiTopRightRim, aiRight, aiBottomRightRim, aiBottom, aiBottomLeftRim, aiLeft, aiCenter}; + + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + QPen mainPen() const; + QBrush mainBrush() const; +}; + + +class QCP_LIB_DECL QCPItemPixmap : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPixmap pixmap READ pixmap WRITE setPixmap) + Q_PROPERTY(bool scaled READ scaled WRITE setScaled) + Q_PROPERTY(Qt::AspectRatioMode aspectRatioMode READ aspectRatioMode) + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + /// \endcond +public: + QCPItemPixmap(QCustomPlot *parentPlot); + virtual ~QCPItemPixmap(); + + // getters: + QPixmap pixmap() const { return mPixmap; } + bool scaled() const { return mScaled; } + Qt::AspectRatioMode aspectRatioMode() const { return mAspectRatioMode; } + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + + // setters; + void setPixmap(const QPixmap &pixmap); + void setScaled(bool scaled, Qt::AspectRatioMode aspectRatioMode=Qt::KeepAspectRatio); + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const topLeft; + QCPItemPosition * const bottomRight; + QCPItemAnchor * const top; + QCPItemAnchor * const topRight; + QCPItemAnchor * const right; + QCPItemAnchor * const bottom; + QCPItemAnchor * const bottomLeft; + QCPItemAnchor * const left; + +protected: + enum AnchorIndex {aiTop, aiTopRight, aiRight, aiBottom, aiBottomLeft, aiLeft}; + + // property members: + QPixmap mPixmap; + QPixmap mScaledPixmap; + bool mScaled; + Qt::AspectRatioMode mAspectRatioMode; + QPen mPen, mSelectedPen; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + void updateScaledPixmap(QRect finalRect=QRect(), bool flipHorz=false, bool flipVert=false); + QRect getFinalRect(bool *flippedHorz=0, bool *flippedVert=0) const; + QPen mainPen() const; +}; + + +class QCP_LIB_DECL QCPItemTracer : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(QBrush brush READ brush WRITE setBrush) + Q_PROPERTY(QBrush selectedBrush READ selectedBrush WRITE setSelectedBrush) + Q_PROPERTY(double size READ size WRITE setSize) + Q_PROPERTY(TracerStyle style READ style WRITE setStyle) + Q_PROPERTY(QCPGraph* graph READ graph WRITE setGraph) + Q_PROPERTY(double graphKey READ graphKey WRITE setGraphKey) + Q_PROPERTY(bool interpolating READ interpolating WRITE setInterpolating) + /// \endcond +public: + /*! + The different visual appearances a tracer item can have. Some styles size may be controlled with \ref setSize. + + \see setStyle + */ + enum TracerStyle { tsNone ///< The tracer is not visible + ,tsPlus ///< A plus shaped crosshair with limited size + ,tsCrosshair ///< A plus shaped crosshair which spans the complete axis rect + ,tsCircle ///< A circle + ,tsSquare ///< A square + }; + Q_ENUMS(TracerStyle) + + QCPItemTracer(QCustomPlot *parentPlot); + virtual ~QCPItemTracer(); + + // getters: + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + QBrush brush() const { return mBrush; } + QBrush selectedBrush() const { return mSelectedBrush; } + double size() const { return mSize; } + TracerStyle style() const { return mStyle; } + QCPGraph *graph() const { return mGraph; } + double graphKey() const { return mGraphKey; } + bool interpolating() const { return mInterpolating; } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setBrush(const QBrush &brush); + void setSelectedBrush(const QBrush &brush); + void setSize(double size); + void setStyle(TracerStyle style); + void setGraph(QCPGraph *graph); + void setGraphKey(double key); + void setInterpolating(bool enabled); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + // non-virtual methods: + void updatePosition(); + + QCPItemPosition * const position; + +protected: + // property members: + QPen mPen, mSelectedPen; + QBrush mBrush, mSelectedBrush; + double mSize; + TracerStyle mStyle; + QCPGraph *mGraph; + double mGraphKey; + bool mInterpolating; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + + // non-virtual methods: + QPen mainPen() const; + QBrush mainBrush() const; +}; + + +class QCP_LIB_DECL QCPItemBracket : public QCPAbstractItem +{ + Q_OBJECT + /// \cond INCLUDE_QPROPERTIES + Q_PROPERTY(QPen pen READ pen WRITE setPen) + Q_PROPERTY(QPen selectedPen READ selectedPen WRITE setSelectedPen) + Q_PROPERTY(double length READ length WRITE setLength) + Q_PROPERTY(BracketStyle style READ style WRITE setStyle) + /// \endcond +public: + enum BracketStyle { bsSquare ///< A brace with angled edges + ,bsRound ///< A brace with round edges + ,bsCurly ///< A curly brace + ,bsCalligraphic ///< A curly brace with varying stroke width giving a calligraphic impression + }; + + QCPItemBracket(QCustomPlot *parentPlot); + virtual ~QCPItemBracket(); + + // getters: + QPen pen() const { return mPen; } + QPen selectedPen() const { return mSelectedPen; } + double length() const { return mLength; } + BracketStyle style() const { return mStyle; } + + // setters; + void setPen(const QPen &pen); + void setSelectedPen(const QPen &pen); + void setLength(double length); + void setStyle(BracketStyle style); + + // reimplemented virtual methods: + virtual double selectTest(const QPointF &pos, bool onlySelectable, QVariant *details=0) const; + + QCPItemPosition * const left; + QCPItemPosition * const right; + QCPItemAnchor * const center; + +protected: + // property members: + enum AnchorIndex {aiCenter}; + QPen mPen, mSelectedPen; + double mLength; + BracketStyle mStyle; + + // reimplemented virtual methods: + virtual void draw(QCPPainter *painter); + virtual QPointF anchorPixelPoint(int anchorId) const; + + // non-virtual methods: + QPen mainPen() const; +}; + +#endif // QCUSTOMPLOT_H + diff --git a/src/qt/qvalidatedtextedit.cpp b/src/qt/qvalidatedtextedit.cpp new file mode 100644 index 0000000..c0cb83b --- /dev/null +++ b/src/qt/qvalidatedtextedit.cpp @@ -0,0 +1,44 @@ +#include "qvalidatedtextedit.h" + +#include "guiconstants.h" + +#include +QValidatedTextEdit::QValidatedTextEdit(QWidget *parent) : + QPlainTextEdit(parent), valid(true) +{} + +void QValidatedTextEdit::setValid(bool valid) +{ + setStyleSheet(valid ? "" : STYLE_INVALID); + + if(valid) + { + if(toPlainText() == this->errorText) + setPlainText(""); + } + else if(toPlainText() == "") + setPlainText(this->errorText); +} + +void QValidatedTextEdit::setErrorText(QString errorText) +{ + this->errorText = errorText; +} + +void QValidatedTextEdit::focusInEvent(QFocusEvent *evt) +{ + // Clear invalid flag on focus + setValid(true); + QPlainTextEdit::focusInEvent(evt); +} + +void QValidatedTextEdit::markValid() +{ + setValid(true); +} + +void QValidatedTextEdit::clear() +{ + setValid(true); + QPlainTextEdit::clear(); +} diff --git a/src/qt/qvalidatedtextedit.h b/src/qt/qvalidatedtextedit.h new file mode 100644 index 0000000..f1039e5 --- /dev/null +++ b/src/qt/qvalidatedtextedit.h @@ -0,0 +1,31 @@ +#ifndef QVALIDATEDTEXTEDIT_H +#define QVALIDATEDTEXTEDIT_H + +#include + +/** Text edit that can be marked as "invalid" to show input validation feedback. When marked as invalid, + it will get a red background until it is focused. + */ +class QValidatedTextEdit : public QPlainTextEdit +{ + Q_OBJECT +public: + explicit QValidatedTextEdit(QWidget *parent = 0); + void clear(); + +protected: + void focusInEvent(QFocusEvent *evt); + +private: + bool valid; + QString errorText; + +public slots: + void setValid(bool valid); + void setErrorText(QString errorText); + +private slots: + void markValid(); +}; + +#endif // QVALIDATEDTEXTEDIT_H diff --git a/src/qt/res/icons/novacoin-128.png b/src/qt/res/icons/novacoin-128.png index 20bee12..20f2ec9 100644 Binary files a/src/qt/res/icons/novacoin-128.png and b/src/qt/res/icons/novacoin-128.png differ diff --git a/src/qt/res/icons/novacoin-16.png b/src/qt/res/icons/novacoin-16.png index 56c9f14..9f88002 100644 Binary files a/src/qt/res/icons/novacoin-16.png and b/src/qt/res/icons/novacoin-16.png differ diff --git a/src/qt/res/icons/novacoin-32.png b/src/qt/res/icons/novacoin-32.png index 65214fd..fd57a87 100644 Binary files a/src/qt/res/icons/novacoin-32.png and b/src/qt/res/icons/novacoin-32.png differ diff --git a/src/qt/res/icons/novacoin-48.png b/src/qt/res/icons/novacoin-48.png index 12cdd8c..a2061b8 100644 Binary files a/src/qt/res/icons/novacoin-48.png and b/src/qt/res/icons/novacoin-48.png differ diff --git a/src/qt/res/icons/novacoin-80.png b/src/qt/res/icons/novacoin-80.png index 45d5bc4..4f816bb 100644 Binary files a/src/qt/res/icons/novacoin-80.png and b/src/qt/res/icons/novacoin-80.png differ diff --git a/src/qt/res/icons/novacoin.ico b/src/qt/res/icons/novacoin.ico index ea87322..7545083 100644 Binary files a/src/qt/res/icons/novacoin.ico and b/src/qt/res/icons/novacoin.ico differ diff --git a/src/qt/res/icons/novacoin.png b/src/qt/res/icons/novacoin.png index 2c591d6..a0a8673 100644 Binary files a/src/qt/res/icons/novacoin.png and b/src/qt/res/icons/novacoin.png differ diff --git a/src/qt/res/icons/onion-black.png b/src/qt/res/icons/onion-black.png new file mode 100644 index 0000000..e3ec917 Binary files /dev/null and b/src/qt/res/icons/onion-black.png differ diff --git a/src/qt/res/icons/onion.png b/src/qt/res/icons/onion.png new file mode 100644 index 0000000..7ade2da Binary files /dev/null and b/src/qt/res/icons/onion.png differ diff --git a/src/qt/res/images/about.png b/src/qt/res/images/about.png index c9ab951..a7cbc59 100644 Binary files a/src/qt/res/images/about.png and b/src/qt/res/images/about.png differ diff --git a/src/qt/res/images/header.png b/src/qt/res/images/header.png index f6130ee..0d26c6d 100644 Binary files a/src/qt/res/images/header.png and b/src/qt/res/images/header.png differ diff --git a/src/qt/res/images/splash3.png b/src/qt/res/images/splash3.png index f6130ee..41e5048 100644 Binary files a/src/qt/res/images/splash3.png and b/src/qt/res/images/splash3.png differ diff --git a/src/qt/sendcoinsdialog.cpp b/src/qt/sendcoinsdialog.cpp index 4e7fcc1..05b7910 100644 --- a/src/qt/sendcoinsdialog.cpp +++ b/src/qt/sendcoinsdialog.cpp @@ -36,7 +36,7 @@ SendCoinsDialog::SendCoinsDialog(QWidget *parent) : #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ - ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a Genius address (e.g. 2QWdyivSRQqcHJA9WRVmMi6hxJ7vxfYXrY)")); + ui->lineEditCoinControlChange->setPlaceholderText(tr("Enter a Genius address (e.g. 2XfvvXkSpTAJNP8CjtUgo9YV2M7pDxinKc)")); #endif addEntry(); @@ -94,8 +94,8 @@ void SendCoinsDialog::setModel(WalletModel *model) } } - setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance()); - connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64))); + setBalance(model->getBalance(), model->getStake(), model->getUnconfirmedBalance(), model->getImmatureBalance(), model->getAnonymizedBalance()); + connect(model, SIGNAL(balanceChanged(qint64, qint64, qint64, qint64, qint64)), this, SLOT(setBalance(qint64, qint64, qint64, qint64, qint64))); connect(model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit())); // Coin Control @@ -214,6 +214,11 @@ void SendCoinsDialog::on_sendButton_clicked() tr("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."), QMessageBox::Ok, QMessageBox::Ok); break; + case WalletModel::NarrationTooLong: + QMessageBox::warning(this, tr("Send Coins"), + tr("Error: Narration is too long."), + QMessageBox::Ok, QMessageBox::Ok); + break; case WalletModel::Aborted: // User aborted, nothing to do break; case WalletModel::OK: @@ -346,11 +351,12 @@ bool SendCoinsDialog::handleURI(const QString &uri) return false; } -void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance) +void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance, qint64 anonymizedBalance) { Q_UNUSED(stake); Q_UNUSED(unconfirmedBalance); Q_UNUSED(immatureBalance); + Q_UNUSED(anonymizedBalance); if(model && model->getOptionsModel()) { @@ -360,7 +366,7 @@ void SendCoinsDialog::setBalance(qint64 balance, qint64 stake, qint64 unconfirme void SendCoinsDialog::updateDisplayUnit() { - setBalance(model->getBalance(), 0, 0, 0); + setBalance(model->getBalance(), 0, 0, 0, 0); } // Coin Control: copy label "Quantity" to clipboard diff --git a/src/qt/sendcoinsdialog.h b/src/qt/sendcoinsdialog.h index 68424bb..409bab2 100644 --- a/src/qt/sendcoinsdialog.h +++ b/src/qt/sendcoinsdialog.h @@ -39,7 +39,7 @@ public slots: void accept(); SendCoinsEntry *addEntry(); void updateRemoveEnabled(); - void setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance); + void setBalance(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance, qint64 anonymizedBalance); private: Ui::SendCoinsDialog *ui; diff --git a/src/qt/sendcoinsentry.cpp b/src/qt/sendcoinsentry.cpp index 89dbb84..93b324a 100644 --- a/src/qt/sendcoinsentry.cpp +++ b/src/qt/sendcoinsentry.cpp @@ -7,6 +7,7 @@ #include "walletmodel.h" #include "optionsmodel.h" #include "addresstablemodel.h" +#include "stealth.h" #include #include @@ -24,7 +25,7 @@ SendCoinsEntry::SendCoinsEntry(QWidget *parent) : #if QT_VERSION >= 0x040700 /* Do not move this to the XML file, Qt before 4.7 will choke on it */ ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); - ui->payTo->setPlaceholderText(tr("Enter a Genius address (e.g. 2QWdyivSRQqcHJA9WRVmMi6hxJ7vxfYXrY)")); + ui->payTo->setPlaceholderText(tr("Enter a Genius address (e.g. 2XfvvXkSpTAJNP8CjtUgo9YV2M7pDxinKc)")); #endif setFocusPolicy(Qt::TabFocus); setFocusProxy(ui->payTo); @@ -135,6 +136,12 @@ SendCoinsRecipient SendCoinsEntry::getValue() rv.label = ui->addAsLabel->text(); rv.amount = ui->payAmount->value(); + if (rv.address.length() > 75 + && IsStealthAddress(rv.address.toStdString())) + rv.typeInd = AddressTableModel::AT_Stealth; + else + rv.typeInd = AddressTableModel::AT_Normal; + return rv; } diff --git a/src/qt/sendmessagesdialog.cpp b/src/qt/sendmessagesdialog.cpp new file mode 100644 index 0000000..0680ae4 --- /dev/null +++ b/src/qt/sendmessagesdialog.cpp @@ -0,0 +1,339 @@ +#include "sendmessagesdialog.h" +#include "ui_sendmessagesdialog.h" +//#include "init.h" +#include "walletmodel.h" +#include "messagemodel.h" +#include "addressbookpage.h" +#include "optionsmodel.h" +#include "sendmessagesentry.h" +//#include "guiutil.h" + +#include +#include +#include +#include +#include +#include + +SendMessagesDialog::SendMessagesDialog(Mode mode, Type type, QWidget *parent) : + QDialog(parent), + ui(new Ui::SendMessagesDialog), + model(0), + mode(mode), + type(type) +{ + + ui->setupUi(this); + +#ifdef Q_OS_MAC // Icons on push buttons are very uncommon on Mac + ui->addButton->setIcon(QIcon()); + ui->clearButton->setIcon(QIcon()); + ui->sendButton->setIcon(QIcon()); +#endif + +#if QT_VERSION >= 0x040700 + /* Do not move this to the XML file, Qt before 4.7 will choke on it */ + if(mode == SendMessagesDialog::Encrypted) + ui->addressFrom->setPlaceholderText(tr("Enter a Genius address (e.g. 2XfvvXkSpTAJNP8CjtUgo9YV2M7pDxinKc)")); + #endif + addEntry(); + + connect(ui->addButton, SIGNAL(clicked()), this, SLOT(addEntry())); + connect(ui->clearButton, SIGNAL(clicked()), this, SLOT(clear())); + connect(ui->closeButton, SIGNAL(clicked()), this, SLOT(reject())); + + fNewRecipientAllowed = true; + + if(mode == SendMessagesDialog::Anonymous) + ui->frameAddressFrom->hide(); + + if(type == SendMessagesDialog::Page) + ui->closeButton->hide(); +} + +void SendMessagesDialog::setModel(MessageModel *model) +{ + this->model = model; + + for(int i = 0; i < ui->entries->count(); ++i) + { + SendMessagesEntry *entry = qobject_cast(ui->entries->itemAt(i)->widget()); + + if(entry) + entry->setModel(model); + } +} + +void SendMessagesDialog::loadRow(int row) +{ + if(model->data(model->index(row, model->Type, QModelIndex()), Qt::DisplayRole).toString() == MessageModel::Received) + ui->addressFrom->setText(model->data(model->index(row, model->ToAddress, QModelIndex()), Qt::DisplayRole).toString()); + else + ui->addressFrom->setText(model->data(model->index(row, model->FromAddress, QModelIndex()), Qt::DisplayRole).toString()); + + for(int i = 0; i < ui->entries->count(); ++i) + { + SendMessagesEntry *entry = qobject_cast(ui->entries->itemAt(i)->widget()); + + if(entry) + entry->loadRow(row); + } +} + +bool SendMessagesDialog::checkMode(Mode mode) +{ + return (mode == this->mode); +} + +bool SendMessagesDialog::validate() +{ + if(mode == SendMessagesDialog::Encrypted && ui->addressFrom->text() == "") + { + ui->addressFrom->setValid(false); + + return false; + } + + return true; +} + +SendMessagesDialog::~SendMessagesDialog() +{ + delete ui; +} + +void SendMessagesDialog::on_pasteButton_clicked() +{ + // Paste text from clipboard into recipient field + ui->addressFrom->setText(QApplication::clipboard()->text()); +} + +void SendMessagesDialog::on_addressBookButton_clicked() +{ + if(!model) + return; + + AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::ReceivingTab, this); + + dlg.setModel(model->getWalletModel()->getAddressTableModel()); + + if(dlg.exec()) + { + ui->addressFrom->setText(dlg.getReturnValue()); + SendMessagesEntry *entry = qobject_cast(ui->entries->itemAt(0)->widget()); + entry->setFocus(); + // findChild( const QString "sentTo")->setFocus(); + } +} + +void SendMessagesDialog::on_sendButton_clicked() +{ + QList recipients; + bool valid = true; + + if(!model) + return; + + valid = validate(); + + for(int i = 0; i < ui->entries->count(); ++i) + { + SendMessagesEntry *entry = qobject_cast(ui->entries->itemAt(i)->widget()); + if(entry) + { + if(entry->validate()) + recipients.append(entry->getValue()); + else + valid = false; + } + } + + if(!valid || recipients.isEmpty()) + return; + + // Format confirmation message + QStringList formatted; + foreach(const SendMessagesRecipient &rcp, recipients) + { + formatted.append(tr("%1 to %2 (%3)").arg(rcp.message, Qt::escape(rcp.label), rcp.address)); + } + + fNewRecipientAllowed = false; + + QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm send messages"), + tr("Are you sure you want to send %1?").arg(formatted.join(tr(" and "))), + QMessageBox::Yes|QMessageBox::Cancel, + QMessageBox::Cancel); + + if(retval != QMessageBox::Yes) + { + fNewRecipientAllowed = true; + return; + } + + MessageModel::StatusCode sendstatus; + + if(mode == SendMessagesDialog::Anonymous) + sendstatus = model->sendMessages(recipients); + else + sendstatus = model->sendMessages(recipients, ui->addressFrom->text()); + + switch(sendstatus) + { + case MessageModel::InvalidAddress: + QMessageBox::warning(this, tr("Send Message"), + tr("The recipient address is not valid, please recheck."), + QMessageBox::Ok, QMessageBox::Ok); + break; + case MessageModel::InvalidMessage: + QMessageBox::warning(this, tr("Send Message"), + tr("The message can't be empty."), + QMessageBox::Ok, QMessageBox::Ok); + break; + case MessageModel::DuplicateAddress: + QMessageBox::warning(this, tr("Send Message"), + tr("Duplicate address found, can only send to each address once per send operation."), + QMessageBox::Ok, QMessageBox::Ok); + break; + case MessageModel::MessageCreationFailed: + QMessageBox::warning(this, tr("Send Message"), + tr("Error: Message creation failed."), + QMessageBox::Ok, QMessageBox::Ok); + break; + case MessageModel::MessageCommitFailed: + QMessageBox::warning(this, tr("Send Message"), + tr("Error: The message was rejected."), + QMessageBox::Ok, QMessageBox::Ok); + break; + case MessageModel::Aborted: // User aborted, nothing to do + break; + case MessageModel::FailedErrorShown: // Send failed, error message was displayed + break; + case MessageModel::OK: + accept(); + break; + } + + fNewRecipientAllowed = true; +} + +void SendMessagesDialog::clear() +{ + // Remove entries until only one left + while(ui->entries->count()) + delete ui->entries->takeAt(0)->widget(); + + addEntry(); + + updateRemoveEnabled(); + + ui->sendButton->setDefault(true); +} + +void SendMessagesDialog::reject() +{ + if(type == SendMessagesDialog::Dialog) + done(1); + else + clear(); +} + +void SendMessagesDialog::accept() +{ + if(type == SendMessagesDialog::Dialog) + done(0); + else + clear(); + +} + +void SendMessagesDialog::done(int retval) +{ + if(type == SendMessagesDialog::Dialog) + QDialog::done(retval); + else + clear(); +} + +SendMessagesEntry *SendMessagesDialog::addEntry() +{ + SendMessagesEntry *entry = new SendMessagesEntry(this); + + entry->setModel(model); + ui->entries->addWidget(entry); + connect(entry, SIGNAL(removeEntry(SendMessagesEntry*)), this, SLOT(removeEntry(SendMessagesEntry*))); + updateRemoveEnabled(); + + // Focus the field, so that entry can start immediately + entry->clear(); + entry->setFocus(); + + ui->scrollAreaWidgetContents->resize(ui->scrollAreaWidgetContents->sizeHint()); + QCoreApplication::instance()->processEvents(); + QScrollBar* bar = ui->scrollArea->verticalScrollBar(); + + if(bar) + bar->setSliderPosition(bar->maximum()); + + return entry; +} + +void SendMessagesDialog::updateRemoveEnabled() +{ + // Remove buttons are enabled as soon as there is more than one send-entry + bool enabled = (ui->entries->count() > 1); + + for(int i = 0; i < ui->entries->count(); ++i) + { + SendMessagesEntry *entry = qobject_cast(ui->entries->itemAt(i)->widget()); + if(entry) + entry->setRemoveEnabled(enabled); + } + + setupTabChain(0); +} + +void SendMessagesDialog::removeEntry(SendMessagesEntry* entry) +{ + delete entry; + + updateRemoveEnabled(); +} + +QWidget *SendMessagesDialog::setupTabChain(QWidget *prev) +{ + for(int i = 0; i < ui->entries->count(); ++i) + { + SendMessagesEntry *entry = qobject_cast(ui->entries->itemAt(i)->widget()); + if(entry) + { + prev = entry->setupTabChain(prev); + } + } + + QWidget::setTabOrder(prev, ui->addButton); + QWidget::setTabOrder(ui->addButton, ui->sendButton); + + return ui->sendButton; +} + +void SendMessagesDialog::pasteEntry(const SendMessagesRecipient &rv) +{ + if(!fNewRecipientAllowed) + return; + + SendMessagesEntry *entry = 0; + // Replace the first entry if it is still unused + if(ui->entries->count() == 1) + { + SendMessagesEntry *first = qobject_cast(ui->entries->itemAt(0)->widget()); + + if(first->isClear()) + entry = first; + } + + if(!entry) + entry = addEntry(); + + entry->setValue(rv); +} diff --git a/src/qt/sendmessagesdialog.h b/src/qt/sendmessagesdialog.h new file mode 100644 index 0000000..08d3003 --- /dev/null +++ b/src/qt/sendmessagesdialog.h @@ -0,0 +1,72 @@ +#ifndef SENDMESSAGESDIALOG_H +#define SENDMESSAGESDIALOG_H + +#include +#include + +namespace Ui { + class SendMessagesDialog; +} + +class MessageModel; +class SendMessagesEntry; +class SendMessagesRecipient; + +//QT_BEGIN_NAMESPACE +//class QUrl; +//QT_END_NAMESPACE + +/** Dialog for sending messages */ +class SendMessagesDialog : public QDialog +{ + Q_OBJECT + +public: + + enum Mode { + Encrypted, + Anonymous, + }; + + enum Type { + Page, + Dialog, + }; + + explicit SendMessagesDialog(Mode mode, Type type, QWidget *parent = 0); + ~SendMessagesDialog(); + + void setModel (MessageModel *model); + void loadRow(int row); + bool checkMode(Mode mode); + bool validate (); + + /** Set up the tab chain manually, as Qt messes up the tab chain by default in some cases (issue https://bugreports.qt-project.org/browse/QTBUG-10907). + */ + QWidget *setupTabChain(QWidget *prev); + + void pasteEntry(const SendMessagesRecipient &rv); + +public slots: + void done(int retval); + void clear(); + void reject(); + void accept(); + SendMessagesEntry *addEntry(); + void updateRemoveEnabled(); + +private: + Ui::SendMessagesDialog *ui; + MessageModel *model; + bool fNewRecipientAllowed; + Mode mode; + Type type; + +private slots: + void on_sendButton_clicked(); + void removeEntry(SendMessagesEntry* entry); + void on_addressBookButton_clicked(); + void on_pasteButton_clicked(); +}; + +#endif // SENDMESSAGESDIALOG_H diff --git a/src/qt/sendmessagesentry.cpp b/src/qt/sendmessagesentry.cpp new file mode 100644 index 0000000..1a52aad --- /dev/null +++ b/src/qt/sendmessagesentry.cpp @@ -0,0 +1,204 @@ +#include "sendmessagesentry.h" +#include "ui_sendmessagesentry.h" +#include "guiutil.h" +#include "addressbookpage.h" +#include "walletmodel.h" +#include "messagemodel.h" +#include "optionsmodel.h" +#include "addresstablemodel.h" + +#include "smessage.h" + +#include +#include + +SendMessagesEntry::SendMessagesEntry(QWidget *parent) : + QFrame(parent), + ui(new Ui::SendMessagesEntry), + model(0) +{ + ui->setupUi(this); + +#ifdef Q_OS_MAC + ui->sendToLayout->setSpacing(4); +#endif +#if QT_VERSION >= 0x040700 + /* Do not move this to the XML file, Qt before 4.7 will choke on it */ + ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book")); + ui->sendTo->setPlaceholderText(tr("Enter a Genius address (e.g. 2XfvvXkSpTAJNP8CjtUgo9YV2M7pDxinKc)")); + ui->publicKey->setPlaceholderText(tr("Enter the public key for the address above, it is not in the blockchain")); + ui->messageText->setErrorText(tr("You cannot send a blank message!")); +#endif + setFocusPolicy(Qt::TabFocus); + setFocusProxy(ui->sendTo); + + GUIUtil::setupAddressWidget(ui->sendTo, this); +} + +SendMessagesEntry::~SendMessagesEntry() +{ + delete ui; +} + +void SendMessagesEntry::on_pasteButton_clicked() +{ + // Paste text from clipboard into recipient field + ui->sendTo->setText(QApplication::clipboard()->text()); +} + +void SendMessagesEntry::on_addressBookButton_clicked() +{ + if(!model) + return; + + AddressBookPage dlg(AddressBookPage::ForSending, AddressBookPage::SendingTab, this); + + dlg.setModel(model->getWalletModel()->getAddressTableModel()); + + if(dlg.exec()) + { + + ui->sendTo->setText(dlg.getReturnValue()); + + if(ui->publicKey->text() == "") + ui->publicKey->setFocus(); + else + ui->messageText->setFocus(); + } +} + +void SendMessagesEntry::on_sendTo_textChanged(const QString &address) +{ + if(!model) + return; + + QString pubkey; + QString sendTo = address; + + if(model->getAddressOrPubkey(sendTo, pubkey)) + { + + ui->publicKey->setText(pubkey); + } + else + { + ui->publicKey->show(); + ui->publicKeyLabel->show(); + } + + // Fill in label from address book, if address has an associated label + QString associatedLabel = model->getWalletModel()->getAddressTableModel()->labelForAddress(address); + + if(!associatedLabel.isEmpty()) + ui->addAsLabel->setText(associatedLabel); +} + +void SendMessagesEntry::setModel(MessageModel *model) +{ + + this->model = model; + + //clear(); +} + +void SendMessagesEntry::loadRow(int row) +{ + if(model->data(model->index(row, model->Type, QModelIndex()), Qt::DisplayRole).toString() == MessageModel::Received) + ui->sendTo->setText(model->data(model->index(row, model->FromAddress, QModelIndex()), Qt::DisplayRole).toString()); + else + ui->sendTo->setText(model->data(model->index(row, model->ToAddress, QModelIndex()), Qt::DisplayRole).toString()); +} + +void SendMessagesEntry::setRemoveEnabled(bool enabled) +{ + ui->deleteButton->setEnabled(enabled); +} + +void SendMessagesEntry::clear() +{ + ui->sendTo->clear(); + ui->addAsLabel->clear(); + ui->messageText->clear(); + ui->sendTo->setFocus(); +} + +void SendMessagesEntry::on_deleteButton_clicked() +{ + emit removeEntry(this); +} + + +bool SendMessagesEntry::validate() +{ + // Check input validity + bool retval = true; + + if(ui->messageText->toPlainText() == "") + { + ui->messageText->setValid(false); + + retval = false; + } + + if(!ui->sendTo->hasAcceptableInput() || (!model->getWalletModel()->validateAddress(ui->sendTo->text()))) + { + ui->sendTo->setValid(false); + + retval = false; + } + + if(ui->publicKey->text() == "") + { + ui->publicKey->setValid(false); + ui->publicKey->show(); + + retval = false; + } + + return retval; +} + +SendMessagesRecipient SendMessagesEntry::getValue() +{ + SendMessagesRecipient rv; + + rv.address = ui->sendTo->text(); + rv.label = ui->addAsLabel->text(); + rv.pubkey = ui->publicKey->text(); + rv.message = ui->messageText->toPlainText(); + + return rv; +} + + +QWidget *SendMessagesEntry::setupTabChain(QWidget *prev) +{ + QWidget::setTabOrder(prev, ui->sendTo); + QWidget::setTabOrder(ui->sendTo, ui->addressBookButton); + QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton); + QWidget::setTabOrder(ui->pasteButton, ui->deleteButton); + QWidget::setTabOrder(ui->deleteButton, ui->addAsLabel); + QWidget::setTabOrder(ui->addAsLabel, ui->publicKey); + QWidget::setTabOrder(ui->publicKey, ui->messageText); + + return ui->messageText; + +} + +void SendMessagesEntry::setValue(const SendMessagesRecipient &value) +{ + ui->sendTo->setText(value.address); + ui->addAsLabel->setText(value.label); + ui->publicKey->setText(value.pubkey); + ui->messageText->setPlainText(value.message); +} + +bool SendMessagesEntry::isClear() +{ + return ui->sendTo->text().isEmpty(); +} + +void SendMessagesEntry::setFocus() +{ + ui->sendTo->setFocus(); +} diff --git a/src/qt/sendmessagesentry.h b/src/qt/sendmessagesentry.h new file mode 100644 index 0000000..3f589ab --- /dev/null +++ b/src/qt/sendmessagesentry.h @@ -0,0 +1,55 @@ +#ifndef SENDMESSAGESENTRY_H +#define SENDMESSAGESENTRY_H + +#include + +namespace Ui { + class SendMessagesEntry; +} +class MessageModel; +class SendMessagesRecipient; + +/** A single entry in the dialog for sending messages. */ +class SendMessagesEntry : public QFrame +{ + Q_OBJECT + +public: + explicit SendMessagesEntry(QWidget *parent = 0); + ~SendMessagesEntry(); + + void setModel(MessageModel *model); + void loadRow(int row); + bool validate(); + SendMessagesRecipient getValue(); + + /** Return whether the entry is still empty and unedited */ + bool isClear(); + + void setValue(const SendMessagesRecipient &value); + + /** Set up the tab chain manually, as Qt messes up the tab chain by default in some cases (issue https://bugreports.qt-project.org/browse/QTBUG-10907). + */ + QWidget *setupTabChain(QWidget *prev); + + void setFocus(); + +public slots: + void setRemoveEnabled(bool enabled); + void clear(); + +signals: + void removeEntry(SendMessagesEntry *entry); + +private slots: + void on_deleteButton_clicked(); + void on_addressBookButton_clicked(); + void on_pasteButton_clicked(); + void on_sendTo_textChanged(const QString &address); + +private: + Ui::SendMessagesEntry *ui; + MessageModel *model; +}; + +#endif // SENDMESSAGESENTRY_H diff --git a/src/qt/signverifymessagedialog.cpp b/src/qt/signverifymessagedialog.cpp index ec42d16..36717d3 100644 --- a/src/qt/signverifymessagedialog.cpp +++ b/src/qt/signverifymessagedialog.cpp @@ -24,10 +24,10 @@ SignVerifyMessageDialog::SignVerifyMessageDialog(QWidget *parent) : #if (QT_VERSION >= 0x040700) /* Do not move this to the XML file, Qt before 4.7 will choke on it */ - ui->addressIn_SM->setPlaceholderText(tr("Enter a Genius address (e.g. 2QWdyivSRQqcHJA9WRVmMi6hxJ7vxfYXrY)")); + ui->addressIn_SM->setPlaceholderText(tr("Enter a Genius address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)")); ui->signatureOut_SM->setPlaceholderText(tr("Click \"Sign Message\" to generate signature")); - ui->addressIn_VM->setPlaceholderText(tr("Enter a Genius address (e.g. 2QWdyivSRQqcHJA9WRVmMi6hxJ7vxfYXrY)")); + ui->addressIn_VM->setPlaceholderText(tr("Enter a Genius address (e.g. B8gZqgY4r2RoEdqYk3QsAqFckyf9pRHN6i)")); ui->signatureIn_VM->setPlaceholderText(tr("Enter Genius signature")); #endif diff --git a/src/qt/transactiondesc.cpp b/src/qt/transactiondesc.cpp index 8cd187c..f2883f0 100644 --- a/src/qt/transactiondesc.cpp +++ b/src/qt/transactiondesc.cpp @@ -216,7 +216,7 @@ QString TransactionDesc::toHTML(CWallet *wallet, CWalletTx &wtx, TransactionReco strHTML += "" + tr("Transaction ID") + ": " + TransactionRecord::formatSubTxId(wtx.GetHash(), rec->idx) + "
"; if (wtx.IsCoinBase() || wtx.IsCoinStake()) - strHTML += "
" + tr("Generated coins must mature 510 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.") + "
"; + strHTML += "
" + tr("Generated coins must mature 188 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to \"not accepted\" and it won't be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.") + "
"; // // Debug view diff --git a/src/qt/walletmodel.cpp b/src/qt/walletmodel.cpp index 67f9139..d3ec411 100644 --- a/src/qt/walletmodel.cpp +++ b/src/qt/walletmodel.cpp @@ -8,6 +8,8 @@ #include "wallet.h" #include "walletdb.h" // for BackupWallet #include "base58.h" +#include "spork.h" +#include "smessage.h" #include #include @@ -44,7 +46,8 @@ qint64 WalletModel::getBalance(const CCoinControl *coinControl) const std::vector vCoins; wallet->AvailableCoins(vCoins, true, coinControl); BOOST_FOREACH(const COutput& out, vCoins) - nBalance += out.tx->vout[out.i].nValue; + if(out.fSpendable) + nBalance += out.tx->vout[out.i].nValue; return nBalance; } @@ -67,6 +70,12 @@ qint64 WalletModel::getImmatureBalance() const return wallet->GetImmatureBalance(); } +qint64 WalletModel::getAnonymizedBalance() const +{ + qint64 ret = wallet->GetAnonymizedBalance(); + return ret; +} + void WalletModel::updateStatus() { EncryptionStatus newEncryptionStatus = getEncryptionStatus(); @@ -104,14 +113,17 @@ void WalletModel::checkBalanceChanged() qint64 newStake = getStake(); qint64 newUnconfirmedBalance = getUnconfirmedBalance(); qint64 newImmatureBalance = getImmatureBalance(); + qint64 newAnonymizedBalance = getAnonymizedBalance(); - if(cachedBalance != newBalance || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance) + if(cachedBalance != newBalance || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance || cachedAnonymizedBalance != newAnonymizedBalance || cachedTxLocks != nCompleteTXLocks) { cachedBalance = newBalance; cachedStake = newStake; cachedUnconfirmedBalance = newUnconfirmedBalance; cachedImmatureBalance = newImmatureBalance; - emit balanceChanged(newBalance, newStake, newUnconfirmedBalance, newImmatureBalance); + cachedAnonymizedBalance = newAnonymizedBalance; + cachedTxLocks = nCompleteTXLocks; + emit balanceChanged(newBalance, newStake, newUnconfirmedBalance, newImmatureBalance, newAnonymizedBalance); } } @@ -132,7 +144,15 @@ void WalletModel::updateAddressBook(const QString &address, const QString &label bool WalletModel::validateAddress(const QString &address) { - CBitcoinAddress addressParsed(address.toStdString()); + std::string sAddr = address.toStdString(); + + if (sAddr.length() > 75) + { + if (IsStealthAddress(sAddr)) + return true; + }; + + CBitcoinAddress addressParsed(sAddr); return addressParsed.IsValid(); } @@ -147,6 +167,11 @@ WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList mapStealthNarr; + { LOCK2(cs_main, wallet->cs_wallet); @@ -187,15 +214,167 @@ WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList > vecSend; foreach(const SendCoinsRecipient &rcp, recipients) { + std::string sAddr = rcp.address.toStdString(); + + if (rcp.typeInd == AddressTableModel::AT_Stealth) + { + CStealthAddress sxAddr; + if (sxAddr.SetEncoded(sAddr)) + { + ec_secret ephem_secret; + ec_secret secretShared; + ec_point pkSendTo; + ec_point ephem_pubkey; + + + if (GenerateRandomSecret(ephem_secret) != 0) + { + printf("GenerateRandomSecret failed.\n"); + return Aborted; + }; + + if (StealthSecret(ephem_secret, sxAddr.scan_pubkey, sxAddr.spend_pubkey, secretShared, pkSendTo) != 0) + { + printf("Could not generate receiving public key.\n"); + return Aborted; + }; + + CPubKey cpkTo(pkSendTo); + if (!cpkTo.IsValid()) + { + printf("Invalid public key generated.\n"); + return Aborted; + }; + + CKeyID ckidTo = cpkTo.GetID(); + + CBitcoinAddress addrTo(ckidTo); + + if (SecretToPublicKey(ephem_secret, ephem_pubkey) != 0) + { + printf("Could not generate ephem public key.\n"); + return Aborted; + }; + + if (fDebug) + { + printf("Stealth send to generated pubkey %"PRIszu": %s\n", pkSendTo.size(), HexStr(pkSendTo).c_str()); + printf("hash %s\n", addrTo.ToString().c_str()); + printf("ephem_pubkey %"PRIszu": %s\n", ephem_pubkey.size(), HexStr(ephem_pubkey).c_str()); + }; + + CScript scriptPubKey; + scriptPubKey.SetDestination(addrTo.Get()); + + vecSend.push_back(make_pair(scriptPubKey, rcp.amount)); + + CScript scriptP = CScript() << OP_RETURN << ephem_pubkey; + + if (rcp.narration.length() > 0) + { + std::string sNarr = rcp.narration.toStdString(); + + if (sNarr.length() > 24) + { + printf("Narration is too long.\n"); + return NarrationTooLong; + }; + + std::vector vchNarr; + + SecMsgCrypter crypter; + crypter.SetKey(&secretShared.e[0], &ephem_pubkey[0]); + + if (!crypter.Encrypt((uint8_t*)&sNarr[0], sNarr.length(), vchNarr)) + { + printf("Narration encryption failed.\n"); + return Aborted; + }; + + if (vchNarr.size() > 48) + { + printf("Encrypted narration is too long.\n"); + return Aborted; + }; + + if (vchNarr.size() > 0) + scriptP = scriptP << OP_RETURN << vchNarr; + + int pos = vecSend.size()-1; + mapStealthNarr[pos] = sNarr; + }; + + vecSend.push_back(make_pair(scriptP, 1)); + + + continue; + } + else + { + printf("Couldn't parse stealth address!\n"); + return Aborted; + } // else drop through to normal + } + CScript scriptPubKey; - scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get()); + scriptPubKey.SetDestination(CBitcoinAddress(sAddr).Get()); vecSend.push_back(make_pair(scriptPubKey, rcp.amount)); + + + + + if (rcp.narration.length() > 0) + { + std::string sNarr = rcp.narration.toStdString(); + + if (sNarr.length() > 24) + { + printf("Narration is too long.\n"); + return NarrationTooLong; + }; + + std::vector vNarr(sNarr.c_str(), sNarr.c_str() + sNarr.length()); + std::vector vNDesc; + + vNDesc.resize(2); + vNDesc[0] = 'n'; + vNDesc[1] = 'p'; + + CScript scriptN = CScript() << OP_RETURN << vNDesc << OP_RETURN << vNarr; + + vecSend.push_back(make_pair(scriptN, 1)); + } } CWalletTx wtx; CReserveKey keyChange(wallet); int64_t nFeeRequired = 0; - bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl); + int nChangePos = -1; + std::string strFailReason; + + /*if(recipients[0].useInstantX && total > GetSporkValue(SPORK_2_MAX_VALUE)*COIN){ + emit message(tr("Send Coins"), tr("InstantX doesn't support sending values that high yet. Transactions are currently limited to %n GENIUS.", "", GetSporkValue(SPORK_2_MAX_VALUE)),true, + CClientUIInterface::MSG_ERROR); + return TransactionCreationFailed; + }*/ + + bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePos, strFailReason, coinControl); + + std::map::iterator it; + for (it = mapStealthNarr.begin(); it != mapStealthNarr.end(); ++it) + { + int pos = it->first; + if (nChangePos > -1 && it->first >= nChangePos) + pos++; + + char key[64]; + if (snprintf(key, sizeof(key), "n_%u", pos) < 1) + { + printf("CreateStealthTransaction(): Error creating narration key."); + continue; + }; + wtx.mapValue[key] = it->second; + }; if(!fCreated) { @@ -225,13 +404,19 @@ WalletModel::SendCoinsReturn WalletModel::sendCoins(const QListcs_wallet); - std::map::iterator mi = wallet->mapAddressBook.find(dest); - - // Check if we have a new address or an updated label - if (mi == wallet->mapAddressBook.end() || mi->second != strLabel) + if (rcp.typeInd == AddressTableModel::AT_Stealth) { - wallet->SetAddressBookName(dest, strLabel); - } + wallet->UpdateStealthAddress(strAddress, strLabel, true); + } else + { + std::map::iterator mi = wallet->mapAddressBook.find(dest); + + // Check if we have a new address or an updated label + if (mi == wallet->mapAddressBook.end() || mi->second != strLabel) + { + wallet->SetAddressBookName(dest, strLabel); + }; + }; } } @@ -263,6 +448,14 @@ WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const { return Locked; } + else if(fWalletUnlockStakingOnly) + { + return Locked; + } + else if (wallet->fWalletUnlockAnonymizeOnly) + { + return UnlockedForAnonymizationOnly; + } else { return Unlocked; @@ -283,7 +476,7 @@ bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphr } } -bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase) +bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase, bool anonymizeOnly) { if(locked) { @@ -293,10 +486,15 @@ bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase) else { // Unlock - return wallet->Unlock(passPhrase); + return wallet->Unlock(passPhrase, anonymizeOnly); } } +bool WalletModel::isAnonymizeOnlyUnlocked() +{ + return wallet->fWalletUnlockAnonymizeOnly; +} + bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass) { bool retval; @@ -322,15 +520,25 @@ static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStor static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status) { - QString strAddress = QString::fromStdString(CBitcoinAddress(address).ToString()); - QString strLabel = QString::fromStdString(label); - - qDebug() << "NotifyAddressBookChanged : " + strAddress + " " + strLabel + " isMine=" + QString::number(isMine) + " status=" + QString::number(status); - QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, - Q_ARG(QString, strAddress), - Q_ARG(QString, strLabel), - Q_ARG(bool, isMine), - Q_ARG(int, status)); + if (address.type() == typeid(CStealthAddress)) + { + CStealthAddress sxAddr = boost::get(address); + std::string enc = sxAddr.Encoded(); + LogPrintf("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", enc.c_str(), label.c_str(), isMine, status); + QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, + Q_ARG(QString, QString::fromStdString(enc)), + Q_ARG(QString, QString::fromStdString(label)), + Q_ARG(bool, isMine), + Q_ARG(int, status)); + } else + { + LogPrintf("NotifyAddressBookChanged %s %s isMine=%i status=%i\n", CBitcoinAddress(address).ToString().c_str(), label.c_str(), isMine, status); + QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection, + Q_ARG(QString, QString::fromStdString(CBitcoinAddress(address).ToString())), + Q_ARG(QString, QString::fromStdString(label)), + Q_ARG(bool, isMine), + Q_ARG(int, status)); + } } static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status) @@ -364,7 +572,7 @@ WalletModel::UnlockContext WalletModel::requestUnlock() { bool was_locked = getEncryptionStatus() == Locked; - if ((!was_locked) && fWalletUnlockStakingOnly) + if ((!was_locked) && fWalletUnlockStakingOnly && isAnonymizeOnlyUnlocked()) { setWalletLocked(true); was_locked = getEncryptionStatus() == Locked; @@ -417,7 +625,7 @@ void WalletModel::getOutputs(const std::vector& vOutpoints, std::vect if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; - COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth); + COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth, true); vOutputs.push_back(out); } } @@ -425,10 +633,10 @@ void WalletModel::getOutputs(const std::vector& vOutpoints, std::vect // AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address) void WalletModel::listCoins(std::map >& mapCoins) const { + LOCK2(cs_main, wallet->cs_wallet); // ListLockedCoins, mapWallet std::vector vCoins; wallet->AvailableCoins(vCoins); - LOCK2(cs_main, wallet->cs_wallet); // ListLockedCoins, mapWallet std::vector vLockedCoins; // add locked coins @@ -437,7 +645,7 @@ void WalletModel::listCoins(std::map >& mapCoins) if (!wallet->mapWallet.count(outpoint.hash)) continue; int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain(); if (nDepth < 0) continue; - COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth); + COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth, true); vCoins.push_back(out); } @@ -448,31 +656,36 @@ void WalletModel::listCoins(std::map >& mapCoins) while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0])) { if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break; - cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0); + cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0, true); } CTxDestination address; - if(!ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue; + if(!out.fSpendable || !ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue; mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out); } } bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const { - return false; + LOCK2(cs_main, wallet->cs_wallet); + return wallet->IsLockedCoin(hash, n); } void WalletModel::lockCoin(COutPoint& output) { - return; + LOCK2(cs_main, wallet->cs_wallet); + wallet->LockCoin(output); } void WalletModel::unlockCoin(COutPoint& output) { - return; + LOCK2(cs_main, wallet->cs_wallet); + wallet->UnlockCoin(output); } void WalletModel::listLockedCoins(std::vector& vOutpts) { - return; + LOCK2(cs_main, wallet->cs_wallet); + wallet->ListLockedCoins(vOutpts); } + diff --git a/src/qt/walletmodel.h b/src/qt/walletmodel.h index 4c0e699..72e4c54 100644 --- a/src/qt/walletmodel.h +++ b/src/qt/walletmodel.h @@ -6,6 +6,8 @@ #include #include "allocators.h" /* for SecureString */ +#include "instantx.h" +#include "wallet.h" class OptionsModel; class AddressTableModel; @@ -27,7 +29,11 @@ class SendCoinsRecipient public: QString address; QString label; + QString narration; + int typeInd; qint64 amount; + AvailableCoinsType inputType; + bool useInstantX; }; /** Interface to Bitcoin wallet from Qt view code. */ @@ -49,14 +55,17 @@ class WalletModel : public QObject DuplicateAddress, TransactionCreationFailed, // Error returned when wallet is still locked TransactionCommitFailed, - Aborted + NarrationTooLong, + Aborted, + AnonymizeOnlyUnlocked }; enum EncryptionStatus { Unencrypted, // !wallet->IsCrypted() Locked, // wallet->IsCrypted() && wallet->IsLocked() - Unlocked // wallet->IsCrypted() && !wallet->IsLocked() + Unlocked, // wallet->IsCrypted() && !wallet->IsLocked() + UnlockedForAnonymizationOnly }; OptionsModel *getOptionsModel(); @@ -67,6 +76,7 @@ class WalletModel : public QObject qint64 getStake() const; qint64 getUnconfirmedBalance() const; qint64 getImmatureBalance() const; + qint64 getAnonymizedBalance() const; EncryptionStatus getEncryptionStatus() const; // Check address for validity @@ -90,8 +100,10 @@ class WalletModel : public QObject // Wallet encryption bool setWalletEncrypted(bool encrypted, const SecureString &passphrase); // Passphrase only needed when unlocking - bool setWalletLocked(bool locked, const SecureString &passPhrase=SecureString()); + bool setWalletLocked(bool locked, const SecureString &passPhrase=SecureString(), bool anonymizeOnly=false); bool changePassphrase(const SecureString &oldPass, const SecureString &newPass); + // Is wallet unlocked for anonymization only? + bool isAnonymizeOnlyUnlocked(); // Wallet backup bool backupWallet(const QString &filename); @@ -140,6 +152,10 @@ class WalletModel : public QObject qint64 cachedStake; qint64 cachedUnconfirmedBalance; qint64 cachedImmatureBalance; + qint64 cachedAnonymizedBalance; + qint64 cachedNumTransactions; + int cachedTxLocks; + int cachedDarksendRounds; EncryptionStatus cachedEncryptionStatus; int cachedNumBlocks; @@ -162,7 +178,7 @@ public slots: signals: // Signal that balance in wallet changed - void balanceChanged(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance); + void balanceChanged(qint64 balance, qint64 stake, qint64 unconfirmedBalance, qint64 immatureBalance, qint64 anonymizedBalance); // Encryption status of wallet changed void encryptionStatusChanged(int status); diff --git a/src/rpcclient.cpp b/src/rpcclient.cpp index 10ef3ac..e6d1742 100644 --- a/src/rpcclient.cpp +++ b/src/rpcclient.cpp @@ -74,7 +74,7 @@ Object CallRPC(const string& strMethod, const Array& params) // Receive HTTP reply message headers and body map mapHeaders; string strReply; - ReadHTTPMessage(stream, mapHeaders, strReply, nProto); + ReadHTTPMessage(stream, mapHeaders, strReply, nProto, MAX_SIZE); if (nStatus == HTTP_UNAUTHORIZED) throw runtime_error("incorrect rpcuser or rpcpassword (authorization failed)"); @@ -152,6 +152,10 @@ static const CRPCConvertParam vRPCConvertParams[] = { "importprivkey", 2 }, { "checkkernel", 0 }, { "checkkernel", 1 }, + { "sendtostealthaddress", 1 }, + { "searchrawtransactions", 1 }, + { "searchrawtransactions", 2 }, + { "searchrawtransactions", 3 }, }; class CRPCConvertTable diff --git a/src/rpcdarksend.cpp b/src/rpcdarksend.cpp new file mode 100644 index 0000000..93c57c9 --- /dev/null +++ b/src/rpcdarksend.cpp @@ -0,0 +1,587 @@ +// Copyright (c) 2010 Satoshi Nakamoto +// Copyright (c) 2009-2012 The Darkcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "main.h" +//#include "primitives/transaction.h" +#include "db.h" +#include "init.h" +#include "masternode.h" +#include "activemasternode.h" +#include "masternodeconfig.h" +#include "rpcserver.h" +#include +//#include "amount.h" +#include "util.h" +//#include "utilmoneystr.h" + +#include +using namespace json_spirit; +using namespace std; + +void SendMoney(const CTxDestination &address, CAmount nValue, CWalletTx& wtxNew, AvailableCoinsType coin_type) +{ + // Check amount + if (nValue <= 0) + throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid amount"); + + if (nValue > pwalletMain->GetBalance()) + throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Insufficient funds"); + + string strError; + if (pwalletMain->IsLocked()) + { + strError = "Error: Wallet locked, unable to create transaction!"; + LogPrintf("SendMoney() : %s", strError); + throw JSONRPCError(RPC_WALLET_ERROR, strError); + } + + // Parse genius address + CScript scriptPubKey = GetScriptForDestination(address); + + // Create and send the transaction + CReserveKey reservekey(pwalletMain); + int64_t nFeeRequired; + std::string sNarr; + if (!pwalletMain->CreateTransaction(scriptPubKey, nValue, sNarr, wtxNew, reservekey, nFeeRequired, NULL)) + { + if (nValue + nFeeRequired > pwalletMain->GetBalance()) + strError = strprintf("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!", FormatMoney(nFeeRequired)); + LogPrintf("SendMoney() : %s\n", strError); + throw JSONRPCError(RPC_WALLET_ERROR, strError); + } + if (!pwalletMain->CommitTransaction(wtxNew, reservekey)) + throw JSONRPCError(RPC_WALLET_ERROR, "Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); +} + +Value darksend(const Array& params, bool fHelp) +{ + if (fHelp || params.size() == 0) + throw runtime_error( + "darksend \n" + "geniusaddress, reset, or auto (AutoDenominate)" + " is a real and is rounded to the nearest 0.00000001" + + HelpRequiringPassphrase()); + + if (pwalletMain->IsLocked()) + throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); + + if(params[0].get_str() == "auto"){ + if(fMasterNode) + return "DarkSend is not supported from masternodes"; + + darkSendPool.DoAutomaticDenominating(); + return "DoAutomaticDenominating"; + } + + if(params[0].get_str() == "reset"){ + darkSendPool.SetNull(true); + darkSendPool.UnlockCoins(); + return "successfully reset darksend"; + } + + if (params.size() != 2) + throw runtime_error( + "darksend \n" + "geniusaddress, denominate, or auto (AutoDenominate)" + " is a real and is rounded to the nearest 0.00000001" + + HelpRequiringPassphrase()); + + CBitcoinAddress address(params[0].get_str()); + if (!address.IsValid()) + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid genius address"); + + // Amount + int64_t nAmount = AmountFromValue(params[1]); + + // Wallet comments + CWalletTx wtx; + SendMoney(address.Get(), nAmount, wtx, ONLY_DENOMINATED); + + return wtx.GetHash().GetHex(); +} + + +Value getpoolinfo(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 0) + throw runtime_error( + "getpoolinfo\n" + "Returns an object containing anonymous pool-related information."); + + Object obj; + obj.push_back(Pair("current_masternode", GetCurrentMasterNode())); + obj.push_back(Pair("state", darkSendPool.GetState())); + obj.push_back(Pair("entries", darkSendPool.GetEntriesCount())); + obj.push_back(Pair("entries_accepted", darkSendPool.GetCountEntriesAccepted())); + return obj; +} + + +Value masternode(const Array& params, bool fHelp) +{ + string strCommand; + if (params.size() >= 1) + strCommand = params[0].get_str(); + + if (fHelp || + (strCommand != "start" && strCommand != "start-alias" && strCommand != "start-many" && strCommand != "stop" && strCommand != "stop-alias" && strCommand != "stop-many" && strCommand != "list" && strCommand != "list-conf" && strCommand != "count" && strCommand != "enforce" + && strCommand != "debug" && strCommand != "current" && strCommand != "winners" && strCommand != "genkey" && strCommand != "connect" && strCommand != "outputs")) + throw runtime_error( + "masternode [passphrase]\n"); + + if (strCommand == "stop") + { + if(!fMasterNode) return "you must set masternode=1 in the configuration"; + + if(pwalletMain->IsLocked()) { + SecureString strWalletPass; + strWalletPass.reserve(100); + + if (params.size() == 2){ + strWalletPass = params[1].get_str().c_str(); + } else { + throw runtime_error( + "Your wallet is locked, passphrase is required\n"); + } + + if(!pwalletMain->Unlock(strWalletPass)){ + return "incorrect passphrase"; + } + } + + std::string errorMessage; + if(!activeMasternode.StopMasterNode(errorMessage)) { + return "stop failed: " + errorMessage; + } + pwalletMain->Lock(); + + if(activeMasternode.status == MASTERNODE_STOPPED) return "successfully stopped masternode"; + if(activeMasternode.status == MASTERNODE_NOT_CAPABLE) return "not capable masternode"; + + return "unknown"; + } + + if (strCommand == "stop-alias") + { + if (params.size() < 2){ + throw runtime_error( + "command needs at least 2 parameters\n"); + } + + std::string alias = params[1].get_str().c_str(); + + if(pwalletMain->IsLocked()) { + SecureString strWalletPass; + strWalletPass.reserve(100); + + if (params.size() == 3){ + strWalletPass = params[2].get_str().c_str(); + } else { + throw runtime_error( + "Your wallet is locked, passphrase is required\n"); + } + + if(!pwalletMain->Unlock(strWalletPass)){ + return "incorrect passphrase"; + } + } + + bool found = false; + + Object statusObj; + statusObj.push_back(Pair("alias", alias)); + + BOOST_FOREACH(CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { + if(mne.getAlias() == alias) { + found = true; + std::string errorMessage; + bool result = activeMasternode.StopMasterNode(mne.getIp(), mne.getPrivKey(), errorMessage); + + statusObj.push_back(Pair("result", result ? "successful" : "failed")); + if(!result) { + statusObj.push_back(Pair("errorMessage", errorMessage)); + } + break; + } + } + + if(!found) { + statusObj.push_back(Pair("result", "failed")); + statusObj.push_back(Pair("errorMessage", "could not find alias in config. Verify with list-conf.")); + } + + pwalletMain->Lock(); + return statusObj; + } + + if (strCommand == "stop-many") + { + if(pwalletMain->IsLocked()) { + SecureString strWalletPass; + strWalletPass.reserve(100); + + if (params.size() == 2){ + strWalletPass = params[1].get_str().c_str(); + } else { + throw runtime_error( + "Your wallet is locked, passphrase is required\n"); + } + + if(!pwalletMain->Unlock(strWalletPass)){ + return "incorrect passphrase"; + } + } + + int total = 0; + int successful = 0; + int fail = 0; + + + Object resultsObj; + + BOOST_FOREACH(CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { + total++; + + std::string errorMessage; + bool result = activeMasternode.StopMasterNode(mne.getIp(), mne.getPrivKey(), errorMessage); + + Object statusObj; + statusObj.push_back(Pair("alias", mne.getAlias())); + statusObj.push_back(Pair("result", result ? "successful" : "failed")); + + if(result) { + successful++; + } else { + fail++; + statusObj.push_back(Pair("errorMessage", errorMessage)); + } + + resultsObj.push_back(Pair("status", statusObj)); + } + pwalletMain->Lock(); + + Object returnObj; + returnObj.push_back(Pair("overall", "Successfully stopped " + boost::lexical_cast(successful) + " masternodes, failed to stop " + + boost::lexical_cast(fail) + ", total " + boost::lexical_cast(total))); + returnObj.push_back(Pair("detail", resultsObj)); + + return returnObj; + + } + + if (strCommand == "list") + { + std::string strCommand = "active"; + + if (params.size() == 2){ + strCommand = params[1].get_str().c_str(); + } + + if (strCommand != "active" && strCommand != "vin" && strCommand != "pubkey" && strCommand != "lastseen" && strCommand != "activeseconds" && strCommand != "rank" && strCommand != "protocol"){ + throw runtime_error( + "list supports 'active', 'vin', 'pubkey', 'lastseen', 'activeseconds', 'rank', 'protocol'\n"); + } + + Object obj; + BOOST_FOREACH(CMasterNode mn, vecMasternodes) { + mn.Check(); + + if(strCommand == "active"){ + obj.push_back(Pair(mn.addr.ToString().c_str(), (int)mn.IsEnabled())); + } else if (strCommand == "vin") { + obj.push_back(Pair(mn.addr.ToString().c_str(), mn.vin.prevout.hash.ToString().c_str())); + } else if (strCommand == "pubkey") { + CScript pubkey; + pubkey =GetScriptForDestination(mn.pubkey.GetID()); + CTxDestination address1; + ExtractDestination(pubkey, address1); + CBitcoinAddress address2(address1); + + obj.push_back(Pair(mn.addr.ToString().c_str(), address2.ToString().c_str())); + } else if (strCommand == "protocol") { + obj.push_back(Pair(mn.addr.ToString().c_str(), (int64_t)mn.protocolVersion)); + } else if (strCommand == "lastseen") { + obj.push_back(Pair(mn.addr.ToString().c_str(), (int64_t)mn.lastTimeSeen)); + } else if (strCommand == "activeseconds") { + obj.push_back(Pair(mn.addr.ToString().c_str(), (int64_t)(mn.lastTimeSeen - mn.now))); + } else if (strCommand == "rank") { + obj.push_back(Pair(mn.addr.ToString().c_str(), (int)(GetMasternodeRank(mn.vin, pindexBest->nHeight)))); + } + } + return obj; + } + if (strCommand == "count") return (int)vecMasternodes.size(); + + if (strCommand == "start") + { + if(!fMasterNode) return "you must set masternode=1 in the configuration"; + + if(pwalletMain->IsLocked()) { + SecureString strWalletPass; + strWalletPass.reserve(100); + + if (params.size() == 2){ + strWalletPass = params[1].get_str().c_str(); + } else { + throw runtime_error( + "Your wallet is locked, passphrase is required\n"); + } + + if(!pwalletMain->Unlock(strWalletPass)){ + return "incorrect passphrase"; + } + } + + if(activeMasternode.status != MASTERNODE_REMOTELY_ENABLED && activeMasternode.status != MASTERNODE_IS_CAPABLE){ + activeMasternode.status = MASTERNODE_NOT_PROCESSED; // TODO: consider better way + std::string errorMessage; + activeMasternode.ManageStatus(); + pwalletMain->Lock(); + } + + if(activeMasternode.status == MASTERNODE_REMOTELY_ENABLED) return "masternode started remotely"; + if(activeMasternode.status == MASTERNODE_INPUT_TOO_NEW) return "masternode input must have at least 15 confirmations"; + if(activeMasternode.status == MASTERNODE_STOPPED) return "masternode is stopped"; + if(activeMasternode.status == MASTERNODE_IS_CAPABLE) return "successfully started masternode"; + if(activeMasternode.status == MASTERNODE_NOT_CAPABLE) return "not capable masternode: " + activeMasternode.notCapableReason; + if(activeMasternode.status == MASTERNODE_SYNC_IN_PROCESS) return "sync in process. Must wait until client is synced to start."; + + return "unknown"; + } + + if (strCommand == "start-alias") + { + if (params.size() < 2){ + throw runtime_error( + "command needs at least 2 parameters\n"); + } + + std::string alias = params[1].get_str().c_str(); + + if(pwalletMain->IsLocked()) { + SecureString strWalletPass; + strWalletPass.reserve(100); + + if (params.size() == 3){ + strWalletPass = params[2].get_str().c_str(); + } else { + throw runtime_error( + "Your wallet is locked, passphrase is required\n"); + } + + if(!pwalletMain->Unlock(strWalletPass)){ + return "incorrect passphrase"; + } + } + + bool found = false; + + Object statusObj; + statusObj.push_back(Pair("alias", alias)); + + BOOST_FOREACH(CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { + if(mne.getAlias() == alias) { + found = true; + std::string errorMessage; + bool result = activeMasternode.Register(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), errorMessage); + + statusObj.push_back(Pair("result", result ? "successful" : "failed")); + if(!result) { + statusObj.push_back(Pair("errorMessage", errorMessage)); + } + break; + } + } + + if(!found) { + statusObj.push_back(Pair("result", "failed")); + statusObj.push_back(Pair("errorMessage", "could not find alias in config. Verify with list-conf.")); + } + + pwalletMain->Lock(); + return statusObj; + + } + + if (strCommand == "start-many") + { + if(pwalletMain->IsLocked()) { + SecureString strWalletPass; + strWalletPass.reserve(100); + + if (params.size() == 2){ + strWalletPass = params[1].get_str().c_str(); + } else { + throw runtime_error( + "Your wallet is locked, passphrase is required\n"); + } + + if(!pwalletMain->Unlock(strWalletPass)){ + return "incorrect passphrase"; + } + } + + std::vector mnEntries; + mnEntries = masternodeConfig.getEntries(); + + int total = 0; + int successful = 0; + int fail = 0; + + Object resultsObj; + + BOOST_FOREACH(CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { + total++; + + std::string errorMessage; + bool result = activeMasternode.Register(mne.getIp(), mne.getPrivKey(), mne.getTxHash(), mne.getOutputIndex(), errorMessage); + + Object statusObj; + statusObj.push_back(Pair("alias", mne.getAlias())); + statusObj.push_back(Pair("result", result ? "succesful" : "failed")); + + if(result) { + successful++; + } else { + fail++; + statusObj.push_back(Pair("errorMessage", errorMessage)); + } + + resultsObj.push_back(Pair("status", statusObj)); + } + pwalletMain->Lock(); + + Object returnObj; + returnObj.push_back(Pair("overall", "Successfully started " + boost::lexical_cast(successful) + " masternodes, failed to start " + + boost::lexical_cast(fail) + ", total " + boost::lexical_cast(total))); + returnObj.push_back(Pair("detail", resultsObj)); + + return returnObj; + } + + if (strCommand == "debug") + { + if(activeMasternode.status == MASTERNODE_REMOTELY_ENABLED) return "masternode started remotely"; + if(activeMasternode.status == MASTERNODE_INPUT_TOO_NEW) return "masternode input must have at least 15 confirmations"; + if(activeMasternode.status == MASTERNODE_IS_CAPABLE) return "successfully started masternode"; + if(activeMasternode.status == MASTERNODE_STOPPED) return "masternode is stopped"; + if(activeMasternode.status == MASTERNODE_NOT_CAPABLE) return "not capable masternode: " + activeMasternode.notCapableReason; + if(activeMasternode.status == MASTERNODE_SYNC_IN_PROCESS) return "sync in process. Must wait until client is synced to start."; + + CTxIn vin = CTxIn(); + CPubKey pubkey = CScript(); + CKey key; + bool found = activeMasternode.GetMasterNodeVin(vin, pubkey, key); + if(!found){ + return "Missing masternode input, please look at the documentation for instructions on masternode creation"; + } else { + return "No problems were found"; + } + } + + if (strCommand == "create") + { + + return "Not implemented yet, please look at the documentation for instructions on masternode creation"; + } + + if (strCommand == "current") + { + int winner = GetCurrentMasterNode(1); + if(winner >= 0) { + return vecMasternodes[winner].addr.ToString().c_str(); + } + + return "unknown"; + } + + if (strCommand == "genkey") + { + CKey secret; + secret.MakeNewKey(false); + + return CBitcoinSecret(secret).ToString(); + } + + if (strCommand == "winners") + { + Object obj; + + for(int nHeight = pindexBest->nHeight-10; nHeight < pindexBest->nHeight+20; nHeight++) + { + CScript payee; + if(masternodePayments.GetBlockPayee(nHeight, payee)){ + CTxDestination address1; + ExtractDestination(payee, address1); + CBitcoinAddress address2(address1); + obj.push_back(Pair(boost::lexical_cast(nHeight), address2.ToString().c_str())); + } else { + obj.push_back(Pair(boost::lexical_cast(nHeight), "")); + } + } + + return obj; + } + + if(strCommand == "enforce") + { + return (uint64_t)enforceMasternodePaymentsTime; + } + + if(strCommand == "connect") + { + std::string strAddress = ""; + if (params.size() == 2){ + strAddress = params[1].get_str().c_str(); + } else { + throw runtime_error( + "Masternode address required\n"); + } + + CService addr = CService(strAddress); + + if(ConnectNode((CAddress)addr, NULL, true)){ + return "successfully connected"; + } else { + return "error connecting"; + } + } + + if(strCommand == "list-conf") + { + std::vector mnEntries; + mnEntries = masternodeConfig.getEntries(); + + Object resultObj; + + BOOST_FOREACH(CMasternodeConfig::CMasternodeEntry mne, masternodeConfig.getEntries()) { + Object mnObj; + mnObj.push_back(Pair("alias", mne.getAlias())); + mnObj.push_back(Pair("address", mne.getIp())); + mnObj.push_back(Pair("privateKey", mne.getPrivKey())); + mnObj.push_back(Pair("txHash", mne.getTxHash())); + mnObj.push_back(Pair("outputIndex", mne.getOutputIndex())); + resultObj.push_back(Pair("masternode", mnObj)); + } + + return resultObj; + } + + if (strCommand == "outputs"){ + // Find possible candidates + vector possibleCoins = activeMasternode.SelectCoinsMasternode(); + + Object obj; + BOOST_FOREACH(COutput& out, possibleCoins) { + obj.push_back(Pair(out.tx->GetHash().ToString().c_str(), boost::lexical_cast(out.i))); + } + + return obj; + + } + + return Value::null; +} + diff --git a/src/rpcmisc.cpp b/src/rpcmisc.cpp index 93bf857..d971262 100644 --- a/src/rpcmisc.cpp +++ b/src/rpcmisc.cpp @@ -11,6 +11,8 @@ #include "rpcserver.h" #include "timedata.h" #include "util.h" +#include "stealth.h" +#include "spork.h" #ifdef ENABLE_WALLET #include "wallet.h" #include "walletdb.h" @@ -109,6 +111,12 @@ class DescribeAddressVisitor : public boost::static_visitor obj.push_back(Pair("sigsrequired", nRequired)); return obj; } + + Object operator()(const CStealthAddress &stxAddr) const { + Object obj; + obj.push_back(Pair("todo", true)); + return obj; + } }; #endif @@ -217,3 +225,43 @@ Value verifymessage(const Array& params, bool fHelp) return (pubkey.GetID() == keyID); } + +/* + Used for updating/reading spork settings on the network +*/ +Value spork(const Array& params, bool fHelp) +{ + if(params.size() == 1 && params[0].get_str() == "show"){ + std::map::iterator it = mapSporksActive.begin(); + + Object ret; + while(it != mapSporksActive.end()) { + ret.push_back(Pair(sporkManager.GetSporkNameByID(it->second.nSporkID), it->second.nValue)); + it++; + } + return ret; + } else if (params.size() == 2){ + int nSporkID = sporkManager.GetSporkIDByName(params[0].get_str()); + if(nSporkID == -1){ + return "Invalid spork name"; + } + + // SPORK VALUE + int64_t nValue = params[1].get_int(); + + //broadcast new spork + if(sporkManager.UpdateSpork(nSporkID, nValue)){ + return "success"; + } else { + return "failure"; + } + + } + + throw runtime_error( + "spork []\n" + " is the corresponding spork name, or 'show' to show all current spork settings" + " is a epoch datetime to enable or disable spork" + + HelpRequiringPassphrase()); +} + diff --git a/src/rpcprotocol.cpp b/src/rpcprotocol.cpp index 925ee12..23497d1 100644 --- a/src/rpcprotocol.cpp +++ b/src/rpcprotocol.cpp @@ -177,14 +177,14 @@ int ReadHTTPHeaders(std::basic_istream& stream, map& mapHe int ReadHTTPMessage(std::basic_istream& stream, map& mapHeadersRet, string& strMessageRet, - int nProto) + int nProto, size_t max_size) { mapHeadersRet.clear(); strMessageRet = ""; // Read header int nLen = ReadHTTPHeaders(stream, mapHeadersRet); - if (nLen < 0 || nLen > (int)MAX_SIZE) + if (nLen < 0 || (size_t)nLen > max_size) return HTTP_INTERNAL_SERVER_ERROR; // Read message diff --git a/src/rpcprotocol.h b/src/rpcprotocol.h index a5da6fe..9a18779 100644 --- a/src/rpcprotocol.h +++ b/src/rpcprotocol.h @@ -131,7 +131,7 @@ bool ReadHTTPRequestLine(std::basic_istream& stream, int &proto, int ReadHTTPStatus(std::basic_istream& stream, int &proto); int ReadHTTPHeaders(std::basic_istream& stream, std::map& mapHeadersRet); int ReadHTTPMessage(std::basic_istream& stream, std::map& mapHeadersRet, - std::string& strMessageRet, int nProto); + std::string& strMessageRet, int nProto, size_t max_size); std::string JSONRPCRequest(const std::string& strMethod, const json_spirit::Array& params, const json_spirit::Value& id); json_spirit::Object JSONRPCReplyObj(const json_spirit::Value& result, const json_spirit::Value& error, const json_spirit::Value& id); std::string JSONRPCReply(const json_spirit::Value& result, const json_spirit::Value& error, const json_spirit::Value& id); diff --git a/src/rpcrawtransaction.cpp b/src/rpcrawtransaction.cpp index 4414c12..c9ff66a 100644 --- a/src/rpcrawtransaction.cpp +++ b/src/rpcrawtransaction.cpp @@ -596,3 +596,71 @@ Value sendrawtransaction(const Array& params, bool fHelp) return hashTx.GetHex(); } + + +Value searchrawtransactions(const Array ¶ms, bool fHelp) +{ + if (fHelp || params.size() < 1 || params.size() > 4) + throw runtime_error( + "searchrawtransactions
[verbose=1] [skip=0] [count=100]\n"); + + CBitcoinAddress address(params[0].get_str()); + if (!address.IsValid()) + throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid Bitcoin address"); + CTxDestination dest = address.Get(); + + std::vector vtxhash; + if (!FindTransactionsByDestination(dest, vtxhash)) + throw JSONRPCError(RPC_DATABASE_ERROR, "Cannot search for address"); + + int nSkip = 0; + int nCount = 100; + bool fVerbose = true; + if (params.size() > 1) + fVerbose = (params[1].get_int() != 0); + if (params.size() > 2) + nSkip = params[2].get_int(); + if (params.size() > 3) + nCount = params[3].get_int(); + + if (nSkip < 0) + nSkip += vtxhash.size(); + if (nSkip < 0) + nSkip = 0; + if (nCount < 0) + nCount = 0; + + std::vector::const_iterator it = vtxhash.begin(); + while (it != vtxhash.end() && nSkip--) it++; + + Array result; + while (it != vtxhash.end() && nCount--) { + CTransaction tx; + uint256 hashBlock; + if (!GetTransaction(*it, tx, hashBlock)) + { + // throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Cannot read transaction from disk"); + Object obj; + obj.push_back(Pair("ERROR", "Cannot read transaction from disk")); + result.push_back(obj); + } + else + { + + CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); + ssTx << tx; + string strHex = HexStr(ssTx.begin(), ssTx.end()); + if (fVerbose) { + Object object; + TxToJSON(tx, hashBlock, object); + object.push_back(Pair("hex", strHex)); + result.push_back(object); + } else { + result.push_back(strHex); + } + + } + it++; + } + return result; +} diff --git a/src/rpcserver.cpp b/src/rpcserver.cpp index 0d39c72..25ccea1 100644 --- a/src/rpcserver.cpp +++ b/src/rpcserver.cpp @@ -245,6 +245,12 @@ static const CRPCCommand vRPCCommands[] = { "validateaddress", &validateaddress, true, false, false }, { "validatepubkey", &validatepubkey, true, false, false }, { "verifymessage", &verifymessage, false, false, false }, + { "searchrawtransactions", &searchrawtransactions, false, false, false }, + +/* Dark features */ + { "darksend", &darksend, false, false, true }, + { "spork", &spork, true, false, false }, + { "masternode", &masternode, true, false, true }, #ifdef ENABLE_WALLET { "getmininginfo", &getmininginfo, true, false, false }, @@ -296,6 +302,23 @@ static const CRPCCommand vRPCCommands[] = { "resendtx", &resendtx, false, true, true }, { "makekeypair", &makekeypair, false, true, false }, { "checkkernel", &checkkernel, true, false, true }, + { "getnewstealthaddress", &getnewstealthaddress, false, false, true}, + { "liststealthaddresses", &liststealthaddresses, false, false, true}, + { "importstealthaddress", &importstealthaddress, false, false, true}, + { "sendtostealthaddress", &sendtostealthaddress, false, false, true}, + { "smsgenable", &smsgenable, false, false, false }, + { "smsgdisable", &smsgdisable, false, false, false }, + { "smsglocalkeys", &smsglocalkeys, false, false, false }, + { "smsgoptions", &smsgoptions, false, false, false }, + { "smsgscanchain", &smsgscanchain, false, false, false }, + { "smsgscanbuckets", &smsgscanbuckets, false, false, false }, + { "smsgaddkey", &smsgaddkey, false, false, false }, + { "smsggetpubkey", &smsggetpubkey, false, false, false }, + { "smsgsend", &smsgsend, false, false, false }, + { "smsgsendanon", &smsgsendanon, false, false, false }, + { "smsginbox", &smsginbox, false, false, false }, + { "smsgoutbox", &smsgoutbox, false, false, false }, + { "smsgbuckets", &smsgbuckets, false, false, false }, #endif }; @@ -723,7 +746,7 @@ void ServiceConnection(AcceptedConnection *conn) break; // Read HTTP message headers and body - ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto); + ReadHTTPMessage(conn->stream(), mapHeaders, strRequest, nProto, MAX_SIZE); if (strURI != "/") { conn->stream() << HTTPReply(HTTP_NOT_FOUND, "", false) << std::flush; diff --git a/src/rpcserver.h b/src/rpcserver.h index 5a9b0bd..2367241 100644 --- a/src/rpcserver.h +++ b/src/rpcserver.h @@ -160,6 +160,8 @@ extern json_spirit::Value validatepubkey(const json_spirit::Array& params, bool extern json_spirit::Value getnewpubkey(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getrawtransaction(const json_spirit::Array& params, bool fHelp); // in rcprawtransaction.cpp +extern json_spirit::Value searchrawtransactions(const json_spirit::Array& params, bool fHelp); + extern json_spirit::Value listunspent(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value createrawtransaction(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value decoderawtransaction(const json_spirit::Array& params, bool fHelp); @@ -177,4 +179,26 @@ extern json_spirit::Value getblock(const json_spirit::Array& params, bool fHelp) extern json_spirit::Value getblockbynumber(const json_spirit::Array& params, bool fHelp); extern json_spirit::Value getcheckpoint(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value getnewstealthaddress(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value liststealthaddresses(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value importstealthaddress(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value sendtostealthaddress(const json_spirit::Array& params, bool fHelp); + +extern json_spirit::Value darksend(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value spork(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value masternode(const json_spirit::Array& params, bool fHelp); + +extern json_spirit::Value smsgenable(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value smsgdisable(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value smsglocalkeys(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value smsgoptions(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value smsgscanchain(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value smsgscanbuckets(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value smsgaddkey(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value smsggetpubkey(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value smsgsend(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value smsgsendanon(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value smsginbox(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value smsgoutbox(const json_spirit::Array& params, bool fHelp); +extern json_spirit::Value smsgbuckets(const json_spirit::Array& params, bool fHelp); #endif diff --git a/src/rpcsmessage.cpp b/src/rpcsmessage.cpp new file mode 100644 index 0000000..cda4334 --- /dev/null +++ b/src/rpcsmessage.cpp @@ -0,0 +1,895 @@ +// Copyright (c) 2014 The ShadowCoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "main.h" +#include "rpcserver.h" + +#include + +#include "smessage.h" +#include "init.h" // pwalletMain + +using namespace json_spirit; +using namespace std; + +extern void TxToJSON(const CTransaction& tx, const uint256 hashBlock, json_spirit::Object& entry); + + + +Value smsgenable(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 0) + throw runtime_error( + "smsgenable \n" + "Enable secure messaging."); + + if (fSecMsgEnabled) + throw runtime_error("Secure messaging is already enabled."); + + Object result; + if (!SecureMsgEnable()) + { + result.push_back(Pair("result", "Failed to enable secure messaging.")); + } else + { + result.push_back(Pair("result", "Enabled secure messaging.")); + } + return result; +} + +Value smsgdisable(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 0) + throw runtime_error( + "smsgdisable \n" + "Disable secure messaging."); + if (!fSecMsgEnabled) + throw runtime_error("Secure messaging is already disabled."); + + Object result; + if (!SecureMsgDisable()) + { + result.push_back(Pair("result", "Failed to disable secure messaging.")); + } else + { + result.push_back(Pair("result", "Disabled secure messaging.")); + } + return result; +} + +Value smsgoptions(const Array& params, bool fHelp) +{ + if (fHelp || params.size() > 3) + throw runtime_error( + "smsgoptions [list|set ]\n" + "List and manage options."); + + std::string mode = "list"; + if (params.size() > 0) + { + mode = params[0].get_str(); + }; + + Object result; + + if (mode == "list") + { + result.push_back(Pair("option", std::string("newAddressRecv = ") + (smsgOptions.fNewAddressRecv ? "true" : "false"))); + result.push_back(Pair("option", std::string("newAddressAnon = ") + (smsgOptions.fNewAddressAnon ? "true" : "false"))); + + result.push_back(Pair("result", "Success.")); + } else + if (mode == "set") + { + if (params.size() < 3) + { + result.push_back(Pair("result", "Too few parameters.")); + result.push_back(Pair("expected", "set ")); + return result; + }; + + std::string optname = params[1].get_str(); + std::string value = params[2].get_str(); + + if (optname == "newAddressRecv") + { + if (value == "+" || value == "on" || value == "true" || value == "1") + { + smsgOptions.fNewAddressRecv = true; + } else + if (value == "-" || value == "off" || value == "false" || value == "0") + { + smsgOptions.fNewAddressRecv = false; + } else + { + result.push_back(Pair("result", "Unknown value.")); + return result; + }; + result.push_back(Pair("set option", std::string("newAddressRecv = ") + (smsgOptions.fNewAddressRecv ? "true" : "false"))); + } else + if (optname == "newAddressAnon") + { + if (value == "+" || value == "on" || value == "true" || value == "1") + { + smsgOptions.fNewAddressAnon = true; + } else + if (value == "-" || value == "off" || value == "false" || value == "0") + { + smsgOptions.fNewAddressAnon = false; + } else + { + result.push_back(Pair("result", "Unknown value.")); + return result; + }; + result.push_back(Pair("set option", std::string("newAddressAnon = ") + (smsgOptions.fNewAddressAnon ? "true" : "false"))); + } else + { + result.push_back(Pair("result", "Option not found.")); + return result; + }; + } else + { + result.push_back(Pair("result", "Unknown Mode.")); + result.push_back(Pair("expected", "smsgoption [list|set ]")); + }; + return result; +} + +Value smsglocalkeys(const Array& params, bool fHelp) +{ + if (fHelp || params.size() > 3) + throw runtime_error( + "smsglocalkeys [whitelist|all|wallet|recv <+/->
|anon <+/->
]\n" + "List and manage keys."); + + if (!fSecMsgEnabled) + throw runtime_error("Secure messaging is disabled."); + + Object result; + + std::string mode = "whitelist"; + if (params.size() > 0) + { + mode = params[0].get_str(); + }; + + char cbuf[256]; + + if (mode == "whitelist" + || mode == "all") + { + uint32_t nKeys = 0; + int all = mode == "all" ? 1 : 0; + for (std::vector::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it) + { + if (!all + && !it->fReceiveEnabled) + continue; + + CBitcoinAddress coinAddress(it->sAddress); + if (!coinAddress.IsValid()) + continue; + + std::string sPublicKey; + + CKeyID keyID; + if (!coinAddress.GetKeyID(keyID)) + continue; + + CPubKey pubKey; + if (!pwalletMain->GetPubKey(keyID, pubKey)) + continue; + if (!pubKey.IsValid() + || !pubKey.IsCompressed()) + { + continue; + }; + + + sPublicKey = EncodeBase58(pubKey.Raw()); + + std::string sLabel = pwalletMain->mapAddressBook[keyID]; + std::string sInfo; + if (all) + sInfo = std::string("Receive ") + (it->fReceiveEnabled ? "on, " : "off, "); + sInfo += std::string("Anon ") + (it->fReceiveAnon ? "on" : "off"); + result.push_back(Pair("key", it->sAddress + " - " + sPublicKey + " " + sInfo + " - " + sLabel)); + + nKeys++; + }; + + + snprintf(cbuf, sizeof(cbuf), "%u keys listed.", nKeys); + result.push_back(Pair("result", std::string(cbuf))); + + } else + if (mode == "recv") + { + if (params.size() < 3) + { + result.push_back(Pair("result", "Too few parameters.")); + result.push_back(Pair("expected", "recv <+/->
")); + return result; + }; + + std::string op = params[1].get_str(); + std::string addr = params[2].get_str(); + + std::vector::iterator it; + for (it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it) + { + if (addr != it->sAddress) + continue; + break; + }; + + if (it == smsgAddresses.end()) + { + result.push_back(Pair("result", "Address not found.")); + return result; + }; + + if (op == "+" || op == "on" || op == "add" || op == "a") + { + it->fReceiveEnabled = true; + } else + if (op == "-" || op == "off" || op == "rem" || op == "r") + { + it->fReceiveEnabled = false; + } else + { + result.push_back(Pair("result", "Unknown operation.")); + return result; + }; + + std::string sInfo; + sInfo = std::string("Receive ") + (it->fReceiveEnabled ? "on, " : "off,"); + sInfo += std::string("Anon ") + (it->fReceiveAnon ? "on" : "off"); + result.push_back(Pair("result", "Success.")); + result.push_back(Pair("key", it->sAddress + " " + sInfo)); + return result; + + } else + if (mode == "anon") + { + if (params.size() < 3) + { + result.push_back(Pair("result", "Too few parameters.")); + result.push_back(Pair("expected", "anon <+/->
")); + return result; + }; + + std::string op = params[1].get_str(); + std::string addr = params[2].get_str(); + + std::vector::iterator it; + for (it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it) + { + if (addr != it->sAddress) + continue; + break; + }; + + if (it == smsgAddresses.end()) + { + result.push_back(Pair("result", "Address not found.")); + return result; + }; + + if (op == "+" || op == "on" || op == "add" || op == "a") + { + it->fReceiveAnon = true; + } else + if (op == "-" || op == "off" || op == "rem" || op == "r") + { + it->fReceiveAnon = false; + } else + { + result.push_back(Pair("result", "Unknown operation.")); + return result; + }; + + std::string sInfo; + sInfo = std::string("Receive ") + (it->fReceiveEnabled ? "on, " : "off,"); + sInfo += std::string("Anon ") + (it->fReceiveAnon ? "on" : "off"); + result.push_back(Pair("result", "Success.")); + result.push_back(Pair("key", it->sAddress + " " + sInfo)); + return result; + + } else + if (mode == "wallet") + { + uint32_t nKeys = 0; + BOOST_FOREACH(const PAIRTYPE(CTxDestination, std::string)& entry, pwalletMain->mapAddressBook) + { + if (!IsMine(*pwalletMain, entry.first)) + continue; + + CBitcoinAddress coinAddress(entry.first); + if (!coinAddress.IsValid()) + continue; + + std::string address; + std::string sPublicKey; + address = coinAddress.ToString(); + + CKeyID keyID; + if (!coinAddress.GetKeyID(keyID)) + continue; + + CPubKey pubKey; + if (!pwalletMain->GetPubKey(keyID, pubKey)) + continue; + if (!pubKey.IsValid() + || !pubKey.IsCompressed()) + { + continue; + }; + + sPublicKey = EncodeBase58(pubKey.Raw()); + + result.push_back(Pair("key", address + " - " + sPublicKey + " - " + entry.second)); + nKeys++; + }; + + snprintf(cbuf, sizeof(cbuf), "%u keys listed from wallet.", nKeys); + result.push_back(Pair("result", std::string(cbuf))); + } else + { + result.push_back(Pair("result", "Unknown Mode.")); + result.push_back(Pair("expected", "smsglocalkeys [whitelist|all|wallet|recv <+/->
|anon <+/->
]")); + }; + + return result; +}; + +Value smsgscanchain(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 0) + throw runtime_error( + "smsgscanchain \n" + "Look for public keys in the block chain."); + + if (!fSecMsgEnabled) + throw runtime_error("Secure messaging is disabled."); + + Object result; + if (!SecureMsgScanBlockChain()) + { + result.push_back(Pair("result", "Scan Chain Failed.")); + } else + { + result.push_back(Pair("result", "Scan Chain Completed.")); + } + return result; +} + +Value smsgscanbuckets(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 0) + throw runtime_error( + "smsgscanbuckets \n" + "Force rescan of all messages in the bucket store."); + + if (!fSecMsgEnabled) + throw runtime_error("Secure messaging is disabled."); + + if (pwalletMain->IsLocked()) + throw runtime_error("Wallet is locked."); + + Object result; + if (!SecureMsgScanBuckets()) + { + result.push_back(Pair("result", "Scan Buckets Failed.")); + } else + { + result.push_back(Pair("result", "Scan Buckets Completed.")); + } + return result; +} + +Value smsgaddkey(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 2) + throw runtime_error( + "smsgaddkey
\n" + "Add address, pubkey pair to database."); + + if (!fSecMsgEnabled) + throw runtime_error("Secure messaging is disabled."); + + std::string addr = params[0].get_str(); + std::string pubk = params[1].get_str(); + + Object result; + int rv = SecureMsgAddAddress(addr, pubk); + if (rv != 0) + { + result.push_back(Pair("result", "Public key not added to db.")); + switch (rv) + { + case 2: result.push_back(Pair("reason", "publicKey is invalid.")); break; + case 3: result.push_back(Pair("reason", "publicKey does not match address.")); break; + case 4: result.push_back(Pair("reason", "address is already in db.")); break; + case 5: result.push_back(Pair("reason", "address is invalid.")); break; + default: result.push_back(Pair("reason", "error.")); break; + }; + } else + { + result.push_back(Pair("result", "Added public key to db.")); + }; + + return result; +} + +Value smsggetpubkey(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 1) + throw runtime_error( + "smsggetpubkey
\n" + "Return the base58 encoded compressed public key for an address.\n" + "Tests localkeys first, then looks in public key db.\n"); + + if (!fSecMsgEnabled) + throw runtime_error("Secure messaging is disabled."); + + + std::string address = params[0].get_str(); + std::string publicKey; + + Object result; + int rv = SecureMsgGetLocalPublicKey(address, publicKey); + switch (rv) + { + case 0: + result.push_back(Pair("result", "Success.")); + result.push_back(Pair("address in wallet", address)); + result.push_back(Pair("compressed public key", publicKey)); + return result; // success, don't check db + case 2: + case 3: + result.push_back(Pair("result", "Failed.")); + result.push_back(Pair("message", "Invalid address.")); + return result; + case 4: + break; // check db + //case 1: + default: + result.push_back(Pair("result", "Failed.")); + result.push_back(Pair("message", "Error.")); + return result; + }; + + CBitcoinAddress coinAddress(address); + + + CKeyID keyID; + if (!coinAddress.GetKeyID(keyID)) + { + result.push_back(Pair("result", "Failed.")); + result.push_back(Pair("message", "Invalid address.")); + return result; + }; + + CPubKey cpkFromDB; + rv = SecureMsgGetStoredKey(keyID, cpkFromDB); + + switch (rv) + { + case 0: + if (!cpkFromDB.IsValid() + || !cpkFromDB.IsCompressed()) + { + result.push_back(Pair("result", "Failed.")); + result.push_back(Pair("message", "Invalid address.")); + } else + { + //cpkFromDB.SetCompressedPubKey(); // make sure key is compressed + publicKey = EncodeBase58(cpkFromDB.Raw()); + + result.push_back(Pair("result", "Success.")); + result.push_back(Pair("peer address in DB", address)); + result.push_back(Pair("compressed public key", publicKey)); + }; + break; + case 2: + result.push_back(Pair("result", "Failed.")); + result.push_back(Pair("message", "Address not found in wallet or db.")); + return result; + //case 1: + default: + result.push_back(Pair("result", "Failed.")); + result.push_back(Pair("message", "Error, GetStoredKey().")); + return result; + }; + + return result; +} + +Value smsgsend(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 3) + throw runtime_error( + "smsgsend \n" + "Send an encrypted message from addrFrom to addrTo."); + + if (!fSecMsgEnabled) + throw runtime_error("Secure messaging is disabled."); + + std::string addrFrom = params[0].get_str(); + std::string addrTo = params[1].get_str(); + std::string msg = params[2].get_str(); + + + Object result; + + std::string sError; + if (SecureMsgSend(addrFrom, addrTo, msg, sError) != 0) + { + result.push_back(Pair("result", "Send failed.")); + result.push_back(Pair("error", sError)); + } else + result.push_back(Pair("result", "Sent.")); + + return result; +} + +Value smsgsendanon(const Array& params, bool fHelp) +{ + if (fHelp || params.size() != 2) + throw runtime_error( + "smsgsendanon \n" + "Send an anonymous encrypted message to addrTo."); + + if (!fSecMsgEnabled) + throw runtime_error("Secure messaging is disabled."); + + std::string addrFrom = "anon"; + std::string addrTo = params[0].get_str(); + std::string msg = params[1].get_str(); + + + Object result; + std::string sError; + if (SecureMsgSend(addrFrom, addrTo, msg, sError) != 0) + { + result.push_back(Pair("result", "Send failed.")); + result.push_back(Pair("error", sError)); + } else + result.push_back(Pair("result", "Sent.")); + + return result; +} + +Value smsginbox(const Array& params, bool fHelp) +{ + if (fHelp || params.size() > 1) // defaults to read + throw runtime_error( + "smsginbox [all|unread|clear]\n" + "Decrypt and display all received messages.\n" + "Warning: clear will delete all messages."); + + if (!fSecMsgEnabled) + throw runtime_error("Secure messaging is disabled."); + + if (pwalletMain->IsLocked()) + throw runtime_error("Wallet is locked."); + + std::string mode = "unread"; + if (params.size() > 0) + { + mode = params[0].get_str(); + } + + + Object result; + + std::vector vchKey; + vchKey.resize(16); + memset(&vchKey[0], 0, 16); + + { + LOCK(cs_smsgDB); + + SecMsgDB dbInbox; + + if (!dbInbox.Open("cr+")) + throw runtime_error("Could not open DB."); + + uint32_t nMessages = 0; + char cbuf[256]; + + std::string sPrefix("im"); + unsigned char chKey[18]; + + if (mode == "clear") + { + dbInbox.TxnBegin(); + + leveldb::Iterator* it = dbInbox.pdb->NewIterator(leveldb::ReadOptions()); + while (dbInbox.NextSmesgKey(it, sPrefix, chKey)) + { + dbInbox.EraseSmesg(chKey); + nMessages++; + }; + delete it; + dbInbox.TxnCommit(); + + snprintf(cbuf, sizeof(cbuf), "Deleted %u messages.", nMessages); + result.push_back(Pair("result", std::string(cbuf))); + } else + if (mode == "all" + || mode == "unread") + { + int fCheckReadStatus = mode == "unread" ? 1 : 0; + + SecMsgStored smsgStored; + MessageData msg; + + dbInbox.TxnBegin(); + + leveldb::Iterator* it = dbInbox.pdb->NewIterator(leveldb::ReadOptions()); + while (dbInbox.NextSmesg(it, sPrefix, chKey, smsgStored)) + { + if (fCheckReadStatus + && !(smsgStored.status & SMSG_MASK_UNREAD)) + continue; + + uint32_t nPayload = smsgStored.vchMessage.size() - SMSG_HDR_LEN; + if (SecureMsgDecrypt(false, smsgStored.sAddrTo, &smsgStored.vchMessage[0], &smsgStored.vchMessage[SMSG_HDR_LEN], nPayload, msg) == 0) + { + Object objM; + objM.push_back(Pair("received", getTimeString(smsgStored.timeReceived, cbuf, sizeof(cbuf)))); + objM.push_back(Pair("sent", getTimeString(msg.timestamp, cbuf, sizeof(cbuf)))); + objM.push_back(Pair("from", msg.sFromAddress)); + objM.push_back(Pair("to", smsgStored.sAddrTo)); + objM.push_back(Pair("text", std::string((char*)&msg.vchMessage[0]))); // ugh + + result.push_back(Pair("message", objM)); + } else + { + result.push_back(Pair("message", "Could not decrypt.")); + }; + + if (fCheckReadStatus) + { + smsgStored.status &= ~SMSG_MASK_UNREAD; + dbInbox.WriteSmesg(chKey, smsgStored); + }; + nMessages++; + }; + delete it; + dbInbox.TxnCommit(); + + snprintf(cbuf, sizeof(cbuf), "%u messages shown.", nMessages); + result.push_back(Pair("result", std::string(cbuf))); + + } else + { + result.push_back(Pair("result", "Unknown Mode.")); + result.push_back(Pair("expected", "[all|unread|clear].")); + }; + } + + return result; +}; + +Value smsgoutbox(const Array& params, bool fHelp) +{ + if (fHelp || params.size() > 1) // defaults to read + throw runtime_error( + "smsgoutbox [all|clear]\n" + "Decrypt and display all sent messages.\n" + "Warning: clear will delete all sent messages."); + + if (!fSecMsgEnabled) + throw runtime_error("Secure messaging is disabled."); + + if (pwalletMain->IsLocked()) + throw runtime_error("Wallet is locked."); + + std::string mode = "all"; + if (params.size() > 0) + { + mode = params[0].get_str(); + } + + + Object result; + + std::string sPrefix("sm"); + unsigned char chKey[18]; + memset(&chKey[0], 0, 18); + + { + LOCK(cs_smsgDB); + + SecMsgDB dbOutbox; + + if (!dbOutbox.Open("cr+")) + throw runtime_error("Could not open DB."); + + uint32_t nMessages = 0; + char cbuf[256]; + + if (mode == "clear") + { + dbOutbox.TxnBegin(); + + leveldb::Iterator* it = dbOutbox.pdb->NewIterator(leveldb::ReadOptions()); + while (dbOutbox.NextSmesgKey(it, sPrefix, chKey)) + { + dbOutbox.EraseSmesg(chKey); + nMessages++; + }; + delete it; + dbOutbox.TxnCommit(); + + + snprintf(cbuf, sizeof(cbuf), "Deleted %u messages.", nMessages); + result.push_back(Pair("result", std::string(cbuf))); + } else + if (mode == "all") + { + SecMsgStored smsgStored; + MessageData msg; + leveldb::Iterator* it = dbOutbox.pdb->NewIterator(leveldb::ReadOptions()); + while (dbOutbox.NextSmesg(it, sPrefix, chKey, smsgStored)) + { + uint32_t nPayload = smsgStored.vchMessage.size() - SMSG_HDR_LEN; + + if (SecureMsgDecrypt(false, smsgStored.sAddrOutbox, &smsgStored.vchMessage[0], &smsgStored.vchMessage[SMSG_HDR_LEN], nPayload, msg) == 0) + { + Object objM; + objM.push_back(Pair("sent", getTimeString(msg.timestamp, cbuf, sizeof(cbuf)))); + objM.push_back(Pair("from", msg.sFromAddress)); + objM.push_back(Pair("to", smsgStored.sAddrTo)); + objM.push_back(Pair("text", std::string((char*)&msg.vchMessage[0]))); // ugh + + result.push_back(Pair("message", objM)); + } else + { + result.push_back(Pair("message", "Could not decrypt.")); + }; + nMessages++; + }; + delete it; + + snprintf(cbuf, sizeof(cbuf), "%u sent messages shown.", nMessages); + result.push_back(Pair("result", std::string(cbuf))); + } else + { + result.push_back(Pair("result", "Unknown Mode.")); + result.push_back(Pair("expected", "[all|clear].")); + }; + } + + return result; +}; + + +Value smsgbuckets(const Array& params, bool fHelp) +{ + if (fHelp || params.size() > 1) + throw runtime_error( + "smsgbuckets [stats|dump]\n" + "Display some statistics."); + + if (!fSecMsgEnabled) + throw runtime_error("Secure messaging is disabled."); + + std::string mode = "stats"; + if (params.size() > 0) + { + mode = params[0].get_str(); + }; + + Object result; + + char cbuf[256]; + if (mode == "stats") + { + uint32_t nBuckets = 0; + uint32_t nMessages = 0; + uint64_t nBytes = 0; + { + LOCK(cs_smsg); + std::map::iterator it; + it = smsgBuckets.begin(); + + for (it = smsgBuckets.begin(); it != smsgBuckets.end(); ++it) + { + std::set& tokenSet = it->second.setTokens; + + std::string sBucket = boost::lexical_cast(it->first); + std::string sFile = sBucket + "_01.dat"; + + snprintf(cbuf, sizeof(cbuf), "%"PRIszu, tokenSet.size()); + std::string snContents(cbuf); + + std::string sHash = boost::lexical_cast(it->second.hash); + + nBuckets++; + nMessages += tokenSet.size(); + + Object objM; + objM.push_back(Pair("bucket", sBucket)); + objM.push_back(Pair("time", getTimeString(it->first, cbuf, sizeof(cbuf)))); + objM.push_back(Pair("no. messages", snContents)); + objM.push_back(Pair("hash", sHash)); + objM.push_back(Pair("last changed", getTimeString(it->second.timeChanged, cbuf, sizeof(cbuf)))); + + boost::filesystem::path fullPath = GetDataDir() / "smsgStore" / sFile; + + + if (!boost::filesystem::exists(fullPath)) + { + // -- If there is a file for an empty bucket something is wrong. + if (tokenSet.size() == 0) + objM.push_back(Pair("file size", "Empty bucket.")); + else + objM.push_back(Pair("file size, error", "File not found.")); + } else + { + try { + + uint64_t nFBytes = 0; + nFBytes = boost::filesystem::file_size(fullPath); + nBytes += nFBytes; + objM.push_back(Pair("file size", bytesReadable(nFBytes))); + } catch (const boost::filesystem::filesystem_error& ex) + { + objM.push_back(Pair("file size, error", ex.what())); + }; + }; + + result.push_back(Pair("bucket", objM)); + }; + }; // LOCK(cs_smsg); + + + std::string snBuckets = boost::lexical_cast(nBuckets); + std::string snMessages = boost::lexical_cast(nMessages); + + Object objM; + objM.push_back(Pair("buckets", snBuckets)); + objM.push_back(Pair("messages", snMessages)); + objM.push_back(Pair("size", bytesReadable(nBytes))); + result.push_back(Pair("total", objM)); + + } else + if (mode == "dump") + { + { + LOCK(cs_smsg); + std::map::iterator it; + it = smsgBuckets.begin(); + + for (it = smsgBuckets.begin(); it != smsgBuckets.end(); ++it) + { + std::string sFile = boost::lexical_cast(it->first) + "_01.dat"; + + try { + boost::filesystem::path fullPath = GetDataDir() / "smsgStore" / sFile; + boost::filesystem::remove(fullPath); + } catch (const boost::filesystem::filesystem_error& ex) + { + //objM.push_back(Pair("file size, error", ex.what())); + printf("Error removing bucket file %s.\n", ex.what()); + }; + }; + smsgBuckets.clear(); + }; // LOCK(cs_smsg); + + result.push_back(Pair("result", "Removed all buckets.")); + + } else + { + result.push_back(Pair("result", "Unknown Mode.")); + result.push_back(Pair("expected", "[stats|dump].")); + }; + + + return result; +}; diff --git a/src/rpcwallet.cpp b/src/rpcwallet.cpp index 5af4456..1a4a8d2 100644 --- a/src/rpcwallet.cpp +++ b/src/rpcwallet.cpp @@ -261,9 +261,9 @@ Value getaddressesbyaccount(const Array& params, bool fHelp) Value sendtoaddress(const Array& params, bool fHelp) { - if (fHelp || params.size() < 2 || params.size() > 4) + if (fHelp || params.size() < 2 || params.size() > 5) throw runtime_error( - "sendtoaddress [comment] [comment-to]\n" + "sendtoaddress [comment] [comment-to] [narration]\n" " is a real and is rounded to the nearest 0.000001" + HelpRequiringPassphrase()); @@ -274,6 +274,13 @@ Value sendtoaddress(const Array& params, bool fHelp) // Amount int64_t nAmount = AmountFromValue(params[1]); + std::string sNarr; + if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) + sNarr = params[4].get_str(); + + if (sNarr.length() > 24) + throw runtime_error("Narration must be 24 characters or less."); + // Wallet comments CWalletTx wtx; if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()) @@ -284,7 +291,7 @@ Value sendtoaddress(const Array& params, bool fHelp) if (pwalletMain->IsLocked()) throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); - string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); + string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, sNarr, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); @@ -587,9 +594,9 @@ Value movecmd(const Array& params, bool fHelp) Value sendfrom(const Array& params, bool fHelp) { - if (fHelp || params.size() < 3 || params.size() > 6) + if (fHelp || params.size() < 3 || params.size() > 7) throw runtime_error( - "sendfrom [minconf=1] [comment] [comment-to]\n" + "sendfrom [minconf=1] [comment] [comment-to] [narration]\n" " is a real and is rounded to the nearest 0.000001" + HelpRequiringPassphrase()); @@ -605,6 +612,13 @@ Value sendfrom(const Array& params, bool fHelp) CWalletTx wtx; wtx.strFromAccount = strAccount; + std::string sNarr; + if (params.size() > 6 && params[6].type() != null_type && !params[6].get_str().empty()) + sNarr = params[6].get_str(); + + if (sNarr.length() > 24) + throw runtime_error("Narration must be 24 characters or less."); + if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) wtx.mapValue["comment"] = params[4].get_str(); if (params.size() > 5 && params[5].type() != null_type && !params[5].get_str().empty()) @@ -618,7 +632,7 @@ Value sendfrom(const Array& params, bool fHelp) throw JSONRPCError(RPC_WALLET_INSUFFICIENT_FUNDS, "Account has insufficient funds"); // Send - string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, wtx); + string strError = pwalletMain->SendMoneyToDestination(address.Get(), nAmount, sNarr, wtx); if (strError != "") throw JSONRPCError(RPC_WALLET_ERROR, strError); @@ -678,7 +692,9 @@ Value sendmany(const Array& params, bool fHelp) // Send CReserveKey keyChange(pwalletMain); int64_t nFeeRequired = 0; - bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired); + int nChangePos; + std::string strFailReason; + bool fCreated = pwalletMain->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, nChangePos, strFailReason); if (!fCreated) { if (totalAmount + nFeeRequired > pwalletMain->GetBalance()) @@ -1576,3 +1592,347 @@ Value settxfee(const Array& params, bool fHelp) return true; } + + +Value getnewstealthaddress(const Array& params, bool fHelp) +{ + if (fHelp || params.size() > 1) + throw runtime_error( + "getnewstealthaddress [label]\n" + "Returns a new Genius stealth address for receiving payments anonymously. "); + + if (pwalletMain->IsLocked()) + throw runtime_error("Failed: Wallet must be unlocked."); + + std::string sLabel; + if (params.size() > 0) + sLabel = params[0].get_str(); + + CStealthAddress sxAddr; + std::string sError; + if (!pwalletMain->NewStealthAddress(sError, sLabel, sxAddr)) + throw runtime_error(std::string("Could get new stealth address: ") + sError); + + if (!pwalletMain->AddStealthAddress(sxAddr)) + throw runtime_error("Could not save to wallet."); + + return sxAddr.Encoded(); +} + +Value liststealthaddresses(const Array& params, bool fHelp) +{ + if (fHelp || params.size() > 1) + throw runtime_error( + "liststealthaddresses [show_secrets=0]\n" + "List owned stealth addresses."); + + bool fShowSecrets = false; + + if (params.size() > 0) + { + std::string str = params[0].get_str(); + + if (str == "0" || str == "n" || str == "no" || str == "-" || str == "false") + fShowSecrets = false; + else + fShowSecrets = true; + }; + + if (fShowSecrets) + { + if (pwalletMain->IsLocked()) + throw runtime_error("Failed: Wallet must be unlocked."); + }; + + Object result; + + //std::set::iterator it; + //for (it = pwalletMain->stealthAddresses.begin(); it != pwalletMain->stealthAddresses.end(); ++it) + BOOST_FOREACH(CStealthAddress sit, pwalletMain->stealthAddresses) + { + CStealthAddress* it = &(sit); + if (it->scan_secret.size() < 1) + continue; // stealth address is not owned + + if (fShowSecrets) + { + Object objA; + objA.push_back(Pair("Label ", it->label)); + objA.push_back(Pair("Address ", it->Encoded())); + objA.push_back(Pair("Scan Secret ", HexStr(it->scan_secret.begin(), it->scan_secret.end()))); + objA.push_back(Pair("Spend Secret ", HexStr(it->spend_secret.begin(), it->spend_secret.end()))); + result.push_back(Pair("Stealth Address", objA)); + } else + { + result.push_back(Pair("Stealth Address", it->Encoded() + " - " + it->label)); + }; + }; + + return result; +} + +Value importstealthaddress(const Array& params, bool fHelp) +{ + if (fHelp || params.size() < 2) + throw runtime_error( + "importstealthaddress [label]\n" + "Import an owned stealth addresses."); + + std::string sScanSecret = params[0].get_str(); + std::string sSpendSecret = params[1].get_str(); + std::string sLabel; + + + if (params.size() > 2) + { + sLabel = params[2].get_str(); + }; + + std::vector vchScanSecret; + std::vector vchSpendSecret; + + if (IsHex(sScanSecret)) + { + vchScanSecret = ParseHex(sScanSecret); + } else + { + if (!DecodeBase58(sScanSecret, vchScanSecret)) + throw runtime_error("Could not decode scan secret as hex or base58."); + }; + + if (IsHex(sSpendSecret)) + { + vchSpendSecret = ParseHex(sSpendSecret); + } else + { + if (!DecodeBase58(sSpendSecret, vchSpendSecret)) + throw runtime_error("Could not decode spend secret as hex or base58."); + }; + + if (vchScanSecret.size() != 32) + throw runtime_error("Scan secret is not 32 bytes."); + if (vchSpendSecret.size() != 32) + throw runtime_error("Spend secret is not 32 bytes."); + + + ec_secret scan_secret; + ec_secret spend_secret; + + memcpy(&scan_secret.e[0], &vchScanSecret[0], 32); + memcpy(&spend_secret.e[0], &vchSpendSecret[0], 32); + + ec_point scan_pubkey, spend_pubkey; + if (SecretToPublicKey(scan_secret, scan_pubkey) != 0) + throw runtime_error("Could not get scan public key."); + + if (SecretToPublicKey(spend_secret, spend_pubkey) != 0) + throw runtime_error("Could not get spend public key."); + + + CStealthAddress sxAddr; + sxAddr.label = sLabel; + sxAddr.scan_pubkey = scan_pubkey; + sxAddr.spend_pubkey = spend_pubkey; + + sxAddr.scan_secret = vchScanSecret; + sxAddr.spend_secret = vchSpendSecret; + + Object result; + bool fFound = false; + // -- find if address already exists + //std::set::iterator it; + //for (it = pwalletMain->stealthAddresses.begin(); it != pwalletMain->stealthAddresses.end(); ++it) + BOOST_FOREACH(CStealthAddress it, pwalletMain->stealthAddresses) + { + CStealthAddress &sxAddrIt = const_cast(it); //*it); + if (sxAddrIt.scan_pubkey == sxAddr.scan_pubkey + && sxAddrIt.spend_pubkey == sxAddr.spend_pubkey) + { + if (sxAddrIt.scan_secret.size() < 1) + { + sxAddrIt.scan_secret = sxAddr.scan_secret; + sxAddrIt.spend_secret = sxAddr.spend_secret; + fFound = true; // update stealth address with secrets + break; + }; + + result.push_back(Pair("result", "Import failed - stealth address exists.")); + return result; + }; + }; + + if (fFound) + { + result.push_back(Pair("result", "Success, updated " + sxAddr.Encoded())); + } else + { + pwalletMain->stealthAddresses.insert(sxAddr); + result.push_back(Pair("result", "Success, imported " + sxAddr.Encoded())); + }; + + + if (!pwalletMain->AddStealthAddress(sxAddr)) + throw runtime_error("Could not save to wallet."); + + return result; +} + + +Value sendtostealthaddress(const Array& params, bool fHelp) +{ + if (fHelp || params.size() < 2 || params.size() > 5) + throw runtime_error( + "sendtostealthaddress [comment] [comment-to] [narration]\n" + " is a real and is rounded to the nearest 0.000001" + + HelpRequiringPassphrase()); + + if (pwalletMain->IsLocked()) + throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first."); + + std::string sEncoded = params[0].get_str(); + int64_t nAmount = AmountFromValue(params[1]); + + std::string sNarr; + if (params.size() > 4 && params[4].type() != null_type && !params[4].get_str().empty()) + sNarr = params[4].get_str(); + + if (sNarr.length() > 24) + throw runtime_error("Narration must be 24 characters or less."); + + CStealthAddress sxAddr; + Object result; + + if (!sxAddr.SetEncoded(sEncoded)) + { + result.push_back(Pair("result", "Invalid Genius stealth address.")); + return result; + }; + + + CWalletTx wtx; + if (params.size() > 2 && params[2].type() != null_type && !params[2].get_str().empty()) + wtx.mapValue["comment"] = params[2].get_str(); + if (params.size() > 3 && params[3].type() != null_type && !params[3].get_str().empty()) + wtx.mapValue["to"] = params[3].get_str(); + + std::string sError; + if (!pwalletMain->SendStealthMoneyToDestination(sxAddr, nAmount, sNarr, wtx, sError)) + throw JSONRPCError(RPC_WALLET_ERROR, sError); + + return wtx.GetHash().GetHex(); + + result.push_back(Pair("result", "Not implemented yet.")); + + return result; +} + +Value scanforalltxns(const Array& params, bool fHelp) +{ + if (fHelp || params.size() > 1) + throw runtime_error( + "scanforalltxns [fromHeight]\n" + "Scan blockchain for owned transactions."); + + Object result; + int32_t nFromHeight = 0; + + CBlockIndex *pindex = pindexGenesisBlock; + + + if (params.size() > 0) + nFromHeight = params[0].get_int(); + + + if (nFromHeight > 0) + { + pindex = mapBlockIndex[hashBestChain]; + while (pindex->nHeight > nFromHeight + && pindex->pprev) + pindex = pindex->pprev; + }; + + if (pindex == NULL) + throw runtime_error("Genesis Block is not set."); + + { + LOCK2(cs_main, pwalletMain->cs_wallet); + + pwalletMain->MarkDirty(); + + pwalletMain->ScanForWalletTransactions(pindex, true); + pwalletMain->ReacceptWalletTransactions(); + } + + result.push_back(Pair("result", "Scan complete.")); + + return result; +} + +Value scanforstealthtxns(const Array& params, bool fHelp) +{ + if (fHelp || params.size() > 1) + throw runtime_error( + "scanforstealthtxns [fromHeight]\n" + "Scan blockchain for owned stealth transactions."); + + Object result; + uint32_t nBlocks = 0; + uint32_t nTransactions = 0; + int32_t nFromHeight = 0; + + CBlockIndex *pindex = pindexGenesisBlock; + + + if (params.size() > 0) + nFromHeight = params[0].get_int(); + + + if (nFromHeight > 0) + { + pindex = mapBlockIndex[hashBestChain]; + while (pindex->nHeight > nFromHeight + && pindex->pprev) + pindex = pindex->pprev; + }; + + if (pindex == NULL) + throw runtime_error("Genesis Block is not set."); + + // -- locks in AddToWalletIfInvolvingMe + + bool fUpdate = true; // todo: option? + + pwalletMain->nStealth = 0; + pwalletMain->nFoundStealth = 0; + + while (pindex) + { + nBlocks++; + CBlock block; + block.ReadFromDisk(pindex, true); + + BOOST_FOREACH(CTransaction& tx, block.vtx) + { + + nTransactions++; + + pwalletMain->AddToWalletIfInvolvingMe(tx, &block, fUpdate); + }; + + pindex = pindex->pnext; + }; + + printf("Scanned %u blocks, %u transactions\n", nBlocks, nTransactions); + printf("Found %u stealth transactions in blockchain.\n", pwalletMain->nStealth); + printf("Found %u new owned stealth transactions.\n", pwalletMain->nFoundStealth); + + char cbuf[256]; + snprintf(cbuf, sizeof(cbuf), "%u new stealth transactions.", pwalletMain->nFoundStealth); + + result.push_back(Pair("result", "Scan complete.")); + result.push_back(Pair("found", std::string(cbuf))); + + return result; +} + + diff --git a/src/script.cpp b/src/script.cpp index 239c61e..57eef7a 100644 --- a/src/script.cpp +++ b/src/script.cpp @@ -17,6 +17,95 @@ using namespace boost; #include "main.h" #include "sync.h" #include "util.h" +#include "crypto/ripemd160.h" +#include "crypto/sha1.h" +#include "crypto/sha256.h" +#include "eccryptoverify.h" + +namespace { + +inline bool set_success(ScriptError* ret) +{ + if (ret) + *ret = SCRIPT_ERR_OK; + return true; +} + +inline bool set_error(ScriptError* ret, const ScriptError serror) +{ + if (ret) + *ret = serror; + return false; +} + +} // anon namespace + + +const char* ScriptErrorString(const ScriptError serror) +{ + switch (serror) + { + case SCRIPT_ERR_OK: + return "No error"; + case SCRIPT_ERR_EVAL_FALSE: + return "Script evaluated without error but finished with a false/empty top stack element"; + case SCRIPT_ERR_VERIFY: + return "Script failed an OP_VERIFY operation"; + case SCRIPT_ERR_EQUALVERIFY: + return "Script failed an OP_EQUALVERIFY operation"; + case SCRIPT_ERR_CHECKMULTISIGVERIFY: + return "Script failed an OP_CHECKMULTISIGVERIFY operation"; + case SCRIPT_ERR_CHECKSIGVERIFY: + return "Script failed an OP_CHECKSIGVERIFY operation"; + case SCRIPT_ERR_NUMEQUALVERIFY: + return "Script failed an OP_NUMEQUALVERIFY operation"; + case SCRIPT_ERR_SCRIPT_SIZE: + return "Script is too big"; + case SCRIPT_ERR_PUSH_SIZE: + return "Push value size limit exceeded"; + case SCRIPT_ERR_OP_COUNT: + return "Operation limit exceeded"; + case SCRIPT_ERR_STACK_SIZE: + return "Stack size limit exceeded"; + case SCRIPT_ERR_SIG_COUNT: + return "Signature count negative or greater than pubkey count"; + case SCRIPT_ERR_PUBKEY_COUNT: + return "Pubkey count negative or limit exceeded"; + case SCRIPT_ERR_BAD_OPCODE: + return "Opcode missing or not understood"; + case SCRIPT_ERR_DISABLED_OPCODE: + return "Attempted to use a disabled opcode"; + case SCRIPT_ERR_INVALID_STACK_OPERATION: + return "Operation not valid with the current stack size"; + case SCRIPT_ERR_INVALID_ALTSTACK_OPERATION: + return "Operation not valid with the current altstack size"; + case SCRIPT_ERR_OP_RETURN: + return "OP_RETURN was encountered"; + case SCRIPT_ERR_UNBALANCED_CONDITIONAL: + return "Invalid OP_IF construction"; + case SCRIPT_ERR_SIG_HASHTYPE: + return "Signature hash type missing or not understood"; + case SCRIPT_ERR_SIG_DER: + return "Non-canonical DER signature"; + case SCRIPT_ERR_MINIMALDATA: + return "Data push larger than necessary"; + case SCRIPT_ERR_SIG_PUSHONLY: + return "Only non-push operators allowed in signatures"; + case SCRIPT_ERR_SIG_HIGH_S: + return "Non-canonical signature: S value is unnecessarily high"; + case SCRIPT_ERR_SIG_NULLDUMMY: + return "Dummy CHECKMULTISIG argument must be zero"; + case SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS: + return "NOPx reserved for soft-fork upgrades"; + case SCRIPT_ERR_PUBKEYTYPE: + return "Public key is neither compressed or uncompressed"; + case SCRIPT_ERR_UNKNOWN_ERROR: + case SCRIPT_ERR_ERROR_COUNT: + default: break; + } + return "unknown error"; +} + bool CheckSig(vector vchSig, const vector &vchPubKey, const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType, int flags); @@ -828,7 +917,804 @@ bool EvalScript(vector >& stack, const CScript& script, co { // (x1 x2 - bool) if (stack.size() < 2) - return false; + return false; + valtype& vch1 = stacktop(-2); + valtype& vch2 = stacktop(-1); + bool fEqual = (vch1 == vch2); + // OP_NOTEQUAL is disabled because it would be too easy to say + // something like n != 1 and have some wiseguy pass in 1 with extra + // zero bytes after it (numerically, 0x01 == 0x0001 == 0x000001) + //if (opcode == OP_NOTEQUAL) + // fEqual = !fEqual; + popstack(stack); + popstack(stack); + stack.push_back(fEqual ? vchTrue : vchFalse); + if (opcode == OP_EQUALVERIFY) + { + if (fEqual) + popstack(stack); + else + return false; + } + } + break; + + + // + // Numeric + // + case OP_1ADD: + case OP_1SUB: + case OP_2MUL: + case OP_2DIV: + case OP_NEGATE: + case OP_ABS: + case OP_NOT: + case OP_0NOTEQUAL: + { + // (in -- out) + if (stack.size() < 1) + return false; + CBigNum bn = CastToBigNum(stacktop(-1)); + switch (opcode) + { + case OP_1ADD: bn += bnOne; break; + case OP_1SUB: bn -= bnOne; break; + case OP_2MUL: bn <<= 1; break; + case OP_2DIV: bn >>= 1; break; + case OP_NEGATE: bn = -bn; break; + case OP_ABS: if (bn < bnZero) bn = -bn; break; + case OP_NOT: bn = (bn == bnZero); break; + case OP_0NOTEQUAL: bn = (bn != bnZero); break; + default: assert(!"invalid opcode"); break; + } + popstack(stack); + stack.push_back(bn.getvch()); + } + break; + + case OP_ADD: + case OP_SUB: + case OP_MUL: + case OP_DIV: + case OP_MOD: + case OP_LSHIFT: + case OP_RSHIFT: + case OP_BOOLAND: + case OP_BOOLOR: + case OP_NUMEQUAL: + case OP_NUMEQUALVERIFY: + case OP_NUMNOTEQUAL: + case OP_LESSTHAN: + case OP_GREATERTHAN: + case OP_LESSTHANOREQUAL: + case OP_GREATERTHANOREQUAL: + case OP_MIN: + case OP_MAX: + { + // (x1 x2 -- out) + if (stack.size() < 2) + return false; + CBigNum bn1 = CastToBigNum(stacktop(-2)); + CBigNum bn2 = CastToBigNum(stacktop(-1)); + CBigNum bn; + switch (opcode) + { + case OP_ADD: + bn = bn1 + bn2; + break; + + case OP_SUB: + bn = bn1 - bn2; + break; + + case OP_MUL: + if (!BN_mul(&bn, &bn1, &bn2, pctx)) + return false; + break; + + case OP_DIV: + if (!BN_div(&bn, NULL, &bn1, &bn2, pctx)) + return false; + break; + + case OP_MOD: + if (!BN_mod(&bn, &bn1, &bn2, pctx)) + return false; + break; + + case OP_LSHIFT: + if (bn2 < bnZero || bn2 > CBigNum(2048)) + return false; + bn = bn1 << bn2.getulong(); + break; + + case OP_RSHIFT: + if (bn2 < bnZero || bn2 > CBigNum(2048)) + return false; + bn = bn1 >> bn2.getulong(); + break; + + case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break; + case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break; + case OP_NUMEQUAL: bn = (bn1 == bn2); break; + case OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break; + case OP_NUMNOTEQUAL: bn = (bn1 != bn2); break; + case OP_LESSTHAN: bn = (bn1 < bn2); break; + case OP_GREATERTHAN: bn = (bn1 > bn2); break; + case OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break; + case OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break; + case OP_MIN: bn = (bn1 < bn2 ? bn1 : bn2); break; + case OP_MAX: bn = (bn1 > bn2 ? bn1 : bn2); break; + default: assert(!"invalid opcode"); break; + } + popstack(stack); + popstack(stack); + stack.push_back(bn.getvch()); + + if (opcode == OP_NUMEQUALVERIFY) + { + if (CastToBool(stacktop(-1))) + popstack(stack); + else + return false; + } + } + break; + + case OP_WITHIN: + { + // (x min max -- out) + if (stack.size() < 3) + return false; + CBigNum bn1 = CastToBigNum(stacktop(-3)); + CBigNum bn2 = CastToBigNum(stacktop(-2)); + CBigNum bn3 = CastToBigNum(stacktop(-1)); + bool fValue = (bn2 <= bn1 && bn1 < bn3); + popstack(stack); + popstack(stack); + popstack(stack); + stack.push_back(fValue ? vchTrue : vchFalse); + } + break; + + + // + // Crypto + // + case OP_RIPEMD160: + case OP_SHA1: + case OP_SHA256: + case OP_HASH160: + case OP_HASH256: + { + // (in -- hash) + if (stack.size() < 1) + return false; + valtype& vch = stacktop(-1); + valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32); + if (opcode == OP_RIPEMD160) + RIPEMD160(&vch[0], vch.size(), &vchHash[0]); + else if (opcode == OP_SHA1) + SHA1(&vch[0], vch.size(), &vchHash[0]); + else if (opcode == OP_SHA256) + SHA256(&vch[0], vch.size(), &vchHash[0]); + else if (opcode == OP_HASH160) + { + uint160 hash160 = Hash160(vch); + memcpy(&vchHash[0], &hash160, sizeof(hash160)); + } + else if (opcode == OP_HASH256) + { + uint256 hash = Hash(vch.begin(), vch.end()); + memcpy(&vchHash[0], &hash, sizeof(hash)); + } + popstack(stack); + stack.push_back(vchHash); + } + break; + + case OP_CODESEPARATOR: + { + // Hash starts after the code separator + pbegincodehash = pc; + } + break; + + case OP_CHECKSIG: + case OP_CHECKSIGVERIFY: + { + // (sig pubkey -- bool) + if (stack.size() < 2) + return false; + + valtype& vchSig = stacktop(-2); + valtype& vchPubKey = stacktop(-1); + + // Subset of script starting at the most recent codeseparator + CScript scriptCode(pbegincodehash, pend); + + // Drop the signature, since there's no way for a signature to sign itself + scriptCode.FindAndDelete(CScript(vchSig)); + + if ((flags & SCRIPT_VERIFY_STRICTENC) && (!CheckSignatureEncoding(vchSig) || !CheckPubKeyEncoding(vchPubKey))) + return false; + + bool fSuccess = CheckSignatureEncoding(vchSig) && CheckPubKeyEncoding(vchPubKey) && + CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags); + + popstack(stack); + popstack(stack); + stack.push_back(fSuccess ? vchTrue : vchFalse); + if (opcode == OP_CHECKSIGVERIFY) + { + if (fSuccess) + popstack(stack); + else + return false; + } + } + break; + + case OP_CHECKMULTISIG: + case OP_CHECKMULTISIGVERIFY: + { + // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool) + + int i = 1; + if ((int)stack.size() < i) + return false; + + int nKeysCount = CastToBigNum(stacktop(-i)).getint(); + if (nKeysCount < 0 || nKeysCount > 20) + return false; + nOpCount += nKeysCount; + if (nOpCount > 201) + return false; + int ikey = ++i; + i += nKeysCount; + if ((int)stack.size() < i) + return false; + + int nSigsCount = CastToBigNum(stacktop(-i)).getint(); + if (nSigsCount < 0 || nSigsCount > nKeysCount) + return false; + int isig = ++i; + i += nSigsCount; + if ((int)stack.size() < i) + return false; + + // Subset of script starting at the most recent codeseparator + CScript scriptCode(pbegincodehash, pend); + + // Drop the signatures, since there's no way for a signature to sign itself + for (int k = 0; k < nSigsCount; k++) + { + valtype& vchSig = stacktop(-isig-k); + scriptCode.FindAndDelete(CScript(vchSig)); + } + + bool fSuccess = true; + while (fSuccess && nSigsCount > 0) + { + valtype& vchSig = stacktop(-isig); + valtype& vchPubKey = stacktop(-ikey); + + if ((flags & SCRIPT_VERIFY_STRICTENC) && (!CheckSignatureEncoding(vchSig) || !CheckPubKeyEncoding(vchPubKey))) + return false; + + // Check signature + bool fOk = CheckSignatureEncoding(vchSig) && CheckPubKeyEncoding(vchPubKey) && + CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags); + + if (fOk) + { + isig++; + nSigsCount--; + } + ikey++; + nKeysCount--; + + // If there are more signatures left than keys left, + // then too many signatures have failed + if (nSigsCount > nKeysCount) + fSuccess = false; + } + + // Clean up stack of actual arguments + while (i-- > 1) + popstack(stack); + + // A bug causes CHECKMULTISIG to consume one extra argument + // whose contents were not checked in any way. + // + // Unfortunately this is a potential source of mutability, + // so optionally verify it is exactly equal to zero prior + // to removing it from the stack. + if (stack.size() < 1) + return false; + if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size()) + return error("CHECKMULTISIG dummy argument not null"); + popstack(stack); + + stack.push_back(fSuccess ? vchTrue : vchFalse); + + if (opcode == OP_CHECKMULTISIGVERIFY) + { + if (fSuccess) + popstack(stack); + else + return false; + } + } + break; + + default: + return false; + } + + // Size limits + if (stack.size() + altstack.size() > 1000) + return false; + } + } + catch (...) + { + return false; + } + + + if (!vfExec.empty()) + return false; + + return true; +} + +bool static IsLowDERSignature(const valtype &vchSig, ScriptError* serror) { + if (!IsDERSignature(vchSig)) { + return set_error(serror, SCRIPT_ERR_SIG_DER); + } + unsigned int nLenR = vchSig[3]; + unsigned int nLenS = vchSig[5+nLenR]; + const unsigned char *S = &vchSig[6+nLenR]; + // If the S value is above the order of the curve divided by two, its + // complement modulo the order could have been used instead, which is + // one byte shorter when encoded correctly. + if (!eccrypto::CheckSignatureElement(S, nLenS, true)) + return set_error(serror, SCRIPT_ERR_SIG_HIGH_S); + + return true; +} + + +bool static CheckSignatureEncoding(const valtype &vchSig, unsigned int flags, ScriptError* serror) { + if ((flags & (SCRIPT_VERIFY_DERSIG | SCRIPT_VERIFY_LOW_S | SCRIPT_VERIFY_STRICTENC)) != 0 && !IsDERSignature(vchSig)) { + return set_error(serror, SCRIPT_ERR_SIG_DER); + } else if ((flags & SCRIPT_VERIFY_LOW_S) != 0 && !IsLowDERSignature(vchSig, serror)) { + // serror is set + return false; + } else if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsDefinedHashtypeSignature(vchSig)) { + return set_error(serror, SCRIPT_ERR_SIG_HASHTYPE); + } + return true; +} + +bool static CheckPubKeyEncoding(const valtype &vchSig, unsigned int flags, ScriptError* serror) { + if ((flags & SCRIPT_VERIFY_STRICTENC) != 0 && !IsCompressedOrUncompressedPubKey(vchSig)) { + return set_error(serror, SCRIPT_ERR_PUBKEYTYPE); + } + return true; +} + +bool static CheckMinimalPush(const valtype& data, opcodetype opcode) { + if (data.size() == 0) { + // Could have used OP_0. + return opcode == OP_0; + } else if (data.size() == 1 && data[0] >= 1 && data[0] <= 16) { + // Could have used OP_1 .. OP_16. + return opcode == OP_1 + (data[0] - 1); + } else if (data.size() == 1 && data[0] == 0x81) { + // Could have used OP_1NEGATE. + return opcode == OP_1NEGATE; + } else if (data.size() <= 75) { + // Could have used a direct push (opcode indicating number of bytes pushed + those bytes). + return opcode == data.size(); + } else if (data.size() <= 255) { + // Could have used OP_PUSHDATA. + return opcode == OP_PUSHDATA1; + } else if (data.size() <= 65535) { + // Could have used OP_PUSHDATA2. + return opcode == OP_PUSHDATA2; + } + return true; +} + +bool EvalScript(vector >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror) +{ + static const CScriptNum bnZero(0); + static const CScriptNum bnOne(1); + static const CScriptNum bnFalse(0); + static const CScriptNum bnTrue(1); + static const valtype vchFalse(0); + static const valtype vchZero(0); + static const valtype vchTrue(1, 1); + + CScript::const_iterator pc = script.begin(); + CScript::const_iterator pend = script.end(); + CScript::const_iterator pbegincodehash = script.begin(); + opcodetype opcode; + valtype vchPushValue; + vector vfExec; + vector altstack; + set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR); + if (script.size() > 10000) + return set_error(serror, SCRIPT_ERR_SCRIPT_SIZE); + int nOpCount = 0; + bool fRequireMinimal = (flags & SCRIPT_VERIFY_MINIMALDATA) != 0; + + try + { + while (pc < pend) + { + bool fExec = !count(vfExec.begin(), vfExec.end(), false); + + // + // Read instruction + // + if (!script.GetOp(pc, opcode, vchPushValue)) + return set_error(serror, SCRIPT_ERR_BAD_OPCODE); + if (vchPushValue.size() > MAX_SCRIPT_ELEMENT_SIZE) + return set_error(serror, SCRIPT_ERR_PUSH_SIZE); + + // Note how OP_RESERVED does not count towards the opcode limit. + if (opcode > OP_16 && ++nOpCount > 201) + return set_error(serror, SCRIPT_ERR_OP_COUNT); + + if (opcode == OP_CAT || + opcode == OP_SUBSTR || + opcode == OP_LEFT || + opcode == OP_RIGHT || + opcode == OP_INVERT || + opcode == OP_AND || + opcode == OP_OR || + opcode == OP_XOR || + opcode == OP_2MUL || + opcode == OP_2DIV || + opcode == OP_MUL || + opcode == OP_DIV || + opcode == OP_MOD || + opcode == OP_LSHIFT || + opcode == OP_RSHIFT) + return set_error(serror, SCRIPT_ERR_DISABLED_OPCODE); // Disabled opcodes. + + if (fExec && 0 <= opcode && opcode <= OP_PUSHDATA4) { + if (fRequireMinimal && !CheckMinimalPush(vchPushValue, opcode)) { + return set_error(serror, SCRIPT_ERR_MINIMALDATA); + } + stack.push_back(vchPushValue); + } else if (fExec || (OP_IF <= opcode && opcode <= OP_ENDIF)) + switch (opcode) + { + // + // Push value + // + case OP_1NEGATE: + case OP_1: + case OP_2: + case OP_3: + case OP_4: + case OP_5: + case OP_6: + case OP_7: + case OP_8: + case OP_9: + case OP_10: + case OP_11: + case OP_12: + case OP_13: + case OP_14: + case OP_15: + case OP_16: + { + // ( -- value) + CScriptNum bn((int)opcode - (int)(OP_1 - 1)); + stack.push_back(bn.getvch()); + // The result of these opcodes should always be the minimal way to push the data + // they push, so no need for a CheckMinimalPush here. + } + break; + + + // + // Control + // + case OP_NOP: + break; + + case OP_NOP1: case OP_NOP2: case OP_NOP3: case OP_NOP4: case OP_NOP5: + case OP_NOP6: case OP_NOP7: case OP_NOP8: case OP_NOP9: case OP_NOP10: + { + if (flags & SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) + return set_error(serror, SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS); + } + break; + + case OP_IF: + case OP_NOTIF: + { + // if [statements] [else [statements]] endif + bool fValue = false; + if (fExec) + { + if (stack.size() < 1) + return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL); + valtype& vch = stacktop(-1); + fValue = CastToBool(vch); + if (opcode == OP_NOTIF) + fValue = !fValue; + popstack(stack); + } + vfExec.push_back(fValue); + } + break; + + case OP_ELSE: + { + if (vfExec.empty()) + return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL); + vfExec.back() = !vfExec.back(); + } + break; + + case OP_ENDIF: + { + if (vfExec.empty()) + return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL); + vfExec.pop_back(); + } + break; + + case OP_VERIFY: + { + // (true -- ) or + // (false -- false) and return + if (stack.size() < 1) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + bool fValue = CastToBool(stacktop(-1)); + if (fValue) + popstack(stack); + else + return set_error(serror, SCRIPT_ERR_VERIFY); + } + break; + + case OP_RETURN: + { + return set_error(serror, SCRIPT_ERR_OP_RETURN); + } + break; + + + // + // Stack ops + // + case OP_TOALTSTACK: + { + if (stack.size() < 1) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + altstack.push_back(stacktop(-1)); + popstack(stack); + } + break; + + case OP_FROMALTSTACK: + { + if (altstack.size() < 1) + return set_error(serror, SCRIPT_ERR_INVALID_ALTSTACK_OPERATION); + stack.push_back(altstacktop(-1)); + popstack(altstack); + } + break; + + case OP_2DROP: + { + // (x1 x2 -- ) + if (stack.size() < 2) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + popstack(stack); + popstack(stack); + } + break; + + case OP_2DUP: + { + // (x1 x2 -- x1 x2 x1 x2) + if (stack.size() < 2) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + valtype vch1 = stacktop(-2); + valtype vch2 = stacktop(-1); + stack.push_back(vch1); + stack.push_back(vch2); + } + break; + + case OP_3DUP: + { + // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3) + if (stack.size() < 3) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + valtype vch1 = stacktop(-3); + valtype vch2 = stacktop(-2); + valtype vch3 = stacktop(-1); + stack.push_back(vch1); + stack.push_back(vch2); + stack.push_back(vch3); + } + break; + + case OP_2OVER: + { + // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2) + if (stack.size() < 4) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + valtype vch1 = stacktop(-4); + valtype vch2 = stacktop(-3); + stack.push_back(vch1); + stack.push_back(vch2); + } + break; + + case OP_2ROT: + { + // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2) + if (stack.size() < 6) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + valtype vch1 = stacktop(-6); + valtype vch2 = stacktop(-5); + stack.erase(stack.end()-6, stack.end()-4); + stack.push_back(vch1); + stack.push_back(vch2); + } + break; + + case OP_2SWAP: + { + // (x1 x2 x3 x4 -- x3 x4 x1 x2) + if (stack.size() < 4) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + swap(stacktop(-4), stacktop(-2)); + swap(stacktop(-3), stacktop(-1)); + } + break; + + case OP_IFDUP: + { + // (x - 0 | x x) + if (stack.size() < 1) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + valtype vch = stacktop(-1); + if (CastToBool(vch)) + stack.push_back(vch); + } + break; + + case OP_DEPTH: + { + // -- stacksize + CScriptNum bn(stack.size()); + stack.push_back(bn.getvch()); + } + break; + + case OP_DROP: + { + // (x -- ) + if (stack.size() < 1) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + popstack(stack); + } + break; + + case OP_DUP: + { + // (x -- x x) + if (stack.size() < 1) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + valtype vch = stacktop(-1); + stack.push_back(vch); + } + break; + + case OP_NIP: + { + // (x1 x2 -- x2) + if (stack.size() < 2) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + stack.erase(stack.end() - 2); + } + break; + + case OP_OVER: + { + // (x1 x2 -- x1 x2 x1) + if (stack.size() < 2) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + valtype vch = stacktop(-2); + stack.push_back(vch); + } + break; + + case OP_PICK: + case OP_ROLL: + { + // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn) + // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn) + if (stack.size() < 2) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + int n = CScriptNum(stacktop(-1), fRequireMinimal).getint(); + popstack(stack); + if (n < 0 || n >= (int)stack.size()) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + valtype vch = stacktop(-n-1); + if (opcode == OP_ROLL) + stack.erase(stack.end()-n-1); + stack.push_back(vch); + } + break; + + case OP_ROT: + { + // (x1 x2 x3 -- x2 x3 x1) + // x2 x1 x3 after first swap + // x2 x3 x1 after second swap + if (stack.size() < 3) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + swap(stacktop(-3), stacktop(-2)); + swap(stacktop(-2), stacktop(-1)); + } + break; + + case OP_SWAP: + { + // (x1 x2 -- x2 x1) + if (stack.size() < 2) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + swap(stacktop(-2), stacktop(-1)); + } + break; + + case OP_TUCK: + { + // (x1 x2 -- x2 x1 x2) + if (stack.size() < 2) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + valtype vch = stacktop(-1); + stack.insert(stack.end()-2, vch); + } + break; + + + case OP_SIZE: + { + // (in -- in size) + if (stack.size() < 1) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + CScriptNum bn(stacktop(-1).size()); + stack.push_back(bn.getvch()); + } + break; + + + // + // Bitwise logic + // + case OP_EQUAL: + case OP_EQUALVERIFY: + //case OP_NOTEQUAL: // use OP_NUMNOTEQUAL + { + // (x1 x2 - bool) + if (stack.size() < 2) + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype& vch1 = stacktop(-2); valtype& vch2 = stacktop(-1); bool fEqual = (vch1 == vch2); @@ -845,7 +1731,7 @@ bool EvalScript(vector >& stack, const CScript& script, co if (fEqual) popstack(stack); else - return false; + return set_error(serror, SCRIPT_ERR_EQUALVERIFY); } } break; @@ -856,8 +1742,6 @@ bool EvalScript(vector >& stack, const CScript& script, co // case OP_1ADD: case OP_1SUB: - case OP_2MUL: - case OP_2DIV: case OP_NEGATE: case OP_ABS: case OP_NOT: @@ -865,14 +1749,12 @@ bool EvalScript(vector >& stack, const CScript& script, co { // (in -- out) if (stack.size() < 1) - return false; - CBigNum bn = CastToBigNum(stacktop(-1)); + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + CScriptNum bn(stacktop(-1), fRequireMinimal); switch (opcode) { case OP_1ADD: bn += bnOne; break; case OP_1SUB: bn -= bnOne; break; - case OP_2MUL: bn <<= 1; break; - case OP_2DIV: bn >>= 1; break; case OP_NEGATE: bn = -bn; break; case OP_ABS: if (bn < bnZero) bn = -bn; break; case OP_NOT: bn = (bn == bnZero); break; @@ -886,11 +1768,6 @@ bool EvalScript(vector >& stack, const CScript& script, co case OP_ADD: case OP_SUB: - case OP_MUL: - case OP_DIV: - case OP_MOD: - case OP_LSHIFT: - case OP_RSHIFT: case OP_BOOLAND: case OP_BOOLOR: case OP_NUMEQUAL: @@ -905,10 +1782,10 @@ bool EvalScript(vector >& stack, const CScript& script, co { // (x1 x2 -- out) if (stack.size() < 2) - return false; - CBigNum bn1 = CastToBigNum(stacktop(-2)); - CBigNum bn2 = CastToBigNum(stacktop(-1)); - CBigNum bn; + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + CScriptNum bn1(stacktop(-2), fRequireMinimal); + CScriptNum bn2(stacktop(-1), fRequireMinimal); + CScriptNum bn(0); switch (opcode) { case OP_ADD: @@ -919,33 +1796,6 @@ bool EvalScript(vector >& stack, const CScript& script, co bn = bn1 - bn2; break; - case OP_MUL: - if (!BN_mul(&bn, &bn1, &bn2, pctx)) - return false; - break; - - case OP_DIV: - if (!BN_div(&bn, NULL, &bn1, &bn2, pctx)) - return false; - break; - - case OP_MOD: - if (!BN_mod(&bn, &bn1, &bn2, pctx)) - return false; - break; - - case OP_LSHIFT: - if (bn2 < bnZero || bn2 > CBigNum(2048)) - return false; - bn = bn1 << bn2.getulong(); - break; - - case OP_RSHIFT: - if (bn2 < bnZero || bn2 > CBigNum(2048)) - return false; - bn = bn1 >> bn2.getulong(); - break; - case OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break; case OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break; case OP_NUMEQUAL: bn = (bn1 == bn2); break; @@ -968,7 +1818,7 @@ bool EvalScript(vector >& stack, const CScript& script, co if (CastToBool(stacktop(-1))) popstack(stack); else - return false; + return set_error(serror, SCRIPT_ERR_NUMEQUALVERIFY); } } break; @@ -977,10 +1827,10 @@ bool EvalScript(vector >& stack, const CScript& script, co { // (x min max -- out) if (stack.size() < 3) - return false; - CBigNum bn1 = CastToBigNum(stacktop(-3)); - CBigNum bn2 = CastToBigNum(stacktop(-2)); - CBigNum bn3 = CastToBigNum(stacktop(-1)); + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); + CScriptNum bn1(stacktop(-3), fRequireMinimal); + CScriptNum bn2(stacktop(-2), fRequireMinimal); + CScriptNum bn3(stacktop(-1), fRequireMinimal); bool fValue = (bn2 <= bn1 && bn1 < bn3); popstack(stack); popstack(stack); @@ -1001,29 +1851,23 @@ bool EvalScript(vector >& stack, const CScript& script, co { // (in -- hash) if (stack.size() < 1) - return false; + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype& vch = stacktop(-1); valtype vchHash((opcode == OP_RIPEMD160 || opcode == OP_SHA1 || opcode == OP_HASH160) ? 20 : 32); if (opcode == OP_RIPEMD160) - RIPEMD160(&vch[0], vch.size(), &vchHash[0]); + CRIPEMD160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash)); else if (opcode == OP_SHA1) - SHA1(&vch[0], vch.size(), &vchHash[0]); + CSHA1().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash)); else if (opcode == OP_SHA256) - SHA256(&vch[0], vch.size(), &vchHash[0]); + CSHA256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash)); else if (opcode == OP_HASH160) - { - uint160 hash160 = Hash160(vch); - memcpy(&vchHash[0], &hash160, sizeof(hash160)); - } + CHash160().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash)); else if (opcode == OP_HASH256) - { - uint256 hash = Hash(vch.begin(), vch.end()); - memcpy(&vchHash[0], &hash, sizeof(hash)); - } + CHash256().Write(begin_ptr(vch), vch.size()).Finalize(begin_ptr(vchHash)); popstack(stack); stack.push_back(vchHash); } - break; + break; case OP_CODESEPARATOR: { @@ -1037,7 +1881,7 @@ bool EvalScript(vector >& stack, const CScript& script, co { // (sig pubkey -- bool) if (stack.size() < 2) - return false; + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); valtype& vchSig = stacktop(-2); valtype& vchPubKey = stacktop(-1); @@ -1048,11 +1892,11 @@ bool EvalScript(vector >& stack, const CScript& script, co // Drop the signature, since there's no way for a signature to sign itself scriptCode.FindAndDelete(CScript(vchSig)); - if ((flags & SCRIPT_VERIFY_STRICTENC) && (!CheckSignatureEncoding(vchSig) || !CheckPubKeyEncoding(vchPubKey))) + if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) { + //serror is set return false; - - bool fSuccess = CheckSignatureEncoding(vchSig) && CheckPubKeyEncoding(vchPubKey) && - CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags); + } + bool fSuccess = checker.CheckSig(vchSig, vchPubKey, scriptCode); popstack(stack); popstack(stack); @@ -1062,7 +1906,7 @@ bool EvalScript(vector >& stack, const CScript& script, co if (fSuccess) popstack(stack); else - return false; + return set_error(serror, SCRIPT_ERR_CHECKSIGVERIFY); } } break; @@ -1074,26 +1918,26 @@ bool EvalScript(vector >& stack, const CScript& script, co int i = 1; if ((int)stack.size() < i) - return false; + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); - int nKeysCount = CastToBigNum(stacktop(-i)).getint(); + int nKeysCount = CScriptNum(stacktop(-i), fRequireMinimal).getint(); if (nKeysCount < 0 || nKeysCount > 20) - return false; + return set_error(serror, SCRIPT_ERR_PUBKEY_COUNT); nOpCount += nKeysCount; if (nOpCount > 201) - return false; + return set_error(serror, SCRIPT_ERR_OP_COUNT); int ikey = ++i; i += nKeysCount; if ((int)stack.size() < i) - return false; + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); - int nSigsCount = CastToBigNum(stacktop(-i)).getint(); + int nSigsCount = CScriptNum(stacktop(-i), fRequireMinimal).getint(); if (nSigsCount < 0 || nSigsCount > nKeysCount) - return false; + return set_error(serror, SCRIPT_ERR_SIG_COUNT); int isig = ++i; i += nSigsCount; if ((int)stack.size() < i) - return false; + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); // Subset of script starting at the most recent codeseparator CScript scriptCode(pbegincodehash, pend); @@ -1111,15 +1955,18 @@ bool EvalScript(vector >& stack, const CScript& script, co valtype& vchSig = stacktop(-isig); valtype& vchPubKey = stacktop(-ikey); - if ((flags & SCRIPT_VERIFY_STRICTENC) && (!CheckSignatureEncoding(vchSig) || !CheckPubKeyEncoding(vchPubKey))) + // Note how this makes the exact order of pubkey/signature evaluation + // distinguishable by CHECKMULTISIG NOT if the STRICTENC flag is set. + // See the script_(in)valid tests for details. + if (!CheckSignatureEncoding(vchSig, flags, serror) || !CheckPubKeyEncoding(vchPubKey, flags, serror)) { + // serror is set return false; + } // Check signature - bool fOk = CheckSignatureEncoding(vchSig) && CheckPubKeyEncoding(vchPubKey) && - CheckSig(vchSig, vchPubKey, scriptCode, txTo, nIn, nHashType, flags); + bool fOk = checker.CheckSig(vchSig, vchPubKey, scriptCode); - if (fOk) - { + if (fOk) { isig++; nSigsCount--; } @@ -1127,7 +1974,8 @@ bool EvalScript(vector >& stack, const CScript& script, co nKeysCount--; // If there are more signatures left than keys left, - // then too many signatures have failed + // then too many signatures have failed. Exit early, + // without checking any further signatures. if (nSigsCount > nKeysCount) fSuccess = false; } @@ -1143,9 +1991,9 @@ bool EvalScript(vector >& stack, const CScript& script, co // so optionally verify it is exactly equal to zero prior // to removing it from the stack. if (stack.size() < 1) - return false; + return set_error(serror, SCRIPT_ERR_INVALID_STACK_OPERATION); if ((flags & SCRIPT_VERIFY_NULLDUMMY) && stacktop(-1).size()) - return error("CHECKMULTISIG dummy argument not null"); + return set_error(serror, SCRIPT_ERR_SIG_NULLDUMMY); popstack(stack); stack.push_back(fSuccess ? vchTrue : vchFalse); @@ -1155,30 +2003,29 @@ bool EvalScript(vector >& stack, const CScript& script, co if (fSuccess) popstack(stack); else - return false; + return set_error(serror, SCRIPT_ERR_CHECKMULTISIGVERIFY); } } break; default: - return false; + return set_error(serror, SCRIPT_ERR_BAD_OPCODE); } // Size limits if (stack.size() + altstack.size() > 1000) - return false; + return set_error(serror, SCRIPT_ERR_STACK_SIZE); } } catch (...) { - return false; + return set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR); } - if (!vfExec.empty()) - return false; + return set_error(serror, SCRIPT_ERR_UNBALANCED_CONDITIONAL); - return true; + return set_success(serror); } @@ -1186,9 +2033,6 @@ bool EvalScript(vector >& stack, const CScript& script, co - - - uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType) { if (nIn >= txTo.vin.size()) @@ -1251,6 +2095,54 @@ uint256 SignatureHash(CScript scriptCode, const CTransaction& txTo, unsigned int } +bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType) +{ + assert(nIn < txTo.vin.size()); + CTxIn& txin = txTo.vin[nIn]; + + // Leave out the signature from the hash, since a signature can't sign itself. + // The checksig op will also drop the signatures from its hash. + uint256 hash = SignatureHash(fromPubKey, txTo, nIn, nHashType); + + txnouttype whichType; + if (!Solver(keystore, fromPubKey, hash, nHashType, txin.scriptSig, whichType)) + return false; + + if (whichType == TX_SCRIPTHASH) + { + // Solver returns the subscript that need to be evaluated; + // the final scriptSig is the signatures from that + // and then the serialized subscript: + CScript subscript = txin.scriptSig; + + // Recompute txn hash using subscript in place of scriptPubKey: + uint256 hash2 = SignatureHash(subscript, txTo, nIn, nHashType); + + txnouttype subType; + bool fSolved = + Solver(keystore, subscript, hash2, nHashType, txin.scriptSig, subType) && subType != TX_SCRIPTHASH; + // Append serialized subscript whether or not it is completely signed: + txin.scriptSig << static_cast(subscript); + if (!fSolved) return false; + } + + // Test solution + return VerifyScript(txin.scriptSig, fromPubKey, STANDARD_SCRIPT_VERIFY_FLAGS, SignatureChecker(txTo, nIn)); +} + +bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType) +{ + assert(nIn < txTo.vin.size()); + CTxIn& txin = txTo.vin[nIn]; + assert(txin.prevout.n < txFrom.vout.size()); + const CTxOut& txout = txFrom.vout[txin.prevout.n]; + + return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType); +} + + + + // Valid signature cache, to avoid doing expensive ECDSA signature checking // twice for every transaction (once when accepted into memory pool, and // again when accepted into the block chain) @@ -1610,6 +2502,10 @@ class CKeyStoreIsMineVisitor : public boost::static_visitor bool operator()(const CNoDestination &dest) const { return false; } bool operator()(const CKeyID &keyID) const { return keystore->HaveKey(keyID); } bool operator()(const CScriptID &scriptID) const { return keystore->HaveCScript(scriptID); } + bool operator()(const CStealthAddress &stxAddr) const + { + return stxAddr.scan_secret.size() == ec_secret_size; + } }; bool IsMine(const CKeyStore &keystore, const CTxDestination &dest) @@ -1712,6 +2608,11 @@ class CAffectedKeysVisitor : public boost::static_visitor { Process(script); } + void operator()(const CStealthAddress &stxAddr) { + CScript script; + + } + void operator()(const CNoDestination &none) {} }; @@ -1753,8 +2654,58 @@ bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, vecto return true; } -bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, - unsigned int flags, int nHashType) +/*uint256 SignatureHash(const CScript& scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType) +{ + if (nIn >= txTo.vin.size()) { + // nIn out of range + return 1; + } + + // Check for invalid use of SIGHASH_SINGLE + if ((nHashType & 0x1f) == SIGHASH_SINGLE) { + if (nIn >= txTo.vout.size()) { + // nOut out of range + return 1; + } + } + + // Wrapper to serialize only the necessary parts of the transaction being signed + CTransactionSignatureSerializer txTmp(txTo, scriptCode, nIn, nHashType); + + // Serialize and hash + CHashWriter ss(SER_GETHASH, 0); + ss << txTmp << nHashType; + return ss.GetHash(); +}*/ + +bool SignatureChecker::VerifySignature(const std::vector& vchSig, const CPubKey& pubkey, const uint256& sighash) const +{ + return pubkey.Verify(sighash, vchSig); +} + +bool SignatureChecker::CheckSig(const vector& vchSigIn, const vector& vchPubKey, const CScript& scriptCode) const +{ + CPubKey pubkey(vchPubKey); + if (!pubkey.IsValid()) + return false; + + // Hash type is one byte tacked on to the end of the signature + vector vchSig(vchSigIn); + if (vchSig.empty()) + return false; + int nHashType = vchSig.back(); + vchSig.pop_back(); + + uint256 sighash = SignatureHash(scriptCode, txTo, nIn, nHashType); + + if (!VerifySignature(vchSig, pubkey, sighash)) + return false; + + return true; +} + + +bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType) { vector > stack, stackCopy; if (!EvalScript(stack, scriptSig, txTo, nIn, flags, nHashType)) @@ -1790,8 +2741,61 @@ bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const C return true; } +bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* serror) +{ + set_error(serror, SCRIPT_ERR_UNKNOWN_ERROR); -bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType) + if ((flags & SCRIPT_VERIFY_SIGPUSHONLY) != 0 && !scriptSig.IsPushOnly()) { + return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY); + } + + vector > stack, stackCopy; + if (!EvalScript(stack, scriptSig, flags, checker, serror)) + // serror is set + return false; + if (flags & SCRIPT_VERIFY_P2SH) + stackCopy = stack; + if (!EvalScript(stack, scriptPubKey, flags, checker, serror)) + // serror is set + return false; + if (stack.empty()) + return set_error(serror, SCRIPT_ERR_EVAL_FALSE); + + if (CastToBool(stack.back()) == false) + return set_error(serror, SCRIPT_ERR_EVAL_FALSE); + + // Additional validation for spend-to-script-hash transactions: + if ((flags & SCRIPT_VERIFY_P2SH) && scriptPubKey.IsPayToScriptHash()) + { + // scriptSig must be literals-only or validation fails + if (!scriptSig.IsPushOnly()) + return set_error(serror, SCRIPT_ERR_SIG_PUSHONLY); + + // stackCopy cannot be empty here, because if it was the + // P2SH HASH <> EQUAL scriptPubKey would be evaluated with + // an empty stack and the EvalScript above would return false. + assert(!stackCopy.empty()); + + const valtype& pubKeySerialized = stackCopy.back(); + CScript pubKey2(pubKeySerialized.begin(), pubKeySerialized.end()); + popstack(stackCopy); + + if (!EvalScript(stackCopy, pubKey2, flags, checker, serror)) + // serror is set + return false; + if (stackCopy.empty()) + return set_error(serror, SCRIPT_ERR_EVAL_FALSE); + if (!CastToBool(stackCopy.back())) + return set_error(serror, SCRIPT_ERR_EVAL_FALSE); + else + return set_success(serror); + } + + return set_success(serror); +} + + +/*bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType) { assert(nIn < txTo.vin.size()); CTxIn& txin = txTo.vin[nIn]; @@ -1824,9 +2828,9 @@ bool SignSignature(const CKeyStore &keystore, const CScript& fromPubKey, CTransa // Test solution return VerifyScript(txin.scriptSig, fromPubKey, txTo, nIn, STANDARD_SCRIPT_VERIFY_FLAGS, 0); -} +}*/ -bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType) +/*bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType) { assert(nIn < txTo.vin.size()); CTxIn& txin = txTo.vin[nIn]; @@ -1835,7 +2839,7 @@ bool SignSignature(const CKeyStore &keystore, const CTransaction& txFrom, CTrans const CTxOut& txout = txFrom.vout[txin.prevout.n]; return SignSignature(keystore, txout.scriptPubKey, txTo, nIn, nHashType); -} +}*/ bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType) { @@ -2081,6 +3085,13 @@ class CScriptVisitor : public boost::static_visitor *script << OP_HASH160 << scriptID << OP_EQUAL; return true; } + + bool operator()(const CStealthAddress &stxAddr) const { + script->clear(); + //*script << OP_HASH160 << scriptID << OP_EQUAL; + printf("TODO\n"); + return false; + } }; void CScript::SetDestination(const CTxDestination& dest) @@ -2218,3 +3229,46 @@ bool CScriptCompressor::Decompress(unsigned int nSize, const std::vector& keys) +{ + CScript script; + + script << CScript::EncodeOP_N(nRequired); + BOOST_FOREACH(const CPubKey& key, keys) + script << ToByteVector(key); + script << CScript::EncodeOP_N(keys.size()) << OP_CHECKMULTISIG; + return script; +} + +bool CScript::IsNormalPaymentScript() const +{ + if(this->size() != 25) return false; + + std::string str; + opcodetype opcode; + const_iterator pc = begin(); + int i = 0; + while (pc < end()) + { + GetOp(pc, opcode); + + if( i == 0 && opcode != OP_DUP) return false; + else if(i == 1 && opcode != OP_HASH160) return false; + else if(i == 3 && opcode != OP_EQUALVERIFY) return false; + else if(i == 4 && opcode != OP_CHECKSIG) return false; + else if(i == 5) return false; + + i++; + } + + return true; +} diff --git a/src/script.h b/src/script.h index 0ff6966..48b8329 100644 --- a/src/script.h +++ b/src/script.h @@ -17,14 +17,73 @@ #include "keystore.h" #include "bignum.h" #include "util.h" +#include "stealth.h" typedef std::vector valtype; +class CKeyStore; class CTransaction; +class BaseSignatureChecker; + static const unsigned int MAX_SCRIPT_ELEMENT_SIZE = 520; // bytes static const unsigned int MAX_OP_RETURN_RELAY = 40; // bytes +template +std::vector ToByteVector(const T& in) +{ + return std::vector(in.begin(), in.end()); +} + +typedef enum ScriptError_t +{ + SCRIPT_ERR_OK = 0, + SCRIPT_ERR_UNKNOWN_ERROR, + SCRIPT_ERR_EVAL_FALSE, + SCRIPT_ERR_OP_RETURN, + + /* Max sizes */ + SCRIPT_ERR_SCRIPT_SIZE, + SCRIPT_ERR_PUSH_SIZE, + SCRIPT_ERR_OP_COUNT, + SCRIPT_ERR_STACK_SIZE, + SCRIPT_ERR_SIG_COUNT, + SCRIPT_ERR_PUBKEY_COUNT, + + /* Failed verify operations */ + SCRIPT_ERR_VERIFY, + SCRIPT_ERR_EQUALVERIFY, + SCRIPT_ERR_CHECKMULTISIGVERIFY, + SCRIPT_ERR_CHECKSIGVERIFY, + SCRIPT_ERR_NUMEQUALVERIFY, + + /* Logical/Format/Canonical errors */ + SCRIPT_ERR_BAD_OPCODE, + SCRIPT_ERR_DISABLED_OPCODE, + SCRIPT_ERR_INVALID_STACK_OPERATION, + SCRIPT_ERR_INVALID_ALTSTACK_OPERATION, + SCRIPT_ERR_UNBALANCED_CONDITIONAL, + + /* BIP62 */ + SCRIPT_ERR_SIG_HASHTYPE, + SCRIPT_ERR_SIG_DER, + SCRIPT_ERR_MINIMALDATA, + SCRIPT_ERR_SIG_PUSHONLY, + SCRIPT_ERR_SIG_HIGH_S, + SCRIPT_ERR_SIG_NULLDUMMY, + SCRIPT_ERR_PUBKEYTYPE, + + /* softfork safeness */ + SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS, + + SCRIPT_ERR_ERROR_COUNT +} ScriptError; + +#define SCRIPT_ERR_LAST SCRIPT_ERR_ERROR_COUNT + +const char* ScriptErrorString(const ScriptError error); + + /** Signature hash types/flags */ enum { @@ -38,8 +97,34 @@ enum enum { SCRIPT_VERIFY_NONE = 0, - SCRIPT_VERIFY_NOCACHE = (1U << 0), // do not store results in signature cache (but do query it) - SCRIPT_VERIFY_NULLDUMMY = (1U << 1), // verify dummy stack item consumed by CHECKMULTISIG is of zero-length + SCRIPT_VERIFY_NOCACHE = (1U << 0), + // Evaluate P2SH subscripts (softfork safe, BIP16). + SCRIPT_VERIFY_P2SH = (1U << 0), + + // Passing a non-strict-DER signature or one with undefined hashtype to a checksig operation causes script failure. + // Evaluating a pubkey that is not (0x04 + 64 bytes) or (0x02 or 0x03 + 32 bytes) by checksig causes script failure. + // (softfork safe, but not used or intended as a consensus rule). + SCRIPT_VERIFY_STRICTENC = (1U << 1), + + // Passing a non-strict-DER signature to a checksig operation causes script failure (softfork safe, BIP62 rule 1) + SCRIPT_VERIFY_DERSIG = (1U << 2), + + // Passing a non-strict-DER signature or one with S > order/2 to a checksig operation causes script failure + // (softfork safe, BIP62 rule 5). + SCRIPT_VERIFY_LOW_S = (1U << 3), + + // verify dummy stack item consumed by CHECKMULTISIG is of zero-length (softfork safe, BIP62 rule 7). + SCRIPT_VERIFY_NULLDUMMY = (1U << 4), + + // Using a non-push operator in the scriptSig causes script failure (softfork safe, BIP62 rule 2). + SCRIPT_VERIFY_SIGPUSHONLY = (1U << 5), + + // Require minimal encodings for all push operations (OP_0... OP_16, OP_1NEGATE where possible, direct + // pushes up to 75 bytes, OP_PUSHDATA up to 255 bytes, OP_PUSHDATA2 for anything larger). Evaluating + // any other push causes the script to fail (BIP62 rule 3). + // In addition, whenever a stack element is interpreted as a number, it must be of minimal length (BIP62 rule 4). + // (softfork safe) + SCRIPT_VERIFY_MINIMALDATA = (1U << 6), // Discourage use of NOPs reserved for upgrades (NOP1-10) // @@ -48,10 +133,9 @@ enum // thus rendering the script invalid; with this flag set executing // discouraged NOPs fails the script. This verification flag will never be // a mandatory flag applied to scripts in a block. NOPs that are not - // executed, e.g. within an unexecuted IF ENDIF block, are *not* rejected. - SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS = (1U << 2), + // executed, e.g. within an unexecuted IF ENDIF block, are *not* rejected. + SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS = (1U << 7) - SCRIPT_VERIFY_STRICTENC = (1U << 3), }; // Mandatory script verification flags that all new blocks must comply with for @@ -95,7 +179,7 @@ class CNoDestination { * * CScriptID: TX_SCRIPTHASH destination * A CTxDestination is the internal data type encoded in a CBitcoinAddress */ -typedef boost::variant CTxDestination; +typedef boost::variant CTxDestination; const char* GetTxnOutputType(txnouttype t); @@ -270,9 +354,174 @@ inline std::string StackString(const std::vector >& v return str; } +class scriptnum_error : public std::runtime_error +{ +public: + explicit scriptnum_error(const std::string& str) : std::runtime_error(str) {} +}; +class CScriptNum +{ +/** + * Numeric opcodes (OP_1ADD, etc) are restricted to operating on 4-byte integers. + * The semantics are subtle, though: operands must be in the range [-2^31 +1...2^31 -1], + * but results may overflow (and are valid as long as they are not used in a subsequent + * numeric operation). CScriptNum enforces those semantics by storing results as + * an int64 and allowing out-of-range values to be returned as a vector of bytes but + * throwing an exception if arithmetic is done or the result is interpreted as an integer. + */ +public: + explicit CScriptNum(const int64_t& n) + { + m_value = n; + } + explicit CScriptNum(const std::vector& vch, bool fRequireMinimal) + { + if (vch.size() > nMaxNumSize) { + throw scriptnum_error("script number overflow"); + } + if (fRequireMinimal && vch.size() > 0) { + // Check that the number is encoded with the minimum possible + // number of bytes. + // + // If the most-significant-byte - excluding the sign bit - is zero + // then we're not minimal. Note how this test also rejects the + // negative-zero encoding, 0x80. + if ((vch.back() & 0x7f) == 0) { + // One exception: if there's more than one byte and the most + // significant bit of the second-most-significant-byte is set + // it would conflict with the sign bit. An example of this case + // is +-255, which encode to 0xff00 and 0xff80 respectively. + // (big-endian). + if (vch.size() <= 1 || (vch[vch.size() - 2] & 0x80) == 0) { + throw scriptnum_error("non-minimally encoded script number"); + } + } + } + m_value = set_vch(vch); + } + + inline bool operator==(const int64_t& rhs) const { return m_value == rhs; } + inline bool operator!=(const int64_t& rhs) const { return m_value != rhs; } + inline bool operator<=(const int64_t& rhs) const { return m_value <= rhs; } + inline bool operator< (const int64_t& rhs) const { return m_value < rhs; } + inline bool operator>=(const int64_t& rhs) const { return m_value >= rhs; } + inline bool operator> (const int64_t& rhs) const { return m_value > rhs; } + + inline bool operator==(const CScriptNum& rhs) const { return operator==(rhs.m_value); } + inline bool operator!=(const CScriptNum& rhs) const { return operator!=(rhs.m_value); } + inline bool operator<=(const CScriptNum& rhs) const { return operator<=(rhs.m_value); } + inline bool operator< (const CScriptNum& rhs) const { return operator< (rhs.m_value); } + inline bool operator>=(const CScriptNum& rhs) const { return operator>=(rhs.m_value); } + inline bool operator> (const CScriptNum& rhs) const { return operator> (rhs.m_value); } + + inline CScriptNum operator+( const int64_t& rhs) const { return CScriptNum(m_value + rhs);} + inline CScriptNum operator-( const int64_t& rhs) const { return CScriptNum(m_value - rhs);} + inline CScriptNum operator+( const CScriptNum& rhs) const { return operator+(rhs.m_value); } + inline CScriptNum operator-( const CScriptNum& rhs) const { return operator-(rhs.m_value); } + + inline CScriptNum& operator+=( const CScriptNum& rhs) { return operator+=(rhs.m_value); } + inline CScriptNum& operator-=( const CScriptNum& rhs) { return operator-=(rhs.m_value); } + + inline CScriptNum operator-() const + { + assert(m_value != std::numeric_limits::min()); + return CScriptNum(-m_value); + } + + inline CScriptNum& operator=( const int64_t& rhs) + { + m_value = rhs; + return *this; + } + + inline CScriptNum& operator+=( const int64_t& rhs) + { + assert(rhs == 0 || (rhs > 0 && m_value <= std::numeric_limits::max() - rhs) || + (rhs < 0 && m_value >= std::numeric_limits::min() - rhs)); + m_value += rhs; + return *this; + } + + inline CScriptNum& operator-=( const int64_t& rhs) + { + assert(rhs == 0 || (rhs > 0 && m_value >= std::numeric_limits::min() + rhs) || + (rhs < 0 && m_value <= std::numeric_limits::max() + rhs)); + m_value -= rhs; + return *this; + } + + int getint() const + { + if (m_value > std::numeric_limits::max()) + return std::numeric_limits::max(); + else if (m_value < std::numeric_limits::min()) + return std::numeric_limits::min(); + return m_value; + } + + std::vector getvch() const + { + return serialize(m_value); + } + + static std::vector serialize(const int64_t& value) + { + if(value == 0) + return std::vector(); + + std::vector result; + const bool neg = value < 0; + uint64_t absvalue = neg ? -value : value; + + while(absvalue) + { + result.push_back(absvalue & 0xff); + absvalue >>= 8; + } + +// - If the most significant byte is >= 0x80 and the value is positive, push a +// new zero-byte to make the significant byte < 0x80 again. + +// - If the most significant byte is >= 0x80 and the value is negative, push a +// new 0x80 byte that will be popped off when converting to an integral. + +// - If the most significant byte is < 0x80 and the value is negative, add +// 0x80 to it, since it will be subtracted and interpreted as a negative when +// converting to an integral. + + if (result.back() & 0x80) + result.push_back(neg ? 0x80 : 0); + else if (neg) + result.back() |= 0x80; + + return result; + } + + static const size_t nMaxNumSize = 4; + +private: + static int64_t set_vch(const std::vector& vch) + { + if (vch.empty()) + return 0; + + int64_t result = 0; + for (size_t i = 0; i != vch.size(); ++i) + result |= static_cast(vch[i]) << 8*i; + + // If the input vector's most significant byte is 0x80, remove it from + // the result's msb and return a negative. + if (vch.back() & 0x80) + return -((int64_t)(result & ~(0x80ULL << (8 * (vch.size() - 1))))); + + return result; + } + + int64_t m_value; +}; @@ -567,7 +816,7 @@ class CScript : public std::vector // Accurately count sigOps, including sigOps in // pay-to-script-hash transactions: unsigned int GetSigOpCount(const CScript& scriptSig) const; - + bool IsNormalPaymentScript() const; bool IsPayToScriptHash() const; // Called by IsStandardTx and P2SH VerifyScript (which makes it consensus-critical). @@ -702,6 +951,7 @@ class CScriptCompressor bool IsDERSignature(const valtype &vchSig, bool haveHashType = true); bool EvalScript(std::vector >& stack, const CScript& script, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType); +bool EvalScript(std::vector >& stack, const CScript& script, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* error = NULL); bool Solver(const CScript& scriptPubKey, txnouttype& typeRet, std::vector >& vSolutionsRet); int ScriptSigArgsExpected(txnouttype t, const std::vector >& vSolutions); bool IsStandard(const CScript& scriptPubKey, txnouttype& whichType); @@ -712,12 +962,46 @@ bool ExtractDestination(const CScript& scriptPubKey, CTxDestination& addressRet) bool ExtractDestinations(const CScript& scriptPubKey, txnouttype& typeRet, std::vector& addressRet, int& nRequiredRet); bool SignSignature(const CKeyStore& keystore, const CScript& fromPubKey, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL); bool SignSignature(const CKeyStore& keystore, const CTransaction& txFrom, CTransaction& txTo, unsigned int nIn, int nHashType=SIGHASH_ALL); -bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, - unsigned int flags, int nHashType); +bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType); bool VerifySignature(const CTransaction& txFrom, const CTransaction& txTo, unsigned int nIn, unsigned int flags, int nHashType); +bool VerifyScript(const CScript& scriptSig, const CScript& scriptPubKey, unsigned int flags, const BaseSignatureChecker& checker, ScriptError* error = NULL); + // Given two sets of signatures for scriptPubKey, possibly with OP_0 placeholders, // combine them intelligently and return the result. CScript CombineSignatures(CScript scriptPubKey, const CTransaction& txTo, unsigned int nIn, const CScript& scriptSig1, const CScript& scriptSig2); +CScript GetScriptForDestination(const CTxDestination& dest); +CScript GetScriptForMultisig(int nRequired, const std::vector& keys); + +bool Solver(const CKeyStore& keystore, const CScript& scriptPubKey, uint256 hash, int nHashType, + CScript& scriptSigRet, txnouttype& whichTypeRet); +//uint256 SignatureHash(const CScript &scriptCode, const CTransaction& txTo, unsigned int nIn, int nHashType); + + +class BaseSignatureChecker +{ +public: + virtual bool CheckSig(const std::vector& scriptSig, const std::vector& vchPubKey, const CScript& scriptCode) const + { + return false; + } + + virtual ~BaseSignatureChecker() {} +}; + +class SignatureChecker : public BaseSignatureChecker +{ +private: + const CTransaction& txTo; + unsigned int nIn; + +protected: + virtual bool VerifySignature(const std::vector& vchSig, const CPubKey& vchPubKey, const uint256& sighash) const; + +public: + SignatureChecker(const CTransaction& txToIn, unsigned int nInIn) : txTo(txToIn), nIn(nInIn) {} + bool CheckSig(const std::vector& scriptSig, const std::vector& vchPubKey, const CScript& scriptCode) const; +}; + #endif diff --git a/src/serialize.h b/src/serialize.h index 2914649..a11afd5 100644 --- a/src/serialize.h +++ b/src/serialize.h @@ -36,6 +36,46 @@ inline T& REF(const T& val) return const_cast(val); } +/** + * Used to acquire a non-const pointer "this" to generate bodies + * of const serialization operations from a template + */ +template +inline T* NCONST_PTR(const T* val) +{ + return const_cast(val); +} + +/** + * Get begin pointer of vector (non-const version). + * @note These functions avoid the undefined case of indexing into an empty + * vector, as well as that of indexing after the end of the vector. + */ +template +inline T* begin_ptr(std::vector& v) +{ + return v.empty() ? NULL : &v[0]; +} +/** Get begin pointer of vector (const version) */ +template +inline const T* begin_ptr(const std::vector& v) +{ + return v.empty() ? NULL : &v[0]; +} +/** Get end pointer of vector (non-const version) */ +template +inline T* end_ptr(std::vector& v) +{ + return v.empty() ? NULL : (&v[0] + v.size()); +} +/** Get end pointer of vector (const version) */ +template +inline const T* end_ptr(const std::vector& v) +{ + return v.empty() ? NULL : (&v[0] + v.size()); +} + + ///////////////////////////////////////////////////////////////// // // Templates for serializing to anything that looks like a stream, @@ -93,9 +133,29 @@ enum } #define READWRITE(obj) (nSerSize += ::SerReadWrite(s, (obj), nType, nVersion, ser_action)) +#define READWRITES(obj) (::SerReadWrite(s, (obj), nType, nVersion, ser_action)) - +/** + * Implement three methods for serializable objects. These are actually wrappers over + * "SerializationOp" template, which implements the body of each class' serialization + * code. Adding "ADD_SERIALIZE_METHODS" in the body of the class causes these wrappers to be + * added as members. + */ +#define ADD_SERIALIZE_METHODS \ + size_t GetSerializeSize(int nType, int nVersion) const { \ + CSizeComputer s(nType, nVersion); \ + NCONST_PTR(this)->SerializationOp(s, CSerActionSerialize(), nType, nVersion);\ + return s.size(); \ + } \ + template \ + void Serialize(Stream& s, int nType, int nVersion) const { \ + NCONST_PTR(this)->SerializationOp(s, CSerActionSerialize(), nType, nVersion);\ + } \ + template \ + void Unserialize(Stream& s, int nType, int nVersion) { \ + SerializationOp(s, CSerActionUnserialize(), nType, nVersion); \ + } @@ -1246,4 +1306,6 @@ class CAutoFile } }; + + #endif diff --git a/src/smessage.cpp b/src/smessage.cpp new file mode 100644 index 0000000..ae7bd24 --- /dev/null +++ b/src/smessage.cpp @@ -0,0 +1,3971 @@ +// Copyright (c) 2014 The ShadowCoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +/* +Notes: + Running with -debug could leave to and from address hashes and public keys in the log. + + + parameters: + -nosmsg Disable secure messaging (fNoSmsg) + -debugsmsg Show extra debug messages (fDebugSmsg) + -smsgscanchain Scan the block chain for public key addresses on startup + + + Wallet Locked + A copy of each incoming message is stored in bucket files ending in _wl.dat + wl (wallet locked) bucket files are deleted if they expire, like normal buckets + When the wallet is unlocked all the messages in wl files are scanned. + + + Address Whitelist + Owned Addresses are stored in smsgAddresses vector + Saved to smsg.ini + Modify options using the smsglocalkeys rpc command or edit the smsg.ini file (with client closed) + + +*/ + +#include "smessage.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + + +#include "base58.h" +#include "db.h" +#include "init.h" // pwalletMain +#include "main.h" +#include "txdb.h" +#include "sync.h" +#include "eckey.h" + +#include "lz4/lz4.c" + +#include "xxhash/xxhash.h" +#include "xxhash/xxhash.c" + + +boost::thread_group threadGroupSmsg; + +// TODO: For buckets older than current, only need to store no. messages and hash in memory + +boost::signals2::signal NotifySecMsgInboxChanged; +boost::signals2::signal NotifySecMsgOutboxChanged; +boost::signals2::signal NotifySecMsgWalletUnlocked; + +bool fSecMsgEnabled = false; + +std::map smsgBuckets; +std::vector smsgAddresses; +SecMsgOptions smsgOptions; + + +CCriticalSection cs_smsg; +CCriticalSection cs_smsgDB; +CCriticalSection cs_smsgThreads; + +leveldb::DB *smsgDB = NULL; + + +namespace fs = boost::filesystem; + +bool SecMsgCrypter::SetKey(const std::vector& vchNewKey, uint8_t* chNewIV) +{ + if (vchNewKey.size() < sizeof(chKey)) + return false; + + return SetKey(&vchNewKey[0], chNewIV); +}; + +bool SecMsgCrypter::SetKey(const uint8_t* chNewKey, uint8_t* chNewIV) +{ + // -- for EVP_aes_256_cbc() key must be 256 bit, iv must be 128 bit. + memcpy(&chKey[0], chNewKey, sizeof(chKey)); + memcpy(chIV, chNewIV, sizeof(chIV)); + + fKeySet = true; + return true; +}; + +bool SecMsgCrypter::Encrypt(uint8_t* chPlaintext, uint32_t nPlain, std::vector &vchCiphertext) +{ + if (!fKeySet) + return false; + + // -- max ciphertext len for a n bytes of plaintext is n + AES_BLOCK_SIZE - 1 bytes + int nLen = nPlain; + + int nCLen = nLen + AES_BLOCK_SIZE, nFLen = 0; + vchCiphertext = std::vector (nCLen); + + EVP_CIPHER_CTX ctx; + + bool fOk = true; + + EVP_CIPHER_CTX_init(&ctx); + if (fOk) fOk = EVP_EncryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, &chKey[0], &chIV[0]); + if (fOk) fOk = EVP_EncryptUpdate(&ctx, &vchCiphertext[0], &nCLen, chPlaintext, nLen); + if (fOk) fOk = EVP_EncryptFinal_ex(&ctx, (&vchCiphertext[0])+nCLen, &nFLen); + EVP_CIPHER_CTX_cleanup(&ctx); + + if (!fOk) + return false; + + vchCiphertext.resize(nCLen + nFLen); + + return true; +}; + +bool SecMsgCrypter::Decrypt(uint8_t* chCiphertext, uint32_t nCipher, std::vector& vchPlaintext) +{ + if (!fKeySet) + return false; + + // plaintext will always be equal to or lesser than length of ciphertext + int nPLen = nCipher, nFLen = 0; + + vchPlaintext.resize(nCipher); + + EVP_CIPHER_CTX ctx; + + bool fOk = true; + + EVP_CIPHER_CTX_init(&ctx); + if (fOk) fOk = EVP_DecryptInit_ex(&ctx, EVP_aes_256_cbc(), NULL, &chKey[0], &chIV[0]); + if (fOk) fOk = EVP_DecryptUpdate(&ctx, &vchPlaintext[0], &nPLen, &chCiphertext[0], nCipher); + if (fOk) fOk = EVP_DecryptFinal_ex(&ctx, (&vchPlaintext[0])+nPLen, &nFLen); + EVP_CIPHER_CTX_cleanup(&ctx); + + if (!fOk) + return false; + + vchPlaintext.resize(nPLen + nFLen); + + return true; +}; + +void SecMsgBucket::hashBucket() +{ + if (fDebugSmsg) + LogPrintf("SecMsgBucket::hashBucket()\n"); + + timeChanged = GetTime(); + + std::set::iterator it; + + void* state = XXH32_init(1); + + for (it = setTokens.begin(); it != setTokens.end(); ++it) + { + XXH32_update(state, it->sample, 8); + }; + + hash = XXH32_digest(state); + + if (fDebugSmsg) + LogPrintf("Hashed %u messages, hash %u\n", setTokens.size(), hash); +}; + + +bool SecMsgDB::Open(const char* pszMode) +{ + if (smsgDB) + { + pdb = smsgDB; + return true; + }; + + bool fCreate = strchr(pszMode, 'c'); + + fs::path fullpath = GetDataDir() / "smsgDB"; + + if (!fCreate + && (!fs::exists(fullpath) + || !fs::is_directory(fullpath))) + { + LogPrintf("SecMsgDB::open() - DB does not exist.\n"); + return false; + }; + + leveldb::Options options; + options.create_if_missing = fCreate; + leveldb::Status s = leveldb::DB::Open(options, fullpath.string(), &smsgDB); + + if (!s.ok()) + { + LogPrintf("SecMsgDB::open() - Error opening db: %s.\n", s.ToString().c_str()); + return false; + }; + + pdb = smsgDB; + + return true; +}; + + +class SecMsgBatchScanner : public leveldb::WriteBatch::Handler +{ +public: + std::string needle; + bool* deleted; + std::string* foundValue; + bool foundEntry; + + SecMsgBatchScanner() : foundEntry(false) {} + + virtual void Put(const leveldb::Slice& key, const leveldb::Slice& value) + { + if (key.ToString() == needle) + { + foundEntry = true; + *deleted = false; + *foundValue = value.ToString(); + }; + }; + + virtual void Delete(const leveldb::Slice& key) + { + if (key.ToString() == needle) + { + foundEntry = true; + *deleted = true; + }; + }; +}; + +// When performing a read, if we have an active batch we need to check it first +// before reading from the database, as the rest of the code assumes that once +// a database transaction begins reads are consistent with it. It would be good +// to change that assumption in future and avoid the performance hit, though in +// practice it does not appear to be large. +bool SecMsgDB::ScanBatch(const CDataStream& key, std::string* value, bool* deleted) const +{ + if (!activeBatch) + return false; + + *deleted = false; + SecMsgBatchScanner scanner; + scanner.needle = key.str(); + scanner.deleted = deleted; + scanner.foundValue = value; + leveldb::Status s = activeBatch->Iterate(&scanner); + if (!s.ok()) + { + LogPrintf("SecMsgDB ScanBatch error: %s\n", s.ToString().c_str()); + return false; + }; + + return scanner.foundEntry; +} + +bool SecMsgDB::TxnBegin() +{ + if (activeBatch) + return true; + activeBatch = new leveldb::WriteBatch(); + return true; +}; + +bool SecMsgDB::TxnCommit() +{ + if (!activeBatch) + return false; + + leveldb::WriteOptions writeOptions; + writeOptions.sync = true; + leveldb::Status status = pdb->Write(writeOptions, activeBatch); + delete activeBatch; + activeBatch = NULL; + + if (!status.ok()) + { + LogPrintf("SecMsgDB batch commit failure: %s\n", status.ToString().c_str()); + return false; + }; + + return true; +}; + +bool SecMsgDB::TxnAbort() +{ + delete activeBatch; + activeBatch = NULL; + return true; +}; + +bool SecMsgDB::ReadPK(CKeyID& addr, CPubKey& pubkey) +{ + if (!pdb) + return false; + + CDataStream ssKey(SER_DISK, CLIENT_VERSION); + ssKey.reserve(sizeof(addr) + 2); + ssKey << 'p'; + ssKey << 'k'; + ssKey << addr; + std::string strValue; + + bool readFromDb = true; + if (activeBatch) + { + // -- check activeBatch first + bool deleted = false; + readFromDb = ScanBatch(ssKey, &strValue, &deleted) == false; + if (deleted) + return false; + }; + + if (readFromDb) + { + leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &strValue); + if (!s.ok()) + { + if (s.IsNotFound()) + return false; + LogPrintf("LevelDB read failure: %s\n", s.ToString().c_str()); + return false; + }; + }; + + try { + CDataStream ssValue(strValue.data(), strValue.data() + strValue.size(), SER_DISK, CLIENT_VERSION); + ssValue >> pubkey; + } catch (std::exception& e) { + LogPrintf("SecMsgDB::ReadPK() unserialize threw: %s.\n", e.what()); + return false; + } + + return true; +}; + +bool SecMsgDB::WritePK(CKeyID& addr, CPubKey& pubkey) +{ + if (!pdb) + return false; + + CDataStream ssKey(SER_DISK, CLIENT_VERSION); + ssKey.reserve(sizeof(addr) + 2); + ssKey << 'p'; + ssKey << 'k'; + ssKey << addr; + CDataStream ssValue(SER_DISK, CLIENT_VERSION); + ssValue.reserve(sizeof(pubkey)); + ssValue << pubkey; + + if (activeBatch) + { + activeBatch->Put(ssKey.str(), ssValue.str()); + return true; + }; + + leveldb::WriteOptions writeOptions; + writeOptions.sync = true; + leveldb::Status s = pdb->Put(writeOptions, ssKey.str(), ssValue.str()); + if (!s.ok()) + { + LogPrintf("SecMsgDB write failure: %s\n", s.ToString().c_str()); + return false; + }; + + return true; +}; + +bool SecMsgDB::ExistsPK(CKeyID& addr) +{ + if (!pdb) + return false; + + CDataStream ssKey(SER_DISK, CLIENT_VERSION); + ssKey.reserve(sizeof(addr)+2); + ssKey << 'p'; + ssKey << 'k'; + ssKey << addr; + std::string unused; + + if (activeBatch) + { + bool deleted; + if (ScanBatch(ssKey, &unused, &deleted) && !deleted) + { + return true; + }; + }; + + leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &unused); + return s.IsNotFound() == false; +}; + + +bool SecMsgDB::NextSmesg(leveldb::Iterator* it, std::string& prefix, uint8_t* chKey, SecMsgStored& smsgStored) +{ + if (!pdb) + return false; + + if (!it->Valid()) // first run + it->Seek(prefix); + else + it->Next(); + + if (!(it->Valid() + && it->key().size() == 18 + && memcmp(it->key().data(), prefix.data(), 2) == 0)) + return false; + + memcpy(chKey, it->key().data(), 18); + + try { + CDataStream ssValue(it->value().data(), it->value().data() + it->value().size(), SER_DISK, CLIENT_VERSION); + ssValue >> smsgStored; + } catch (std::exception& e) { + LogPrintf("SecMsgDB::NextSmesg() unserialize threw: %s.\n", e.what()); + return false; + } + + return true; +}; + +bool SecMsgDB::NextSmesgKey(leveldb::Iterator* it, std::string& prefix, uint8_t* chKey) +{ + if (!pdb) + return false; + + if (!it->Valid()) // first run + it->Seek(prefix); + else + it->Next(); + + if (!(it->Valid() + && it->key().size() == 18 + && memcmp(it->key().data(), prefix.data(), 2) == 0)) + return false; + + memcpy(chKey, it->key().data(), 18); + + return true; +}; + +bool SecMsgDB::ReadSmesg(uint8_t* chKey, SecMsgStored& smsgStored) +{ + if (!pdb) + return false; + + CDataStream ssKey(SER_DISK, CLIENT_VERSION); + ssKey.write((const char*)chKey, 18); + std::string strValue; + + bool readFromDb = true; + if (activeBatch) + { + // -- check activeBatch first + bool deleted = false; + readFromDb = ScanBatch(ssKey, &strValue, &deleted) == false; + if (deleted) + return false; + }; + + if (readFromDb) + { + leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &strValue); + if (!s.ok()) + { + if (s.IsNotFound()) + return false; + LogPrintf("LevelDB read failure: %s\n", s.ToString().c_str()); + return false; + }; + }; + + try { + CDataStream ssValue(strValue.data(), strValue.data() + strValue.size(), SER_DISK, CLIENT_VERSION); + ssValue >> smsgStored; + } catch (std::exception& e) { + LogPrintf("SecMsgDB::ReadSmesg() unserialize threw: %s.\n", e.what()); + return false; + } + + return true; +}; + +bool SecMsgDB::WriteSmesg(uint8_t* chKey, SecMsgStored& smsgStored) +{ + if (!pdb) + return false; + + CDataStream ssKey(SER_DISK, CLIENT_VERSION); + ssKey.write((const char*)chKey, 18); + CDataStream ssValue(SER_DISK, CLIENT_VERSION); + ssValue << smsgStored; + + if (activeBatch) + { + activeBatch->Put(ssKey.str(), ssValue.str()); + return true; + }; + + leveldb::WriteOptions writeOptions; + writeOptions.sync = true; + leveldb::Status s = pdb->Put(writeOptions, ssKey.str(), ssValue.str()); + if (!s.ok()) + { + LogPrintf("SecMsgDB write failed: %s\n", s.ToString().c_str()); + return false; + }; + + return true; +}; + +bool SecMsgDB::ExistsSmesg(uint8_t* chKey) +{ + if (!pdb) + return false; + + CDataStream ssKey(SER_DISK, CLIENT_VERSION); + ssKey.write((const char*)chKey, 18); + std::string unused; + + if (activeBatch) + { + bool deleted; + if (ScanBatch(ssKey, &unused, &deleted) && !deleted) + { + return true; + }; + }; + + leveldb::Status s = pdb->Get(leveldb::ReadOptions(), ssKey.str(), &unused); + return s.IsNotFound() == false; + return true; +}; + +bool SecMsgDB::EraseSmesg(uint8_t* chKey) +{ + CDataStream ssKey(SER_DISK, CLIENT_VERSION); + ssKey.write((const char*)chKey, 18); + + if (activeBatch) + { + activeBatch->Delete(ssKey.str()); + return true; + }; + + leveldb::WriteOptions writeOptions; + writeOptions.sync = true; + leveldb::Status s = pdb->Delete(writeOptions, ssKey.str()); + + if (s.ok() || s.IsNotFound()) + return true; + LogPrintf("SecMsgDB erase failed: %s\n", s.ToString().c_str()); + return false; +}; + +void ThreadSecureMsg() +{ + // -- bucket management thread + + while (fSecMsgEnabled) + { + int64_t now = GetTime(); + + if (fDebugSmsg) + LogPrintf("SecureMsgThread %d \n", now); + + int64_t cutoffTime = now - SMSG_RETENTION; + { + LOCK(cs_smsg); + + for (std::map::iterator it(smsgBuckets.begin()); it != smsgBuckets.end(); it++) + { + //if (fDebugSmsg) + // LogPrintf("Checking bucket %d", size %u \n", it->first, it->second.setTokens.size()); + if (it->first < cutoffTime) + { + if (fDebugSmsg) + LogPrintf("Removing bucket %d \n", it->first); + + std::string fileName = boost::lexical_cast(it->first); + + fs::path fullPath = GetDataDir() / "smsgStore" / (fileName + "_01.dat"); + if (fs::exists(fullPath)) + { + try { + fs::remove(fullPath); + } catch (const fs::filesystem_error& ex) + { + LogPrintf("Error removing bucket file %s.\n", ex.what()); + }; + } else + { + LogPrintf("Path %s does not exist \n", fullPath.string().c_str()); + }; + + // -- look for a wl file, it stores incoming messages when wallet is locked + fullPath = GetDataDir() / "smsgStore" / (fileName + "_01_wl.dat"); + if (fs::exists(fullPath)) + { + try { + fs::remove(fullPath); + } catch (const fs::filesystem_error& ex) + { + LogPrintf("Error removing wallet locked file %s.\n", ex.what()); + }; + }; + + smsgBuckets.erase(it); + } else + if (it->second.nLockCount > 0) // -- tick down nLockCount, so will eventually expire if peer never sends data + { + it->second.nLockCount--; + + if (it->second.nLockCount == 0) // lock timed out + { + NodeId nPeerId = it->second.nLockPeerId; + int64_t ignoreUntil = GetTime() + SMSG_TIME_IGNORE; + + if (fDebugSmsg) + LogPrintf("Lock on bucket %d for peer %d timed out.\n", it->first, nPeerId); + + // -- look through the nodes for the peer that locked this bucket + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + if (pnode->id != nPeerId) + continue; + pnode->smsgData.ignoreUntil = ignoreUntil; + + // -- alert peer that they are being ignored + std::vector vchData; + vchData.resize(8); + memcpy(&vchData[0], &ignoreUntil, 8); + pnode->PushMessage("smsgIgnore", vchData); + + if (fDebugSmsg) + LogPrintf("This node will ignore peer %d until %d.\n", nPeerId, ignoreUntil); + break; + }; + it->second.nLockPeerId = 0; + }; // if (it->second.nLockCount == 0) + }; // ! if (it->first < cutoffTime) + }; + }; // LOCK(cs_smsg); + + MilliSleep(SMSG_THREAD_DELAY * 1000); // // check every SMSG_THREAD_DELAY seconds + }; +}; + +void ThreadSecureMsgPow() +{ + // -- proof of work thread + + int rv; + std::vector vchKey; + SecMsgStored smsgStored; + + std::string sPrefix("qm"); + uint8_t chKey[18]; + + + while (fSecMsgEnabled) + { + // -- sleep at end, then fSecMsgEnabled is tested on wake + + SecMsgDB dbOutbox; + leveldb::Iterator* it; + { + LOCK(cs_smsgDB); + + if (!dbOutbox.Open("cr+")) + continue; + + // -- fifo (smallest key first) + it = dbOutbox.pdb->NewIterator(leveldb::ReadOptions()); + } + // -- break up lock, SecureMsgSetHash will take long + + for (;;) + { + { + LOCK(cs_smsgDB); + if (!dbOutbox.NextSmesg(it, sPrefix, chKey, smsgStored)) + break; + } + + uint8_t* pHeader = &smsgStored.vchMessage[0]; + uint8_t* pPayload = &smsgStored.vchMessage[SMSG_HDR_LEN]; + SecureMessage* psmsg = (SecureMessage*) pHeader; + + // -- do proof of work + rv = SecureMsgSetHash(pHeader, pPayload, psmsg->nPayload); + if (rv == 2) + break; // leave message in db, if terminated due to shutdown + + // -- message is removed here, no matter what + { + LOCK(cs_smsgDB); + dbOutbox.EraseSmesg(chKey); + } + if (rv != 0) + { + LogPrintf("SecMsgPow: Could not get proof of work hash, message removed.\n"); + continue; + }; + + // -- add to message store + { + LOCK(cs_smsg); + if (SecureMsgStore(pHeader, pPayload, psmsg->nPayload, true) != 0) + { + LogPrintf("SecMsgPow: Could not place message in buckets, message removed.\n"); + continue; + }; + } + + // -- test if message was sent to self + if (SecureMsgScanMessage(pHeader, pPayload, psmsg->nPayload, true) != 0) + { + // message recipient is not this node (or failed) + }; + }; + + { + LOCK(cs_smsg); + delete it; + } + + // -- shutdown thread waits 5 seconds, this should be less + MilliSleep(2000); // seconds + }; +}; + +int SecureMsgBuildBucketSet() +{ + /* + Build the bucket set by scanning the files in the smsgStore dir. + + smsgBuckets should be empty + */ + + if (fDebugSmsg) + LogPrintf("SecureMsgBuildBucketSet()\n"); + + int64_t now = GetTime(); + uint32_t nFiles = 0; + uint32_t nMessages = 0; + + fs::path pathSmsgDir = GetDataDir() / "smsgStore"; + fs::directory_iterator itend; + + + if (!fs::exists(pathSmsgDir) + || !fs::is_directory(pathSmsgDir)) + { + LogPrintf("Message store directory does not exist.\n"); + return 0; // not an error + } + + + for (fs::directory_iterator itd(pathSmsgDir) ; itd != itend ; ++itd) + { + if (!fs::is_regular_file(itd->status())) + continue; + + std::string fileType = (*itd).path().extension().string(); + + if (fileType.compare(".dat") != 0) + continue; + + std::string fileName = (*itd).path().filename().string(); + + + if (fDebugSmsg) + LogPrintf("Processing file: %s.\n", fileName.c_str()); + + nFiles++; + + // TODO files must be split if > 2GB + // time_noFile.dat + size_t sep = fileName.find_first_of("_"); + if (sep == std::string::npos) + continue; + + std::string stime = fileName.substr(0, sep); + + int64_t fileTime = boost::lexical_cast(stime); + + if (fileTime < now - SMSG_RETENTION) + { + LogPrintf("Dropping file %s, expired.\n", fileName.c_str()); + try { + fs::remove((*itd).path()); + } catch (const fs::filesystem_error& ex) + { + LogPrintf("Error removing bucket file %s, %s.\n", fileName.c_str(), ex.what()); + }; + continue; + }; + + if (boost::algorithm::ends_with(fileName, "_wl.dat")) + { + if (fDebugSmsg) + LogPrintf("Skipping wallet locked file: %s.\n", fileName.c_str()); + continue; + }; + + size_t nTokenSetSize = 0; + SecureMessage smsg; + { + LOCK(cs_smsg); + + std::set& tokenSet = smsgBuckets[fileTime].setTokens; + + FILE *fp; + + if (!(fp = fopen((*itd).path().string().c_str(), "rb"))) + { + LogPrintf("Error opening file: %s\n", strerror(errno)); + continue; + }; + + for (;;) + { + long int ofs = ftell(fp); + SecMsgToken token; + token.offset = ofs; + errno = 0; + if (fread(&smsg.hash[0], sizeof(uint8_t), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN) + { + if (errno != 0) + { + LogPrintf("fread header failed: %s\n", strerror(errno)); + } else + { + //LogPrintf("End of file.\n"); + }; + break; + }; + token.timestamp = smsg.timestamp; + + if (smsg.nPayload < 8) + continue; + + if (fread(token.sample, sizeof(uint8_t), 8, fp) != 8) + { + LogPrintf("fread data failed: %s\n", strerror(errno)); + break; + }; + + if (fseek(fp, smsg.nPayload-8, SEEK_CUR) != 0) + { + LogPrintf("fseek, strerror: %s.\n", strerror(errno)); + break; + }; + + tokenSet.insert(token); + }; + + fclose(fp); + + smsgBuckets[fileTime].hashBucket(); + + nTokenSetSize = tokenSet.size(); + } // LOCK(cs_smsg); + + nMessages += nTokenSetSize; + if (fDebugSmsg) + LogPrintf("Bucket %d contains %u messages.\n", fileTime, nTokenSetSize); + }; + + LogPrintf("Processed %u files, loaded %u buckets containing %u messages.\n", nFiles, smsgBuckets.size(), nMessages); + + return 0; +}; + +int SecureMsgAddWalletAddresses() +{ + if (fDebugSmsg) + LogPrintf("SecureMsgAddWalletAddresses()\n"); + + std::string sAnonPrefix("ao "); + + uint32_t nAdded = 0; + BOOST_FOREACH(const PAIRTYPE(CTxDestination, std::string)& entry, pwalletMain->mapAddressBook) + { + if (!IsMine(*pwalletMain, entry.first)) + continue; + + // -- skip addresses for anon outputs + if (entry.second.compare(0, sAnonPrefix.length(), sAnonPrefix) == 0) + continue; + + // TODO: skip addresses for stealth transactions + + CBitcoinAddress coinAddress(entry.first); + if (!coinAddress.IsValid()) + continue; + + std::string address; + std::string strPublicKey; + address = coinAddress.ToString(); + + bool fExists = 0; + for (std::vector::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it) + { + if (address != it->sAddress) + continue; + fExists = 1; + break; + }; + + if (fExists) + continue; + + bool recvEnabled = 1; + bool recvAnon = 1; + + smsgAddresses.push_back(SecMsgAddress(address, recvEnabled, recvAnon)); + nAdded++; + }; + + if (fDebugSmsg) + LogPrintf("Added %u addresses to whitelist.\n", nAdded); + + return 0; +}; + + +int SecureMsgReadIni() +{ + if (!fSecMsgEnabled) + return false; + + if (fDebugSmsg) + LogPrintf("SecureMsgReadIni()\n"); + + fs::path fullpath = GetDataDir() / "smsg.ini"; + + + FILE *fp; + errno = 0; + if (!(fp = fopen(fullpath.string().c_str(), "r"))) + { + LogPrintf("Error opening file: %s\n", strerror(errno)); + return 1; + }; + + char cLine[512]; + char *pName, *pValue; + + char cAddress[64]; + int addrRecv, addrRecvAnon; + + while (fgets(cLine, 512, fp)) + { + cLine[strcspn(cLine, "\n")] = '\0'; + cLine[strcspn(cLine, "\r")] = '\0'; + cLine[511] = '\0'; // for safety + + // -- check that line contains a name value pair and is not a comment, or section header + if (cLine[0] == '#' || cLine[0] == '[' || strcspn(cLine, "=") < 1) + continue; + + if (!(pName = strtok(cLine, "=")) + || !(pValue = strtok(NULL, "="))) + continue; + + if (strcmp(pName, "newAddressRecv") == 0) + { + smsgOptions.fNewAddressRecv = (strcmp(pValue, "true") == 0) ? true : false; + } else + if (strcmp(pName, "newAddressAnon") == 0) + { + smsgOptions.fNewAddressAnon = (strcmp(pValue, "true") == 0) ? true : false; + } else + if (strcmp(pName, "key") == 0) + { + int rv = sscanf(pValue, "%64[^|]|%d|%d", cAddress, &addrRecv, &addrRecvAnon); + if (rv == 3) + { + smsgAddresses.push_back(SecMsgAddress(std::string(cAddress), addrRecv, addrRecvAnon)); + } else + { + LogPrintf("Could not parse key line %s, rv %d.\n", pValue, rv); + } + } else + { + LogPrintf("Unknown setting name: '%s'.", pName); + }; + }; + + LogPrintf("Loaded %u addresses.\n", smsgAddresses.size()); + + fclose(fp); + + return 0; +}; + +int SecureMsgWriteIni() +{ + if (!fSecMsgEnabled) + return false; + + if (fDebugSmsg) + LogPrintf("SecureMsgWriteIni()\n"); + + fs::path fullpath = GetDataDir() / "smsg.ini~"; + + FILE *fp; + errno = 0; + if (!(fp = fopen(fullpath.string().c_str(), "w"))) + { + LogPrintf("Error opening file: %s\n", strerror(errno)); + return 1; + }; + + if (fwrite("[Options]\n", sizeof(char), 10, fp) != 10) + { + LogPrintf("fwrite error: %s\n", strerror(errno)); + fclose(fp); + return false; + }; + + if (fprintf(fp, "newAddressRecv=%s\n", smsgOptions.fNewAddressRecv ? "true" : "false") < 0 + || fprintf(fp, "newAddressAnon=%s\n", smsgOptions.fNewAddressAnon ? "true" : "false") < 0) + { + LogPrintf("fprintf error: %s\n", strerror(errno)); + fclose(fp); + return false; + } + + if (fwrite("\n[Keys]\n", sizeof(char), 8, fp) != 8) + { + LogPrintf("fwrite error: %s\n", strerror(errno)); + fclose(fp); + return false; + }; + for (std::vector::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it) + { + errno = 0; + if (fprintf(fp, "key=%s|%d|%d\n", it->sAddress.c_str(), it->fReceiveEnabled, it->fReceiveAnon) < 0) + { + LogPrintf("fprintf error: %s\n", strerror(errno)); + continue; + }; + }; + + + fclose(fp); + + + try { + fs::path finalpath = GetDataDir() / "smsg.ini"; + fs::rename(fullpath, finalpath); + } catch (const fs::filesystem_error& ex) + { + LogPrintf("Error renaming file %s, %s.\n", fullpath.string().c_str(), ex.what()); + }; + return 0; +}; + + +/** called from AppInit2() in init.cpp */ +bool SecureMsgStart(bool fDontStart, bool fScanChain) +{ + if (fDontStart) + { + LogPrintf("Secure messaging not started.\n"); + return false; + }; + + LogPrintf("Secure messaging starting.\n"); + + fSecMsgEnabled = true; + + if (SecureMsgReadIni() != 0) + LogPrintf("Failed to read smsg.ini\n"); + + if (smsgAddresses.size() < 1) + { + LogPrintf("No address keys loaded.\n"); + if (SecureMsgAddWalletAddresses() != 0) + LogPrintf("Failed to load addresses from wallet.\n"); + }; + + if (fScanChain) + { + SecureMsgScanBlockChain(); + }; + + if (SecureMsgBuildBucketSet() != 0) + { + LogPrintf("SecureMsg could not load bucket sets, secure messaging disabled.\n"); + fSecMsgEnabled = false; + return false; + }; + + threadGroupSmsg.create_thread(boost::bind(&TraceThread, "smsg", &ThreadSecureMsg)); + threadGroupSmsg.create_thread(boost::bind(&TraceThread, "smsg-pow", &ThreadSecureMsgPow)); + + /* + // -- start threads + if (!NewThread(ThreadSecureMsg, NULL) + || !NewThread(ThreadSecureMsgPow, NULL)) + { + LogPrintf("SecureMsg could not start threads, secure messaging disabled.\n"); + fSecMsgEnabled = false; + return false; + }; + */ + return true; +}; + +bool SecureMsgShutdown() +{ + if (!fSecMsgEnabled) + return false; + + LogPrintf("Stopping secure messaging.\n"); + + + if (SecureMsgWriteIni() != 0) + LogPrintf("Failed to save smsg.ini\n"); + + fSecMsgEnabled = false; + + threadGroupSmsg.interrupt_all(); + threadGroupSmsg.join_all(); + + if (smsgDB) + { + LOCK(cs_smsgDB); + delete smsgDB; + smsgDB = NULL; + }; + + return true; +}; + +bool SecureMsgEnable() +{ + // -- start secure messaging at runtime + if (fSecMsgEnabled) + { + LogPrintf("SecureMsgEnable: secure messaging is already enabled.\n"); + return false; + }; + + { + LOCK(cs_smsg); + fSecMsgEnabled = true; + + smsgAddresses.clear(); // should be empty already + if (SecureMsgReadIni() != 0) + LogPrintf("Failed to read smsg.ini\n"); + + if (smsgAddresses.size() < 1) + { + LogPrintf("No address keys loaded.\n"); + if (SecureMsgAddWalletAddresses() != 0) + LogPrintf("Failed to load addresses from wallet.\n"); + }; + + smsgBuckets.clear(); // should be empty already + + if (SecureMsgBuildBucketSet() != 0) + { + LogPrintf("SecureMsgEnable: could not load bucket sets, secure messaging disabled.\n"); + fSecMsgEnabled = false; + return false; + }; + + }; // LOCK(cs_smsg); + + // -- start threads + threadGroupSmsg.create_thread(boost::bind(&TraceThread, "smsg", &ThreadSecureMsg)); + threadGroupSmsg.create_thread(boost::bind(&TraceThread, "smsg-pow", &ThreadSecureMsgPow)); + /* + if (!NewThread(ThreadSecureMsg, NULL) + || !NewThread(ThreadSecureMsgPow, NULL)) + { + LogPrintf("SecureMsgEnable could not start threads, secure messaging disabled.\n"); + fSecMsgEnabled = false; + return false; + }; + */ + // -- ping each peer, don't know which have messaging enabled + { + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + pnode->PushMessage("smsgPing"); + pnode->PushMessage("smsgPong"); // Send pong as have missed initial ping sent by peer when it connected + }; + } + + LogPrintf("Secure messaging enabled.\n"); + return true; +}; + +bool SecureMsgDisable() +{ + // -- stop secure messaging at runtime + if (!fSecMsgEnabled) + { + LogPrintf("SecureMsgDisable: secure messaging is already disabled.\n"); + return false; + }; + + { + LOCK(cs_smsg); + fSecMsgEnabled = false; + + threadGroupSmsg.interrupt_all(); + threadGroupSmsg.join_all(); + + // -- clear smsgBuckets + std::map::iterator it; + it = smsgBuckets.begin(); + for (it = smsgBuckets.begin(); it != smsgBuckets.end(); ++it) + { + it->second.setTokens.clear(); + }; + smsgBuckets.clear(); + + // -- tell each smsg enabled peer that this node is disabling + { + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes) + { + if (!pnode->smsgData.fEnabled) + continue; + + pnode->PushMessage("smsgDisabled"); + pnode->smsgData.fEnabled = false; + }; + } + + if (SecureMsgWriteIni() != 0) + LogPrintf("Failed to save smsg.ini\n"); + + smsgAddresses.clear(); + + } // LOCK(cs_smsg); + + // -- allow time for threads to stop + MilliSleep(3000); // seconds + // TODO be certain that threads have stopped + + if (smsgDB) + { + LOCK(cs_smsgDB); + delete smsgDB; + smsgDB = NULL; + }; + + + LogPrintf("Secure messaging disabled.\n"); + return true; +}; + + +bool SecureMsgReceiveData(CNode* pfrom, std::string strCommand, CDataStream& vRecv) +{ + /* + Called from ProcessMessage + Runs in ThreadMessageHandler2 + */ + + if (fDebugSmsg) + LogPrintf("SecureMsgReceiveData() %s %s.\n", pfrom->addrName.c_str(), strCommand.c_str()); + + { + + + + if (strCommand == "smsgInv") + { + std::vector vchData; + vRecv >> vchData; + + if (vchData.size() < 4) + { + pfrom->Misbehaving(1); + return false; // not enough data received to be a valid smsgInv + }; + + int64_t now = GetTime(); + + if (now < pfrom->smsgData.ignoreUntil) + { + if (fDebugSmsg) + LogPrintf("Node is ignoring peer %d until %d.\n", pfrom->id, pfrom->smsgData.ignoreUntil); + return false; + }; + + uint32_t nBuckets = smsgBuckets.size(); + uint32_t nLocked = 0; // no. of locked buckets on this node + uint32_t nInvBuckets; // no. of bucket headers sent by peer in smsgInv + memcpy(&nInvBuckets, &vchData[0], 4); + if (fDebugSmsg) + LogPrintf("Remote node sent %d bucket headers, this has %d.\n", nInvBuckets, nBuckets); + + + // -- Check no of buckets: + if (nInvBuckets > (SMSG_RETENTION / SMSG_BUCKET_LEN) + 1) // +1 for some leeway + { + LogPrintf("Peer sent more bucket headers than possible %u, %u.\n", nInvBuckets, (SMSG_RETENTION / SMSG_BUCKET_LEN)); + pfrom->Misbehaving(1); + return false; + }; + + if (vchData.size() < 4 + nInvBuckets*16) + { + LogPrintf("Remote node did not send enough data.\n"); + pfrom->Misbehaving(1); + return false; + }; + + std::vector vchDataOut; + vchDataOut.reserve(4 + 8 * nInvBuckets); // reserve max possible size + vchDataOut.resize(4); + uint32_t nShowBuckets = 0; + + + uint8_t *p = &vchData[4]; + for (uint32_t i = 0; i < nInvBuckets; ++i) + { + int64_t time; + uint32_t ncontent, hash; + memcpy(&time, p, 8); + memcpy(&ncontent, p+8, 4); + memcpy(&hash, p+12, 4); + + p += 16; + + // Check time valid: + if (time < now - SMSG_RETENTION) + { + if (fDebugSmsg) + LogPrintf("Not interested in peer bucket %d, has expired.\n", time); + + if (time < now - SMSG_RETENTION - SMSG_TIME_LEEWAY) + pfrom->Misbehaving(1); + continue; + }; + if (time > now + SMSG_TIME_LEEWAY) + { + if (fDebugSmsg) + LogPrintf("Not interested in peer bucket %d, in the future.\n", time); + pfrom->Misbehaving(1); + continue; + }; + + if (ncontent < 1) + { + if (fDebugSmsg) + LogPrintf("Peer sent empty bucket, ignore %d %u %u.\n", time, ncontent, hash); + continue; + }; + + if (fDebugSmsg) + { + LogPrintf("peer bucket %d %u %u.\n", time, ncontent, hash); + LogPrintf("this bucket %d %u %u.\n", time, smsgBuckets[time].setTokens.size(), smsgBuckets[time].hash); + }; + { + LOCK(cs_smsg); + if (smsgBuckets[time].nLockCount > 0) + { + if (fDebugSmsg) + LogPrintf("Bucket is locked %u, waiting for peer %u to send data.\n", smsgBuckets[time].nLockCount, smsgBuckets[time].nLockPeerId); + nLocked++; + continue; + }; + + // -- if this node has more than the peer node, peer node will pull from this + // if then peer node has more this node will pull fom peer + if (smsgBuckets[time].setTokens.size() < ncontent + || (smsgBuckets[time].setTokens.size() == ncontent + && smsgBuckets[time].hash != hash)) // if same amount in buckets check hash + { + if (fDebugSmsg) + LogPrintf("Requesting contents of bucket %d.\n", time); + + uint32_t sz = vchDataOut.size(); + vchDataOut.resize(sz + 8); + memcpy(&vchDataOut[sz], &time, 8); + + nShowBuckets++; + }; + } // LOCK(cs_smsg); + }; + + // TODO: should include hash? + memcpy(&vchDataOut[0], &nShowBuckets, 4); + if (vchDataOut.size() > 4) + { + pfrom->PushMessage("smsgShow", vchDataOut); + } else + if (nLocked < 1) // Don't report buckets as matched if any are locked + { + // -- peer has no buckets we want, don't send them again until something changes + // peer will still request buckets from this node if needed (< ncontent) + vchDataOut.resize(8); + memcpy(&vchDataOut[0], &now, 8); + pfrom->PushMessage("smsgMatch", vchDataOut); + if (fDebugSmsg) + LogPrintf("Sending smsgMatch, %d.\n", now); + }; + + } else + if (strCommand == "smsgShow") + { + std::vector vchData; + vRecv >> vchData; + + if (vchData.size() < 4) + return false; + + uint32_t nBuckets; + memcpy(&nBuckets, &vchData[0], 4); + + if (vchData.size() < 4 + nBuckets * 8) + return false; + + if (fDebugSmsg) + LogPrintf("smsgShow: peer wants to see content of %u buckets.\n", nBuckets); + + std::map::iterator itb; + std::set::iterator it; + + std::vector vchDataOut; + int64_t time; + uint8_t* pIn = &vchData[4]; + for (uint32_t i = 0; i < nBuckets; ++i, pIn += 8) + { + memcpy(&time, pIn, 8); + + { + LOCK(cs_smsg); + itb = smsgBuckets.find(time); + if (itb == smsgBuckets.end()) + { + if (fDebugSmsg) + LogPrintf("Don't have bucket %d.\n", time); + continue; + }; + + std::set& tokenSet = (*itb).second.setTokens; + + try { vchDataOut.resize(8 + 16 * tokenSet.size()); } catch (std::exception& e) + { + LogPrintf("vchDataOut.resize %u threw: %s.\n", 8 + 16 * tokenSet.size(), e.what()); + continue; + }; + memcpy(&vchDataOut[0], &time, 8); + + uint8_t* p = &vchDataOut[8]; + for (it = tokenSet.begin(); it != tokenSet.end(); ++it) + { + memcpy(p, &it->timestamp, 8); + memcpy(p+8, &it->sample, 8); + + p += 16; + }; + } + pfrom->PushMessage("smsgHave", vchDataOut); + }; + + + } else + if (strCommand == "smsgHave") + { + // -- peer has these messages in bucket + std::vector vchData; + vRecv >> vchData; + + if (vchData.size() < 8) + return false; + + int n = (vchData.size() - 8) / 16; + + int64_t time; + memcpy(&time, &vchData[0], 8); + + // -- Check time valid: + int64_t now = GetTime(); + if (time < now - SMSG_RETENTION) + { + if (fDebugSmsg) + LogPrintf("Not interested in peer bucket %d, has expired.\n", time); + return false; + }; + if (time > now + SMSG_TIME_LEEWAY) + { + if (fDebugSmsg) + LogPrintf("Not interested in peer bucket %d, in the future.\n", time); + pfrom->Misbehaving(1); + return false; + }; + + std::vector vchDataOut; + + { + LOCK(cs_smsg); + if (smsgBuckets[time].nLockCount > 0) + { + if (fDebugSmsg) + LogPrintf("Bucket %d lock count %u, waiting for message data from peer %u.\n", time, smsgBuckets[time].nLockCount, smsgBuckets[time].nLockPeerId); + return false; + }; + + if (fDebugSmsg) + LogPrintf("Sifting through bucket %d.\n", time); + + vchDataOut.resize(8); + memcpy(&vchDataOut[0], &vchData[0], 8); + + std::set& tokenSet = smsgBuckets[time].setTokens; + std::set::iterator it; + SecMsgToken token; + uint8_t* p = &vchData[8]; + + for (int i = 0; i < n; ++i) + { + memcpy(&token.timestamp, p, 8); + memcpy(&token.sample, p+8, 8); + + it = tokenSet.find(token); + if (it == tokenSet.end()) + { + int nd = vchDataOut.size(); + try { + vchDataOut.resize(nd + 16); + } catch (std::exception& e) { + LogPrintf("vchDataOut.resize %d threw: %s.\n", nd + 16, e.what()); + continue; + }; + + memcpy(&vchDataOut[nd], p, 16); + }; + + p += 16; + }; + } + + if (vchDataOut.size() > 8) + { + if (fDebugSmsg) + { + LogPrintf("Asking peer for %u messages.\n", (vchDataOut.size() - 8) / 16); + LogPrintf("Locking bucket %u for peer %d.\n", time, pfrom->id); + }; + { + LOCK(cs_smsg); + smsgBuckets[time].nLockCount = 3; // lock this bucket for at most 3 * SMSG_THREAD_DELAY seconds, unset when peer sends smsgMsg + smsgBuckets[time].nLockPeerId = pfrom->id; + } + pfrom->PushMessage("smsgWant", vchDataOut); + }; + } else + if (strCommand == "smsgWant") + { + std::vector vchData; + vRecv >> vchData; + + if (vchData.size() < 8) + return false; + + std::vector vchOne; + std::vector vchBunch; + + vchBunch.resize(4+8); // nmessages + bucketTime + + int n = (vchData.size() - 8) / 16; + + int64_t time; + uint32_t nBunch = 0; + memcpy(&time, &vchData[0], 8); + + + std::map::iterator itb; + + { + LOCK(cs_smsg); + itb = smsgBuckets.find(time); + if (itb == smsgBuckets.end()) + { + if (fDebugSmsg) + LogPrintf("Don't have bucket %d.\n", time); + return false; + }; + + std::set& tokenSet = itb->second.setTokens; + std::set::iterator it; + SecMsgToken token; + uint8_t* p = &vchData[8]; + for (int i = 0; i < n; ++i) + { + memcpy(&token.timestamp, p, 8); + memcpy(&token.sample, p+8, 8); + + it = tokenSet.find(token); + if (it == tokenSet.end()) + { + if (fDebugSmsg) + LogPrintf("Don't have wanted message %d.\n", token.timestamp); + } else + { + //LogPrintf("Have message at %d.\n", it->offset); // DEBUG + token.offset = it->offset; + //LogPrintf("winb before SecureMsgRetrieve %d.\n", token.timestamp); + + // -- place in vchOne so if SecureMsgRetrieve fails it won't corrupt vchBunch + if (SecureMsgRetrieve(token, vchOne) == 0) + { + nBunch++; + vchBunch.insert(vchBunch.end(), vchOne.begin(), vchOne.end()); // append + } else + { + LogPrintf("SecureMsgRetrieve failed %d.\n", token.timestamp); + }; + + if (nBunch >= 500 + || vchBunch.size() >= 96000) + { + if (fDebugSmsg) + LogPrintf("Break bunch %u, %u.\n", nBunch, vchBunch.size()); + break; // end here, peer will send more want messages if needed. + }; + }; + p += 16; + }; + } // LOCK(cs_smsg); + + if (nBunch > 0) + { + if (fDebugSmsg) + LogPrintf("Sending block of %u messages for bucket %d.\n", nBunch, time); + + memcpy(&vchBunch[0], &nBunch, 4); + memcpy(&vchBunch[4], &time, 8); + pfrom->PushMessage("smsgMsg", vchBunch); + }; + } else + if (strCommand == "smsgMsg") + { + std::vector vchData; + vRecv >> vchData; + + if (fDebugSmsg) + LogPrintf("smsgMsg vchData.size() %u.\n", vchData.size()); + + SecureMsgReceive(pfrom, vchData); + } else + if (strCommand == "smsgMatch") + { + std::vector vchData; + vRecv >> vchData; + + + if (vchData.size() < 8) + { + LogPrintf("smsgMatch, not enough data %u.\n", vchData.size()); + pfrom->Misbehaving(1); + return false; + }; + + int64_t time; + memcpy(&time, &vchData[0], 8); + + int64_t now = GetTime(); + if (time > now + SMSG_TIME_LEEWAY) + { + LogPrintf("Warning: Peer buckets matched in the future: %d.\nEither this node or the peer node has the incorrect time set.\n", time); + if (fDebugSmsg) + LogPrintf("Peer match time set to now.\n"); + time = now; + }; + + pfrom->smsgData.lastMatched = time; + + if (fDebugSmsg) + LogPrintf("Peer buckets matched at %d.\n", time); + + } else + if (strCommand == "smsgPing") + { + // -- smsgPing is the initial message, send reply + pfrom->PushMessage("smsgPong"); + } else + if (strCommand == "smsgPong") + { + if (fDebugSmsg) + LogPrintf("Peer replied, secure messaging enabled.\n"); + + pfrom->smsgData.fEnabled = true; + } else + if (strCommand == "smsgDisabled") + { + // -- peer has disabled secure messaging. + + pfrom->smsgData.fEnabled = false; + + if (fDebugSmsg) + LogPrintf("Peer %d has disabled secure messaging.\n", pfrom->id); + + } else + if (strCommand == "smsgIgnore") + { + // -- peer is reporting that it will ignore this node until time. + // Ignore peer too + std::vector vchData; + vRecv >> vchData; + + if (vchData.size() < 8) + { + LogPrintf("smsgIgnore, not enough data %u.\n", vchData.size()); + pfrom->Misbehaving(1); + return false; + }; + + int64_t time; + memcpy(&time, &vchData[0], 8); + + pfrom->smsgData.ignoreUntil = time; + + if (fDebugSmsg) + LogPrintf("Peer %d is ignoring this node until %d, ignore peer too.\n", pfrom->id, time); + } else + { + // Unknown message + }; + + }; // LOCK(cs_smsg); + + return true; +}; + +bool SecureMsgSendData(CNode* pto, bool fSendTrickle) +{ + /* + Called from ProcessMessage + Runs in ThreadMessageHandler2 + */ + + //LogPrintf("SecureMsgSendData() %s.\n", pto->addrName.c_str()); + + + int64_t now = GetTime(); + + if (pto->smsgData.lastSeen == 0) + { + // -- first contact + if (fDebugSmsg) + LogPrintf("SecureMsgSendData() new node %s, peer id %u.\n", pto->addrName.c_str(), pto->id); + // -- Send smsgPing once, do nothing until receive 1st smsgPong (then set fEnabled) + pto->PushMessage("smsgPing"); + pto->smsgData.lastSeen = GetTime(); + return true; + } else + if (!pto->smsgData.fEnabled + || now - pto->smsgData.lastSeen < SMSG_SEND_DELAY + || now < pto->smsgData.ignoreUntil) + { + return true; + }; + + // -- When nWakeCounter == 0, resend bucket inventory. + if (pto->smsgData.nWakeCounter < 1) + { + pto->smsgData.lastMatched = 0; + pto->smsgData.nWakeCounter = 10 + GetRandInt(300); // set to a random time between [10, 300] * SMSG_SEND_DELAY seconds + + if (fDebugSmsg) + LogPrintf("SecureMsgSendData(): nWakeCounter expired, sending bucket inventory to %s.\n" + "Now %d next wake counter %u\n", pto->addrName.c_str(), now, pto->smsgData.nWakeCounter); + }; + pto->smsgData.nWakeCounter--; + + { + LOCK(cs_smsg); + std::map::iterator it; + + uint32_t nBuckets = smsgBuckets.size(); + if (nBuckets > 0) // no need to send keep alive pkts, coin messages already do that + { + std::vector vchData; + // should reserve? + vchData.reserve(4 + nBuckets*16); // timestamp + size + hash + + uint32_t nBucketsShown = 0; + vchData.resize(4); + + uint8_t* p = &vchData[4]; + for (it = smsgBuckets.begin(); it != smsgBuckets.end(); ++it) + { + SecMsgBucket &bkt = it->second; + + uint32_t nMessages = bkt.setTokens.size(); + + if (bkt.timeChanged < pto->smsgData.lastMatched // peer has this bucket + || nMessages < 1) // this bucket is empty + continue; + + + uint32_t hash = bkt.hash; + + try { vchData.resize(vchData.size() + 16); } catch (std::exception& e) + { + LogPrintf("vchData.resize %u threw: %s.\n", vchData.size() + 16, e.what()); + continue; + }; + memcpy(p, &it->first, 8); + memcpy(p+8, &nMessages, 4); + memcpy(p+12, &hash, 4); + + p += 16; + nBucketsShown++; + //if (fDebug) + // LogPrintf("Sending bucket %d, size %d \n", it->first, it->second.size()); + }; + + if (vchData.size() > 4) + { + memcpy(&vchData[0], &nBucketsShown, 4); + if (fDebugSmsg) + LogPrintf("Sending %d bucket headers.\n", nBucketsShown); + + pto->PushMessage("smsgInv", vchData); + }; + }; + } + + pto->smsgData.lastSeen = GetTime(); + + return true; +}; + + +static int SecureMsgInsertAddress(CKeyID& hashKey, CPubKey& pubKey, SecMsgDB& addrpkdb) +{ + /* insert key hash and public key to addressdb + + should have LOCK(cs_smsg) where db is opened + + returns + 0 success + 1 error + 4 address is already in db + */ + + + if (addrpkdb.ExistsPK(hashKey)) + { + //LogPrintf("DB already contains public key for address.\n"); + CPubKey cpkCheck; + if (!addrpkdb.ReadPK(hashKey, cpkCheck)) + { + LogPrintf("addrpkdb.Read failed.\n"); + } else + { + if (cpkCheck != pubKey) + LogPrintf("DB already contains existing public key that does not match .\n"); + }; + return 4; + }; + + if (!addrpkdb.WritePK(hashKey, pubKey)) + { + LogPrintf("Write pair failed.\n"); + return 1; + }; + + return 0; +}; + +int SecureMsgInsertAddress(CKeyID& hashKey, CPubKey& pubKey) +{ + int rv; + { + LOCK(cs_smsgDB); + SecMsgDB addrpkdb; + + if (!addrpkdb.Open("cr+")) + return 1; + + rv = SecureMsgInsertAddress(hashKey, pubKey, addrpkdb); + } + return rv; +}; + + +static bool ScanBlock(CBlock& block, CTxDB& txdb, SecMsgDB& addrpkdb, + uint32_t& nTransactions, uint32_t& nElements, uint32_t& nPubkeys, uint32_t& nDuplicates) +{ + AssertLockHeld(cs_smsgDB); + + valtype vch; + opcodetype opcode; + + // -- only scan inputs of standard txns and coinstakes + + BOOST_FOREACH(CTransaction& tx, block.vtx) + { + std::string sReason; + // - harvest public keys from coinstake txns + if (tx.IsCoinStake()) + { + const CTxOut& txout = tx.vout[1]; + CScript::const_iterator pc = txout.scriptPubKey.begin(); + while (pc < txout.scriptPubKey.end()) + { + if (!txout.scriptPubKey.GetOp(pc, opcode, vch)) + break; + + if (vch.size() == 33) // pubkey + { + CPubKey pubKey(vch); + + if (!pubKey.IsValid() + || !pubKey.IsCompressed()) + { + LogPrintf("Public key is invalid %s.\n", HexStr(pubKey).c_str()); + continue; + }; + + CKeyID addrKey = pubKey.GetID(); + switch (SecureMsgInsertAddress(addrKey, pubKey, addrpkdb)) + { + case 0: nPubkeys++; break; // added key + case 4: nDuplicates++; break; // duplicate key + } + break; + }; + }; + nElements++; + } else + if (IsStandardTx(tx, sReason)) + { + for (uint32_t i = 0; i < tx.vin.size(); i++) + { + CScript *script = &tx.vin[i].scriptSig; + CScript::const_iterator pc = script->begin(); + CScript::const_iterator pend = script->end(); + + uint256 prevoutHash; + CKey key; + + while (pc < pend) + { + if (!script->GetOp(pc, opcode, vch)) + break; + // -- opcode is the length of the following data, compressed public key is always 33 + if (opcode == 33) + { + CPubKey pubKey(vch); + + if (!pubKey.IsValid() + || !pubKey.IsCompressed()) + { + LogPrintf("Public key is invalid %s.\n", HexStr(pubKey).c_str()); + continue; + }; + + CKeyID addrKey = pubKey.GetID(); + switch (SecureMsgInsertAddress(addrKey, pubKey, addrpkdb)) + { + case 0: nPubkeys++; break; // added key + case 4: nDuplicates++; break; // duplicate key + } + break; + }; + + //LogPrintf("opcode %d, %s, value %s.\n", opcode, GetOpName(opcode), ValueString(vch).c_str()); + }; + nElements++; + }; + }; + nTransactions++; + + if (nTransactions % 10000 == 0) // for ScanChainForPublicKeys + { + LogPrintf("Scanning transaction no. %u.\n", nTransactions); + }; + }; + return true; +}; + + +bool SecureMsgScanBlock(CBlock& block) +{ + /* + scan block for public key addresses + called from ProcessMessage() in main where strCommand == "block" + */ + + if (fDebugSmsg) + LogPrintf("SecureMsgScanBlock().\n"); + + uint32_t nTransactions = 0; + uint32_t nElements = 0; + uint32_t nPubkeys = 0; + uint32_t nDuplicates = 0; + + { + LOCK(cs_smsgDB); + CTxDB txdb("r"); + + SecMsgDB addrpkdb; + if (!addrpkdb.Open("cw") + || !addrpkdb.TxnBegin()) + return false; + + ScanBlock(block, txdb, addrpkdb, + nTransactions, nElements, nPubkeys, nDuplicates); + + addrpkdb.TxnCommit(); + } + + if (fDebugSmsg) + LogPrintf("Found %u transactions, %u elements, %u new public keys, %u duplicates.\n", nTransactions, nElements, nPubkeys, nDuplicates); + + return true; +}; + +bool ScanChainForPublicKeys(CBlockIndex* pindexStart) +{ + LogPrintf("Scanning block chain for public keys.\n"); + int64_t nStart = GetTimeMillis(); + + if (fDebugSmsg) + LogPrintf("From height %u.\n", pindexStart->nHeight); + + // -- public keys are in txin.scriptSig + // matching addresses are in scriptPubKey of txin's referenced output + + uint32_t nBlocks = 0; + uint32_t nTransactions = 0; + uint32_t nInputs = 0; + uint32_t nPubkeys = 0; + uint32_t nDuplicates = 0; + + { + LOCK(cs_smsgDB); + + CTxDB txdb("r"); + + SecMsgDB addrpkdb; + if (!addrpkdb.Open("cw") + || !addrpkdb.TxnBegin()) + return false; + + CBlockIndex* pindex = pindexStart; + while (pindex) + { + nBlocks++; + CBlock block; + block.ReadFromDisk(pindex, true); + + ScanBlock(block, txdb, addrpkdb, + nTransactions, nInputs, nPubkeys, nDuplicates); + + pindex = pindex->pnext; + }; + + addrpkdb.TxnCommit(); + }; + + LogPrintf("Scanned %u blocks, %u transactions, %u inputs\n", nBlocks, nTransactions, nInputs); + LogPrintf("Found %u public keys, %u duplicates.\n", nPubkeys, nDuplicates); + LogPrintf("Took %d ms\n", GetTimeMillis() - nStart); + + return true; +}; + +bool SecureMsgScanBlockChain() +{ + TRY_LOCK(cs_main, lockMain); + if (lockMain) + { + CBlockIndex *pindexScan = pindexGenesisBlock; + if (pindexScan == NULL) + { + LogPrintf("Error: pindexGenesisBlock not set.\n"); + return false; + }; + + + try { // -- in try to catch errors opening db, + if (!ScanChainForPublicKeys(pindexScan)) + return false; + } catch (std::exception& e) + { + LogPrintf("ScanChainForPublicKeys() threw: %s.\n", e.what()); + return false; + }; + } else + { + LogPrintf("ScanChainForPublicKeys() Could not lock main.\n"); + return false; + }; + + return true; +}; + +bool SecureMsgScanBuckets() +{ + if (fDebugSmsg) + LogPrintf("SecureMsgScanBuckets()\n"); + + if (!fSecMsgEnabled + || pwalletMain->IsLocked()) + return false; + + int64_t mStart = GetTimeMillis(); + int64_t now = GetTime(); + uint32_t nFiles = 0; + uint32_t nMessages = 0; + uint32_t nFoundMessages = 0; + + fs::path pathSmsgDir = GetDataDir() / "smsgStore"; + fs::directory_iterator itend; + + if (!fs::exists(pathSmsgDir) + || !fs::is_directory(pathSmsgDir)) + { + LogPrintf("Message store directory does not exist.\n"); + return 0; // not an error + }; + + SecureMessage smsg; + std::vector vchData; + + for (fs::directory_iterator itd(pathSmsgDir) ; itd != itend ; ++itd) + { + if (!fs::is_regular_file(itd->status())) + continue; + + std::string fileType = (*itd).path().extension().string(); + + if (fileType.compare(".dat") != 0) + continue; + + std::string fileName = (*itd).path().filename().string(); + + + if (fDebugSmsg) + LogPrintf("Processing file: %s.\n", fileName.c_str()); + + nFiles++; + + // TODO files must be split if > 2GB + // time_noFile.dat + size_t sep = fileName.find_first_of("_"); + if (sep == std::string::npos) + continue; + + std::string stime = fileName.substr(0, sep); + + int64_t fileTime = boost::lexical_cast(stime); + + if (fileTime < now - SMSG_RETENTION) + { + LogPrintf("Dropping file %s, expired.\n", fileName.c_str()); + try { + fs::remove((*itd).path()); + } catch (const fs::filesystem_error& ex) + { + LogPrintf("Error removing bucket file %s, %s.\n", fileName.c_str(), ex.what()); + }; + continue; + }; + + if (boost::algorithm::ends_with(fileName, "_wl.dat")) + { + if (fDebugSmsg) + LogPrintf("Skipping wallet locked file: %s.\n", fileName.c_str()); + continue; + }; + + { + LOCK(cs_smsg); + FILE *fp; + errno = 0; + if (!(fp = fopen((*itd).path().string().c_str(), "rb"))) + { + LogPrintf("Error opening file: %s\n", strerror(errno)); + continue; + }; + + for (;;) + { + errno = 0; + if (fread(&smsg.hash[0], sizeof(uint8_t), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN) + { + if (errno != 0) + { + LogPrintf("fread header failed: %s\n", strerror(errno)); + } else + { + //LogPrintf("End of file.\n"); + }; + break; + }; + + try { vchData.resize(smsg.nPayload); } catch (std::exception& e) + { + LogPrintf("SecureMsgWalletUnlocked(): Could not resize vchData, %u, %s\n", smsg.nPayload, e.what()); + fclose(fp); + return 1; + }; + + if (fread(&vchData[0], sizeof(uint8_t), smsg.nPayload, fp) != smsg.nPayload) + { + LogPrintf("fread data failed: %s\n", strerror(errno)); + break; + }; + + // -- don't report to gui, + int rv = SecureMsgScanMessage(&smsg.hash[0], &vchData[0], smsg.nPayload, false); + + if (rv == 0) + { + nFoundMessages++; + } else + if (rv != 0) + { + // SecureMsgScanMessage failed + }; + + nMessages ++; + }; + + fclose(fp); + + // -- remove wl file when scanned + try { + fs::remove((*itd).path()); + } catch (const boost::filesystem::filesystem_error& ex) + { + LogPrintf("Error removing wl file %s - %s\n", fileName.c_str(), ex.what()); + return 1; + }; + }; + }; + + LogPrintf("Processed %u files, scanned %u messages, received %u messages.\n", nFiles, nMessages, nFoundMessages); + LogPrintf("Took %d ms\n", GetTimeMillis() - mStart); + + return true; +} + + +int SecureMsgWalletUnlocked() +{ + /* + When the wallet is unlocked, scan messages received while wallet was locked. + */ + if (!fSecMsgEnabled) + return 0; + + LogPrintf("SecureMsgWalletUnlocked()\n"); + + if (pwalletMain->IsLocked()) + { + LogPrintf("Error: Wallet is locked.\n"); + return 1; + }; + + int64_t now = GetTime(); + uint32_t nFiles = 0; + uint32_t nMessages = 0; + uint32_t nFoundMessages = 0; + + fs::path pathSmsgDir = GetDataDir() / "smsgStore"; + fs::directory_iterator itend; + + if (!fs::exists(pathSmsgDir) + || !fs::is_directory(pathSmsgDir)) + { + LogPrintf("Message store directory does not exist.\n"); + return 0; // not an error + }; + + SecureMessage smsg; + std::vector vchData; + + for (fs::directory_iterator itd(pathSmsgDir) ; itd != itend ; ++itd) + { + if (!fs::is_regular_file(itd->status())) + continue; + + std::string fileName = (*itd).path().filename().string(); + + if (!boost::algorithm::ends_with(fileName, "_wl.dat")) + continue; + + if (fDebugSmsg) + LogPrintf("Processing file: %s.\n", fileName.c_str()); + + nFiles++; + + // TODO files must be split if > 2GB + // time_noFile_wl.dat + size_t sep = fileName.find_first_of("_"); + if (sep == std::string::npos) + continue; + + std::string stime = fileName.substr(0, sep); + + int64_t fileTime = boost::lexical_cast(stime); + + if (fileTime < now - SMSG_RETENTION) + { + LogPrintf("Dropping wallet locked file %s, expired.\n", fileName.c_str()); + try { + fs::remove((*itd).path()); + } catch (const boost::filesystem::filesystem_error& ex) + { + LogPrintf("Error removing wl file %s - %s\n", fileName.c_str(), ex.what()); + return 1; + }; + continue; + }; + + { + LOCK(cs_smsg); + FILE *fp; + errno = 0; + if (!(fp = fopen((*itd).path().string().c_str(), "rb"))) + { + LogPrintf("Error opening file: %s\n", strerror(errno)); + continue; + }; + + for (;;) + { + errno = 0; + if (fread(&smsg.hash[0], sizeof(uint8_t), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN) + { + if (errno != 0) + { + LogPrintf("fread header failed: %s\n", strerror(errno)); + } else + { + //LogPrintf("End of file.\n"); + }; + break; + }; + + try { vchData.resize(smsg.nPayload); } catch (std::exception& e) + { + LogPrintf("SecureMsgWalletUnlocked(): Could not resize vchData, %u, %s\n", smsg.nPayload, e.what()); + fclose(fp); + return 1; + }; + + if (fread(&vchData[0], sizeof(uint8_t), smsg.nPayload, fp) != smsg.nPayload) + { + LogPrintf("fread data failed: %s\n", strerror(errno)); + break; + }; + + // -- don't report to gui, + int rv = SecureMsgScanMessage(&smsg.hash[0], &vchData[0], smsg.nPayload, false); + + if (rv == 0) + { + nFoundMessages++; + } else + if (rv != 0) + { + // SecureMsgScanMessage failed + }; + + nMessages ++; + }; + + fclose(fp); + + // -- remove wl file when scanned + try { + fs::remove((*itd).path()); + } catch (const boost::filesystem::filesystem_error& ex) + { + LogPrintf("Error removing wl file %s - %s\n", fileName.c_str(), ex.what()); + return 1; + }; + }; + }; + + LogPrintf("Processed %u files, scanned %u messages, received %u messages.\n", nFiles, nMessages, nFoundMessages); + + // -- notify gui + NotifySecMsgWalletUnlocked(); + return 0; +}; + +int SecureMsgWalletKeyChanged(std::string sAddress, std::string sLabel, ChangeType mode) +{ + if (!fSecMsgEnabled) + return 0; + + LogPrintf("SecureMsgWalletKeyChanged()\n"); + + // TODO: default recv and recvAnon + + { + LOCK(cs_smsg); + + switch(mode) + { + case CT_NEW: + smsgAddresses.push_back(SecMsgAddress(sAddress, smsgOptions.fNewAddressRecv, smsgOptions.fNewAddressAnon)); + break; + case CT_DELETED: + for (std::vector::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it) + { + if (sAddress != it->sAddress) + continue; + smsgAddresses.erase(it); + break; + }; + break; + default: + break; + } + + }; // LOCK(cs_smsg); + + + return 0; +}; + +int SecureMsgScanMessage(uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload, bool reportToGui) +{ + /* + Check if message belongs to this node. + If so add to inbox db. + + if !reportToGui don't fire NotifySecMsgInboxChanged + - loads messages received when wallet locked in bulk. + + returns + 0 success, + 1 error + 2 no match + 3 wallet is locked - message stored for scanning later. + */ + + if (fDebugSmsg) + LogPrintf("SecureMsgScanMessage()\n"); + + if (pwalletMain->IsLocked()) + { + if (fDebugSmsg) + LogPrintf("ScanMessage: Wallet is locked, storing message to scan later.\n"); + + int rv; + if ((rv = SecureMsgStoreUnscanned(pHeader, pPayload, nPayload)) != 0) + return 1; + + return 3; + }; + + std::string addressTo; + MessageData msg; // placeholder + bool fOwnMessage = false; + + for (std::vector::iterator it = smsgAddresses.begin(); it != smsgAddresses.end(); ++it) + { + if (!it->fReceiveEnabled) + continue; + + CBitcoinAddress coinAddress(it->sAddress); + addressTo = coinAddress.ToString(); + + if (!it->fReceiveAnon) + { + // -- have to do full decrypt to see address from + if (SecureMsgDecrypt(false, addressTo, pHeader, pPayload, nPayload, msg) == 0) + { + if (fDebugSmsg) + LogPrintf("Decrypted message with %s.\n", addressTo.c_str()); + + if (msg.sFromAddress.compare("anon") != 0) + fOwnMessage = true; + break; + }; + } else + { + + if (SecureMsgDecrypt(true, addressTo, pHeader, pPayload, nPayload, msg) == 0) + { + if (fDebugSmsg) + LogPrintf("Decrypted message with %s.\n", addressTo.c_str()); + + fOwnMessage = true; + break; + }; + } + }; + + if (fOwnMessage) + { + // -- save to inbox + SecureMessage* psmsg = (SecureMessage*) pHeader; + std::string sPrefix("im"); + uint8_t chKey[18]; + memcpy(&chKey[0], sPrefix.data(), 2); + memcpy(&chKey[2], &psmsg->timestamp, 8); + memcpy(&chKey[10], pPayload, 8); + + SecMsgStored smsgInbox; + smsgInbox.timeReceived = GetTime(); + smsgInbox.status = (SMSG_MASK_UNREAD) & 0xFF; + smsgInbox.sAddrTo = addressTo; + + // -- data may not be contiguous + try { + smsgInbox.vchMessage.resize(SMSG_HDR_LEN + nPayload); + } catch (std::exception& e) { + LogPrintf("SecureMsgScanMessage(): Could not resize vchData, %u, %s\n", SMSG_HDR_LEN + nPayload, e.what()); + return 1; + }; + memcpy(&smsgInbox.vchMessage[0], pHeader, SMSG_HDR_LEN); + memcpy(&smsgInbox.vchMessage[SMSG_HDR_LEN], pPayload, nPayload); + + { + LOCK(cs_smsgDB); + SecMsgDB dbInbox; + + if (dbInbox.Open("cw")) + { + if (dbInbox.ExistsSmesg(chKey)) + { + if (fDebugSmsg) + LogPrintf("Message already exists in inbox db.\n"); + } else + { + dbInbox.WriteSmesg(chKey, smsgInbox); + + if (reportToGui) + NotifySecMsgInboxChanged(smsgInbox); + LogPrintf("SecureMsg saved to inbox, received with %s.\n", addressTo.c_str()); + }; + }; + } + }; + + return 0; +}; + +int SecureMsgGetLocalKey(CKeyID& ckid, CPubKey& cpkOut) +{ + if (fDebugSmsg) + LogPrintf("SecureMsgGetLocalKey()\n"); + + CKey key; + if (!pwalletMain->GetKey(ckid, key)) + return 4; + + cpkOut = key.GetPubKey(); //true); + + if (!cpkOut.IsValid() + || !cpkOut.IsCompressed()) + { + LogPrintf("Public key is invalid %s.\n", HexStr(cpkOut).c_str()); + return 1; + }; + + return 0; +}; + +int SecureMsgGetLocalPublicKey(std::string& strAddress, std::string& strPublicKey) +{ + /* returns + 0 success, + 1 error + 2 invalid address + 3 address does not refer to a key + 4 address not in wallet + */ + + CBitcoinAddress address; + if (!address.SetString(strAddress)) + return 2; // Invalid coin address + + CKeyID keyID; + if (!address.GetKeyID(keyID)) + return 3; + + int rv; + CPubKey pubKey; + if ((rv = SecureMsgGetLocalKey(keyID, pubKey)) != 0) + return rv; + + strPublicKey = EncodeBase58(pubKey.begin(), pubKey.end()); + + return 0; +}; + +int SecureMsgGetStoredKey(CKeyID& ckid, CPubKey& cpkOut) +{ + /* returns + 0 success, + 1 error + 2 public key not in database + */ + if (fDebugSmsg) + LogPrintf("SecureMsgGetStoredKey().\n"); + + { + LOCK(cs_smsgDB); + SecMsgDB addrpkdb; + + if (!addrpkdb.Open("r")) + return 1; + + if (!addrpkdb.ReadPK(ckid, cpkOut)) + { + //LogPrintf("addrpkdb.Read failed: %s.\n", coinAddress.ToString().c_str()); + return 2; + }; + } + + return 0; +}; + +int SecureMsgAddAddress(std::string& address, std::string& publicKey) +{ + static const char *fn = "SecureMsgAddAddress()"; + /* + Add address and matching public key to the database + address and publicKey are in base58 + + returns + 0 success + 1 error + 2 publicKey is invalid + 3 publicKey != address + 4 address is already in db + 5 address is invalid + */ + + CBitcoinAddress coinAddress(address); + + if (!coinAddress.IsValid()) + { + LogPrintf("%s - Address is not valid: %s.\n", fn, address.c_str()); + return 5; + }; + + CKeyID hashKey; + + if (!coinAddress.GetKeyID(hashKey)) + { + LogPrintf("%s - coinAddress.GetKeyID failed: %s.\n", fn, coinAddress.ToString().c_str()); + return 5; + }; + + std::vector vchTest; + DecodeBase58(publicKey, vchTest); + CPubKey pubKey(vchTest); + + // -- check that public key matches address hash + CPubKey pubKeyT(pubKey); + if (!pubKeyT.IsValid()) + { + LogPrintf("%s - Invalid PubKey.\n", fn); + return 2; + }; + + CKeyID keyIDT = pubKeyT.GetID(); + CBitcoinAddress addressT(keyIDT); + + if (addressT.ToString().compare(address) != 0) + { + LogPrintf("%s - Public key does not hash to address, addressT %s.\n", fn, addressT.ToString().c_str()); + return 3; + }; + + return SecureMsgInsertAddress(hashKey, pubKey); +}; + +int SecureMsgRetrieve(SecMsgToken &token, std::vector& vchData) +{ + if (fDebugSmsg) + LogPrintf("SecureMsgRetrieve() %d.\n", token.timestamp); + + // -- has cs_smsg lock from SecureMsgReceiveData + + fs::path pathSmsgDir = GetDataDir() / "smsgStore"; + + //LogPrintf("token.offset %d.\n", token.offset); // DEBUG + int64_t bucket = token.timestamp - (token.timestamp % SMSG_BUCKET_LEN); + std::string fileName = boost::lexical_cast(bucket) + "_01.dat"; + fs::path fullpath = pathSmsgDir / fileName; + + //LogPrintf("bucket %d.\n", bucket); + //LogPrintf("bucket d %d.\n", bucket); + //LogPrintf("fileName %s.\n", fileName.c_str()); + + FILE *fp; + errno = 0; + if (!(fp = fopen(fullpath.string().c_str(), "rb"))) + { + LogPrintf("Error opening file: %s\nPath %s\n", strerror(errno), fullpath.string().c_str()); + return 1; + }; + + errno = 0; + if (fseek(fp, token.offset, SEEK_SET) != 0) + { + LogPrintf("fseek, strerror: %s.\n", strerror(errno)); + fclose(fp); + return 1; + }; + + SecureMessage smsg; + errno = 0; + if (fread(&smsg.hash[0], sizeof(uint8_t), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN) + { + LogPrintf("fread header failed: %s\n", strerror(errno)); + fclose(fp); + return 1; + }; + + try { + vchData.resize(SMSG_HDR_LEN + smsg.nPayload); + } catch (std::exception& e) { + LogPrintf("SecureMsgRetrieve(): Could not resize vchData, %u, %s\n", SMSG_HDR_LEN + smsg.nPayload, e.what()); + return 1; + }; + + memcpy(&vchData[0], &smsg.hash[0], SMSG_HDR_LEN); + errno = 0; + if (fread(&vchData[SMSG_HDR_LEN], sizeof(uint8_t), smsg.nPayload, fp) != smsg.nPayload) + { + LogPrintf("fread data failed: %s. Wanted %u bytes.\n", strerror(errno), smsg.nPayload); + fclose(fp); + return 1; + }; + + + fclose(fp); + + return 0; +}; + +int SecureMsgReceive(CNode* pfrom, std::vector& vchData) +{ + if (fDebugSmsg) + LogPrintf("SecureMsgReceive().\n"); + + if (vchData.size() < 12) // nBunch4 + timestamp8 + { + LogPrintf("Error: not enough data.\n"); + return 1; + }; + + uint32_t nBunch; + int64_t bktTime; + + memcpy(&nBunch, &vchData[0], 4); + memcpy(&bktTime, &vchData[4], 8); + + + // -- check bktTime () + // bucket may not exist yet - will be created when messages are added + int64_t now = GetTime(); + if (bktTime > now + SMSG_TIME_LEEWAY) + { + if (fDebugSmsg) + LogPrintf("bktTime > now.\n"); + // misbehave? + return 1; + } else + if (bktTime < now - SMSG_RETENTION) + { + if (fDebugSmsg) + LogPrintf("bktTime < now - SMSG_RETENTION.\n"); + // misbehave? + return 1; + }; + + std::map::iterator itb; + + if (nBunch == 0 || nBunch > 500) + { + LogPrintf("Error: Invalid no. messages received in bunch %u, for bucket %d.\n", nBunch, bktTime); + pfrom->Misbehaving(1); + + { + LOCK(cs_smsg); + // -- release lock on bucket if it exists + itb = smsgBuckets.find(bktTime); + if (itb != smsgBuckets.end()) + itb->second.nLockCount = 0; + } // LOCK(cs_smsg); + return 1; + }; + + uint32_t n = 12; + + for (uint32_t i = 0; i < nBunch; ++i) + { + if (vchData.size() - n < SMSG_HDR_LEN) + { + LogPrintf("Error: not enough data sent, n = %u.\n", n); + break; + }; + + SecureMessage* psmsg = (SecureMessage*) &vchData[n]; + + int rv; + if ((rv = SecureMsgValidate(&vchData[n], &vchData[n + SMSG_HDR_LEN], psmsg->nPayload)) != 0) + { + // message dropped + if (rv == 2) // invalid proof of work + { + pfrom->Misbehaving(10); + } else + { + pfrom->Misbehaving(1); + }; + continue; + }; + + { + LOCK(cs_smsg); + // -- store message, but don't hash bucket + if (SecureMsgStore(&vchData[n], &vchData[n + SMSG_HDR_LEN], psmsg->nPayload, false) != 0) + { + // message dropped + break; // continue? + }; + + if (SecureMsgScanMessage(&vchData[n], &vchData[n + SMSG_HDR_LEN], psmsg->nPayload, true) != 0) + { + // message recipient is not this node (or failed) + }; + } // LOCK(cs_smsg); + + n += SMSG_HDR_LEN + psmsg->nPayload; + }; + + { + LOCK(cs_smsg); + // -- if messages have been added, bucket must exist now + itb = smsgBuckets.find(bktTime); + if (itb == smsgBuckets.end()) + { + if (fDebugSmsg) + LogPrintf("Don't have bucket %d.\n", bktTime); + return 1; + }; + + itb->second.nLockCount = 0; // this node has received data from peer, release lock + itb->second.nLockPeerId = 0; + itb->second.hashBucket(); + } // LOCK(cs_smsg); + return 0; +}; + +int SecureMsgStoreUnscanned(uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload) +{ + /* + When the wallet is locked a copy of each received message is stored to be scanned later if wallet is unlocked + */ + + if (fDebugSmsg) + LogPrintf("SecureMsgStoreUnscanned()\n"); + + if (!pHeader + || !pPayload) + { + LogPrintf("Error: null pointer to header or payload.\n"); + return 1; + }; + + SecureMessage* psmsg = (SecureMessage*) pHeader; + + fs::path pathSmsgDir; + try { + pathSmsgDir = GetDataDir() / "smsgStore"; + fs::create_directory(pathSmsgDir); + } catch (const boost::filesystem::filesystem_error& ex) + { + LogPrintf("Error: Failed to create directory %s - %s\n", pathSmsgDir.string().c_str(), ex.what()); + return 1; + }; + + int64_t now = GetTime(); + if (psmsg->timestamp > now + SMSG_TIME_LEEWAY) + { + LogPrintf("Message > now.\n"); + return 1; + } else + if (psmsg->timestamp < now - SMSG_RETENTION) + { + LogPrintf("Message < SMSG_RETENTION.\n"); + return 1; + }; + + int64_t bucket = psmsg->timestamp - (psmsg->timestamp % SMSG_BUCKET_LEN); + + std::string fileName = boost::lexical_cast(bucket) + "_01_wl.dat"; + fs::path fullpath = pathSmsgDir / fileName; + + FILE *fp; + errno = 0; + if (!(fp = fopen(fullpath.string().c_str(), "ab"))) + { + LogPrintf("Error opening file: %s\n", strerror(errno)); + return 1; + }; + + if (fwrite(pHeader, sizeof(uint8_t), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN + || fwrite(pPayload, sizeof(uint8_t), nPayload, fp) != nPayload) + { + LogPrintf("fwrite failed: %s\n", strerror(errno)); + fclose(fp); + return 1; + }; + + fclose(fp); + + return 0; +}; + + +int SecureMsgStore(uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload, bool fUpdateBucket) +{ + if (fDebugSmsg) + LogPrintf("SecureMsgStore()\n"); + + AssertLockHeld(cs_smsg); + + if (!pHeader + || !pPayload) + { + LogPrintf("Error: null pointer to header or payload.\n"); + return 1; + }; + + SecureMessage* psmsg = (SecureMessage*) pHeader; + + + long int ofs; + fs::path pathSmsgDir; + try { + pathSmsgDir = GetDataDir() / "smsgStore"; + fs::create_directory(pathSmsgDir); + } catch (const boost::filesystem::filesystem_error& ex) + { + LogPrintf("Error: Failed to create directory %s - %s\n", pathSmsgDir.string().c_str(), ex.what()); + return 1; + }; + + int64_t now = GetTime(); + if (psmsg->timestamp > now + SMSG_TIME_LEEWAY) + { + LogPrintf("Message > now.\n"); + return 1; + } else + if (psmsg->timestamp < now - SMSG_RETENTION) + { + LogPrintf("Message < SMSG_RETENTION.\n"); + return 1; + }; + + int64_t bucket = psmsg->timestamp - (psmsg->timestamp % SMSG_BUCKET_LEN); + + SecMsgToken token(psmsg->timestamp, pPayload, nPayload, 0); + + std::set& tokenSet = smsgBuckets[bucket].setTokens; + std::set::iterator it; + it = tokenSet.find(token); + if (it != tokenSet.end()) + { + LogPrintf("Already have message.\n"); + if (fDebugSmsg) + { + LogPrintf("nPayload: %u\n", nPayload); + LogPrintf("bucket: %d\n", bucket); + + LogPrintf("message ts: %d", token.timestamp); + std::vector vchShow; + vchShow.resize(8); + memcpy(&vchShow[0], token.sample, 8); + LogPrintf(" sample %s\n", ValueString(vchShow).c_str()); + /* + LogPrintf("\nmessages in bucket:\n"); + for (it = tokenSet.begin(); it != tokenSet.end(); ++it) + { + LogPrintf("message ts: %d", (*it).timestamp); + vchShow.resize(8); + memcpy(&vchShow[0], (*it).sample, 8); + LogPrintf(" sample %s\n", ValueString(vchShow).c_str()); + }; + */ + }; + return 1; + }; + + std::string fileName = boost::lexical_cast(bucket) + "_01.dat"; + fs::path fullpath = pathSmsgDir / fileName; + + FILE *fp; + errno = 0; + if (!(fp = fopen(fullpath.string().c_str(), "ab"))) + { + LogPrintf("Error opening file: %s\n", strerror(errno)); + return 1; + }; + + // -- on windows ftell will always return 0 after fopen(ab), call fseek to set. + errno = 0; + if (fseek(fp, 0, SEEK_END) != 0) + { + LogPrintf("Error fseek failed: %s\n", strerror(errno)); + return 1; + }; + + + ofs = ftell(fp); + + if (fwrite(pHeader, sizeof(uint8_t), SMSG_HDR_LEN, fp) != (size_t)SMSG_HDR_LEN + || fwrite(pPayload, sizeof(uint8_t), nPayload, fp) != nPayload) + { + LogPrintf("fwrite failed: %s\n", strerror(errno)); + fclose(fp); + return 1; + }; + + fclose(fp); + + token.offset = ofs; + + //LogPrintf("token.offset: %d\n", token.offset); // DEBUG + tokenSet.insert(token); + + if (fUpdateBucket) + smsgBuckets[bucket].hashBucket(); + + if (fDebugSmsg) + LogPrintf("SecureMsg added to bucket %d.\n", bucket); + return 0; +}; + +int SecureMsgStore(SecureMessage& smsg, bool fUpdateBucket) +{ + return SecureMsgStore(&smsg.hash[0], smsg.pPayload, smsg.nPayload, fUpdateBucket); +}; + +int SecureMsgValidate(uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload) +{ + /* + returns + 0 success + 1 error + 2 invalid hash + 3 checksum mismatch + 4 invalid version + 5 payload is too large + */ + SecureMessage* psmsg = (SecureMessage*) pHeader; + + if (psmsg->version[0] != 1) + return 4; + + if (nPayload > SMSG_MAX_MSG_WORST) + return 5; + + uint8_t civ[32]; + uint8_t sha256Hash[32]; + int rv = 2; // invalid + + uint32_t nonse; + memcpy(&nonse, &psmsg->nonse[0], 4); + + if (fDebugSmsg) + LogPrintf("SecureMsgValidate() nonse %u.\n", nonse); + + for (int i = 0; i < 32; i+=4) + memcpy(civ+i, &nonse, 4); + + HMAC_CTX ctx; + HMAC_CTX_init(&ctx); + + uint32_t nBytes; + if (!HMAC_Init_ex(&ctx, &civ[0], 32, EVP_sha256(), NULL) + || !HMAC_Update(&ctx, (uint8_t*) pHeader+4, SMSG_HDR_LEN-4) + || !HMAC_Update(&ctx, (uint8_t*) pPayload, nPayload) + || !HMAC_Update(&ctx, pPayload, nPayload) + || !HMAC_Final(&ctx, sha256Hash, &nBytes) + || nBytes != 32) + { + if (fDebugSmsg) + LogPrintf("HMAC error.\n"); + rv = 1; // error + } else + { + if (sha256Hash[31] == 0 + && sha256Hash[30] == 0 + && (~(sha256Hash[29]) & ((1<<0) || (1<<1) || (1<<2)) )) + { + if (fDebugSmsg) + LogPrintf("Hash Valid.\n"); + rv = 0; // smsg is valid + }; + + if (memcmp(psmsg->hash, sha256Hash, 4) != 0) + { + if (fDebugSmsg) + LogPrintf("Checksum mismatch.\n"); + rv = 3; // checksum mismatch + } + } + HMAC_CTX_cleanup(&ctx); + + return rv; +}; + +int SecureMsgSetHash(uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload) +{ + /* proof of work and checksum + + May run in a thread, if shutdown detected, return. + + returns: + 0 success + 1 error + 2 stopped due to node shutdown + + */ + + SecureMessage* psmsg = (SecureMessage*) pHeader; + + int64_t nStart = GetTimeMillis(); + uint8_t civ[32]; + uint8_t sha256Hash[32]; + + bool found = false; + HMAC_CTX ctx; + HMAC_CTX_init(&ctx); + + uint32_t nonse = 0; + + //CBigNum bnTarget(2); + //bnTarget = bnTarget.pow(256 - 40); + + // -- break for HMAC_CTX_cleanup + for (;;) + { + if (!fSecMsgEnabled) + break; + + //psmsg->timestamp = GetTime(); + //memcpy(&psmsg->timestamp, &now, 8); + memcpy(&psmsg->nonse[0], &nonse, 4); + + for (int i = 0; i < 32; i+=4) + memcpy(civ+i, &nonse, 4); + + uint32_t nBytes; + if (!HMAC_Init_ex(&ctx, &civ[0], 32, EVP_sha256(), NULL) + || !HMAC_Update(&ctx, (uint8_t*) pHeader+4, SMSG_HDR_LEN-4) + || !HMAC_Update(&ctx, (uint8_t*) pPayload, nPayload) + || !HMAC_Update(&ctx, pPayload, nPayload) + || !HMAC_Final(&ctx, sha256Hash, &nBytes) + //|| !HMAC_Final(&ctx, &vchHash[0], &nBytes) + || nBytes != 32) + break; + + /* + if (CBigNum(vchHash) <= bnTarget) + { + found = true; + if (fDebugSmsg) + LogPrintf("Match %u\n", nonse); + break; + }; + */ + + if (sha256Hash[31] == 0 + && sha256Hash[30] == 0 + && (~(sha256Hash[29]) & ((1<<0) || (1<<1) || (1<<2)) )) + // && sha256Hash[29] == 0) + { + found = true; + //if (fDebugSmsg) + // LogPrintf("Match %u\n", nonse); + break; + } + + //if (nonse >= UINT32_MAX) + if (nonse >= 4294967295U) + { + if (fDebugSmsg) + LogPrintf("No match %u\n", nonse); + break; + //return 1; + } + nonse++; + }; + + HMAC_CTX_cleanup(&ctx); + + if (!fSecMsgEnabled) + { + if (fDebugSmsg) + LogPrintf("SecureMsgSetHash() stopped, shutdown detected.\n"); + return 2; + }; + + if (!found) + { + if (fDebugSmsg) + LogPrintf("SecureMsgSetHash() failed, took %d ms, nonse %u\n", GetTimeMillis() - nStart, nonse); + return 1; + }; + + memcpy(psmsg->hash, sha256Hash, 4); + //memcpy(psmsg->hash, &vchHash[0], 4); + + if (fDebugSmsg) + LogPrintf("SecureMsgSetHash() took %d ms, nonse %u\n", GetTimeMillis() - nStart, nonse); + + return 0; +}; + +int SecureMsgEncrypt(SecureMessage& smsg, std::string& addressFrom, std::string& addressTo, std::string& message) +{ + /* Create a secure message + + Using similar method to bitmessage. + If bitmessage is secure this should be too. + https://bitmessage.org/wiki/Encryption + + Some differences: + bitmessage seems to use curve sect283r1 + *coin addresses use secp256k1 + + returns + 2 message is too long. + 3 addressFrom is invalid. + 4 addressTo is invalid. + 5 Could not get public key for addressTo. + 6 ECDH_compute_key failed + 7 Could not get private key for addressFrom. + 8 Could not allocate memory. + 9 Could not compress message data. + 10 Could not generate MAC. + 11 Encrypt failed. + */ + + if (fDebugSmsg) + LogPrintf("SecureMsgEncrypt(%s, %s, ...)\n", addressFrom.c_str(), addressTo.c_str()); + + + if (message.size() > SMSG_MAX_MSG_BYTES) + { + LogPrintf("Message is too long, %u.\n", message.size()); + return 2; + }; + + smsg.version[0] = 1; + smsg.version[1] = 1; + smsg.timestamp = GetTime(); + + + bool fSendAnonymous; + CBitcoinAddress coinAddrFrom; + CKeyID ckidFrom; + CKey keyFrom; + + if (addressFrom.compare("anon") == 0) + { + fSendAnonymous = true; + + } else + { + fSendAnonymous = false; + + if (!coinAddrFrom.SetString(addressFrom)) + { + LogPrintf("addressFrom is not valid.\n"); + return 3; + }; + + if (!coinAddrFrom.GetKeyID(ckidFrom)) + { + LogPrintf("coinAddrFrom.GetKeyID failed: %s.\n", coinAddrFrom.ToString().c_str()); + return 3; + }; + }; + + + CBitcoinAddress coinAddrDest; + CKeyID ckidDest; + + if (!coinAddrDest.SetString(addressTo)) + { + LogPrintf("addressTo is not valid.\n"); + return 4; + }; + + if (!coinAddrDest.GetKeyID(ckidDest)) + { + LogPrintf("coinAddrDest.GetKeyID failed: %s.\n", coinAddrDest.ToString().c_str()); + return 4; + }; + + // -- public key K is the destination address + CPubKey cpkDestK; + if (SecureMsgGetStoredKey(ckidDest, cpkDestK) != 0 + && SecureMsgGetLocalKey(ckidDest, cpkDestK) != 0) // maybe it's a local key (outbox?) + { + LogPrintf("Could not get public key for destination address.\n"); + return 5; + }; + + + // -- Generate 16 random bytes as IV. + RandAddSeedPerfmon(); + RAND_bytes(&smsg.iv[0], 16); + + + // -- Generate a new random EC key pair with private key called r and public key called R. + CKey keyR; + keyR.MakeNewKey(true); // make compressed key + + CECKey ecKeyR; + ecKeyR.SetSecretBytes(keyR.begin()); + + // -- Do an EC point multiply with public key K and private key r. This gives you public key P. + CECKey ecKeyK; + if (!ecKeyK.SetPubKey(cpkDestK)) + { + LogPrintf("Could not set pubkey for K: %s.\n", HexStr(cpkDestK).c_str()); + return 4; // address to is invalid + }; + + std::vector vchP; + vchP.resize(32); + EC_KEY* pkeyr = ecKeyR.GetECKey(); + EC_KEY* pkeyK = ecKeyK.GetECKey(); + + // always seems to be 32, worth checking? + //int field_size = EC_GROUP_get_degree(EC_KEY_get0_group(pkeyr)); + //int secret_len = (field_size+7)/8; + //LogPrintf("secret_len %d.\n", secret_len); + + // -- ECDH_compute_key returns the same P if fed compressed or uncompressed public keys + ECDH_set_method(pkeyr, ECDH_OpenSSL()); + int lenP = ECDH_compute_key(&vchP[0], 32, EC_KEY_get0_public_key(pkeyK), pkeyr, NULL); + + if (lenP != 32) + { + LogPrintf("ECDH_compute_key failed, lenP: %d.\n", lenP); + return 6; + }; + + CPubKey cpkR = keyR.GetPubKey(); + if (!cpkR.IsValid() + || !cpkR.IsCompressed()) + { + LogPrintf("Could not get public key for key R.\n"); + return 1; + }; + + memcpy(smsg.cpkR, cpkR.begin(), 33); + + + // -- Use public key P and calculate the SHA512 hash H. + // The first 32 bytes of H are called key_e and the last 32 bytes are called key_m. + std::vector vchHashed; + vchHashed.resize(64); // 512 + SHA512(&vchP[0], vchP.size(), (uint8_t*)&vchHashed[0]); + std::vector key_e(&vchHashed[0], &vchHashed[0]+32); + std::vector key_m(&vchHashed[32], &vchHashed[32]+32); + + + std::vector vchPayload; + std::vector vchCompressed; + uint8_t* pMsgData; + uint32_t lenMsgData; + + uint32_t lenMsg = message.size(); + if (lenMsg > 128) + { + // -- only compress if over 128 bytes + int worstCase = LZ4_compressBound(message.size()); + try { + vchCompressed.resize(worstCase); + } catch (std::exception& e) { + LogPrintf("vchCompressed.resize %u threw: %s.\n", worstCase, e.what()); + return 8; + }; + + int lenComp = LZ4_compress((char*)message.c_str(), (char*)&vchCompressed[0], lenMsg); + if (lenComp < 1) + { + LogPrintf("Could not compress message data.\n"); + return 9; + }; + + pMsgData = &vchCompressed[0]; + lenMsgData = lenComp; + + } else + { + // -- no compression + pMsgData = (uint8_t*)message.c_str(); + lenMsgData = lenMsg; + }; + + if (fSendAnonymous) + { + try { + vchPayload.resize(9 + lenMsgData); + } catch (std::exception& e) { + LogPrintf("vchPayload.resize %u threw: %s.\n", 9 + lenMsgData, e.what()); + return 8; + }; + + memcpy(&vchPayload[9], pMsgData, lenMsgData); + + vchPayload[0] = 250; // id as anonymous message + // -- next 4 bytes are unused - there to ensure encrypted payload always > 8 bytes + memcpy(&vchPayload[5], &lenMsg, 4); // length of uncompressed plain text + } else + { + try { + vchPayload.resize(SMSG_PL_HDR_LEN + lenMsgData); + } catch (std::exception& e) { + LogPrintf("vchPayload.resize %u threw: %s.\n", SMSG_PL_HDR_LEN + lenMsgData, e.what()); + return 8; + }; + + memcpy(&vchPayload[SMSG_PL_HDR_LEN], pMsgData, lenMsgData); + // -- compact signature proves ownership of from address and allows the public key to be recovered, recipient can always reply. + if (!pwalletMain->GetKey(ckidFrom, keyFrom)) + { + LogPrintf("Could not get private key for addressFrom.\n"); + return 7; + }; + + // -- sign the plaintext + std::vector vchSignature; + vchSignature.resize(65); + keyFrom.SignCompact(Hash(message.begin(), message.end()), vchSignature); + + // -- Save some bytes by sending address raw + vchPayload[0] = (static_cast(&coinAddrFrom))->getVersion(); // vchPayload[0] = coinAddrDest.nVersion; + memcpy(&vchPayload[1], (static_cast(&ckidFrom))->GetPPN(), 20); // memcpy(&vchPayload[1], ckidDest.pn, 20); + + memcpy(&vchPayload[1+20], &vchSignature[0], vchSignature.size()); + memcpy(&vchPayload[1+20+65], &lenMsg, 4); // length of uncompressed plain text + }; + + + SecMsgCrypter crypter; + crypter.SetKey(key_e, smsg.iv); + std::vector vchCiphertext; + + if (!crypter.Encrypt(&vchPayload[0], vchPayload.size(), vchCiphertext)) + { + LogPrintf("crypter.Encrypt failed.\n"); + return 11; + }; + + try { smsg.pPayload = new uint8_t[vchCiphertext.size()]; } catch (std::exception& e) + { + LogPrintf("Could not allocate pPayload, exception: %s.\n", e.what()); + return 8; + }; + + memcpy(smsg.pPayload, &vchCiphertext[0], vchCiphertext.size()); + smsg.nPayload = vchCiphertext.size(); + + + // -- Calculate a 32 byte MAC with HMACSHA256, using key_m as salt + // Message authentication code, (hash of timestamp + destination + payload) + bool fHmacOk = true; + uint32_t nBytes = 32; + HMAC_CTX ctx; + HMAC_CTX_init(&ctx); + + if (!HMAC_Init_ex(&ctx, &key_m[0], 32, EVP_sha256(), NULL) + || !HMAC_Update(&ctx, (uint8_t*) &smsg.timestamp, sizeof(smsg.timestamp)) + || !HMAC_Update(&ctx, &vchCiphertext[0], vchCiphertext.size()) + || !HMAC_Final(&ctx, smsg.mac, &nBytes) + || nBytes != 32) + fHmacOk = false; + + HMAC_CTX_cleanup(&ctx); + + if (!fHmacOk) + { + LogPrintf("Could not generate MAC.\n"); + return 10; + }; + + + return 0; +}; + +int SecureMsgSend(std::string& addressFrom, std::string& addressTo, std::string& message, std::string& sError) +{ + /* Encrypt secure message, and place it on the network + Make a copy of the message to sender's first address and place in send queue db + proof of work thread will pick up messages from send queue db + + */ + + if (fDebugSmsg) + LogPrintf("SecureMsgSend(%s, %s, ...)\n", addressFrom.c_str(), addressTo.c_str()); + + if (pwalletMain->IsLocked()) + { + sError = "Wallet is locked, wallet must be unlocked to send and recieve messages."; + LogPrintf("Wallet is locked, wallet must be unlocked to send and recieve messages.\n"); + return 1; + }; + + if (message.size() > SMSG_MAX_MSG_BYTES) + { + std::ostringstream oss; + oss << message.size() << " > " << SMSG_MAX_MSG_BYTES; + sError = "Message is too long, " + oss.str(); + LogPrintf("Message is too long, %u.\n", message.size()); + return 1; + }; + + + int rv; + SecureMessage smsg; + + if ((rv = SecureMsgEncrypt(smsg, addressFrom, addressTo, message)) != 0) + { + LogPrintf("SecureMsgSend(), encrypt for recipient failed.\n"); + + switch(rv) + { + case 2: sError = "Message is too long."; break; + case 3: sError = "Invalid addressFrom."; break; + case 4: sError = "Invalid addressTo."; break; + case 5: sError = "Could not get public key for addressTo."; break; + case 6: sError = "ECDH_compute_key failed."; break; + case 7: sError = "Could not get private key for addressFrom."; break; + case 8: sError = "Could not allocate memory."; break; + case 9: sError = "Could not compress message data."; break; + case 10: sError = "Could not generate MAC."; break; + case 11: sError = "Encrypt failed."; break; + default: sError = "Unspecified Error."; break; + }; + + return rv; + }; + + + // -- Place message in send queue, proof of work will happen in a thread. + std::string sPrefix("qm"); + uint8_t chKey[18]; + memcpy(&chKey[0], sPrefix.data(), 2); + memcpy(&chKey[2], &smsg.timestamp, 8); + memcpy(&chKey[10], &smsg.pPayload, 8); + + SecMsgStored smsgSQ; + + smsgSQ.timeReceived = GetTime(); + smsgSQ.sAddrTo = addressTo; + + try { + smsgSQ.vchMessage.resize(SMSG_HDR_LEN + smsg.nPayload); + } catch (std::exception& e) { + LogPrintf("smsgSQ.vchMessage.resize %u threw: %s.\n", SMSG_HDR_LEN + smsg.nPayload, e.what()); + sError = "Could not allocate memory."; + return 8; + }; + + memcpy(&smsgSQ.vchMessage[0], &smsg.hash[0], SMSG_HDR_LEN); + memcpy(&smsgSQ.vchMessage[SMSG_HDR_LEN], smsg.pPayload, smsg.nPayload); + + { + LOCK(cs_smsgDB); + SecMsgDB dbSendQueue; + if (dbSendQueue.Open("cw")) + { + dbSendQueue.WriteSmesg(chKey, smsgSQ); + //NotifySecMsgSendQueueChanged(smsgOutbox); + }; + } + + // TODO: only update outbox when proof of work thread is done. + + // -- for outbox create a copy encrypted for owned address + // if the wallet is encrypted private key needed to decrypt will be unavailable + + if (fDebugSmsg) + LogPrintf("Encrypting message for outbox.\n"); + + std::string addressOutbox = "None"; + CBitcoinAddress coinAddrOutbox; + + BOOST_FOREACH(const PAIRTYPE(CTxDestination, std::string)& entry, pwalletMain->mapAddressBook) + { + // -- get first owned address + if (!IsMine(*pwalletMain, entry.first)) + continue; + + const CBitcoinAddress& address = entry.first; + + addressOutbox = address.ToString(); + if (!coinAddrOutbox.SetString(addressOutbox)) // test valid + continue; + break; + }; + + if (addressOutbox == "None") + { + LogPrintf("Warning: SecureMsgSend() could not find an address to encrypt outbox message with.\n"); + } else + { + if (fDebugSmsg) + LogPrintf("Encrypting a copy for outbox, using address %s\n", addressOutbox.c_str()); + + SecureMessage smsgForOutbox; + if ((rv = SecureMsgEncrypt(smsgForOutbox, addressFrom, addressOutbox, message)) != 0) + { + LogPrintf("SecureMsgSend(), encrypt for outbox failed, %d.\n", rv); + } else + { + // -- save sent message to db + std::string sPrefix("sm"); + uint8_t chKey[18]; + memcpy(&chKey[0], sPrefix.data(), 2); + memcpy(&chKey[2], &smsgForOutbox.timestamp, 8); + memcpy(&chKey[10], &smsgForOutbox.pPayload, 8); // sample + + SecMsgStored smsgOutbox; + + smsgOutbox.timeReceived = GetTime(); + smsgOutbox.sAddrTo = addressTo; + smsgOutbox.sAddrOutbox = addressOutbox; + + try { + smsgOutbox.vchMessage.resize(SMSG_HDR_LEN + smsgForOutbox.nPayload); + } catch (std::exception& e) { + LogPrintf("smsgOutbox.vchMessage.resize %u threw: %s.\n", SMSG_HDR_LEN + smsgForOutbox.nPayload, e.what()); + sError = "Could not allocate memory."; + return 8; + }; + memcpy(&smsgOutbox.vchMessage[0], &smsgForOutbox.hash[0], SMSG_HDR_LEN); + memcpy(&smsgOutbox.vchMessage[SMSG_HDR_LEN], smsgForOutbox.pPayload, smsgForOutbox.nPayload); + + + { + LOCK(cs_smsgDB); + SecMsgDB dbSent; + + if (dbSent.Open("cw")) + { + dbSent.WriteSmesg(chKey, smsgOutbox); + NotifySecMsgOutboxChanged(smsgOutbox); + }; + } + }; + }; + + if (fDebugSmsg) + LogPrintf("Secure message queued for sending to %s.\n", addressTo.c_str()); + + return 0; +}; + + +int SecureMsgDecrypt(bool fTestOnly, std::string& address, uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload, MessageData& msg) +{ + /* Decrypt secure message + + address is the owned address to decrypt with. + + validate first in SecureMsgValidate + + returns + 1 Error + 2 Unknown version number + 3 Decrypt address is not valid. + 8 Could not allocate memory + */ + + if (fDebugSmsg) + LogPrintf("SecureMsgDecrypt(), using %s, testonly %d.\n", address.c_str(), fTestOnly); + + if (!pHeader + || !pPayload) + { + LogPrintf("Error: null pointer to header or payload.\n"); + return 1; + }; + + SecureMessage* psmsg = (SecureMessage*) pHeader; + + + if (psmsg->version[0] != 1) + { + LogPrintf("Unknown version number.\n"); + return 2; + }; + + + + // -- Fetch private key k, used to decrypt + CBitcoinAddress coinAddrDest; + CKeyID ckidDest; + CKey keyDest; + if (!coinAddrDest.SetString(address)) + { + LogPrintf("Address is not valid.\n"); + return 3; + }; + if (!coinAddrDest.GetKeyID(ckidDest)) + { + LogPrintf("coinAddrDest.GetKeyID failed: %s.\n", coinAddrDest.ToString().c_str()); + return 3; + }; + if (!pwalletMain->GetKey(ckidDest, keyDest)) + { + LogPrintf("Could not get private key for addressDest.\n"); + return 3; + }; + + + + CPubKey cpkR(psmsg->cpkR, psmsg->cpkR+33); + if (!cpkR.IsValid()) + { + LogPrintf("Could not get pubkey for key R.\n"); + return 1; + }; + + CECKey ecKeyR; + if (!ecKeyR.SetPubKey(cpkR)) + { + LogPrintf("Could not set pubkey for key R: %s.\n", HexStr(cpkR).c_str()); + return 1; + }; + + CECKey ecKeyDest; + ecKeyDest.SetSecretBytes(keyDest.begin()); + + // -- Do an EC point multiply with private key k and public key R. This gives you public key P. + std::vector vchP; + vchP.resize(32); + EC_KEY* pkeyk = ecKeyDest.GetECKey(); + EC_KEY* pkeyR = ecKeyR.GetECKey(); + + ECDH_set_method(pkeyk, ECDH_OpenSSL()); + int lenPdec = ECDH_compute_key(&vchP[0], 32, EC_KEY_get0_public_key(pkeyR), pkeyk, NULL); + + if (lenPdec != 32) + { + LogPrintf("ECDH_compute_key failed, lenPdec: %d.\n", lenPdec); + return 1; + }; + + + // -- Use public key P to calculate the SHA512 hash H. + // The first 32 bytes of H are called key_e and the last 32 bytes are called key_m. + std::vector vchHashedDec; + vchHashedDec.resize(64); // 512 bits + SHA512(&vchP[0], vchP.size(), (uint8_t*)&vchHashedDec[0]); + std::vector key_e(&vchHashedDec[0], &vchHashedDec[0]+32); + std::vector key_m(&vchHashedDec[32], &vchHashedDec[32]+32); + + + // -- Message authentication code, (hash of timestamp + destination + payload) + uint8_t MAC[32]; + bool fHmacOk = true; + uint32_t nBytes = 32; + HMAC_CTX ctx; + HMAC_CTX_init(&ctx); + + if (!HMAC_Init_ex(&ctx, &key_m[0], 32, EVP_sha256(), NULL) + || !HMAC_Update(&ctx, (uint8_t*) &psmsg->timestamp, sizeof(psmsg->timestamp)) + || !HMAC_Update(&ctx, pPayload, nPayload) + || !HMAC_Final(&ctx, MAC, &nBytes) + || nBytes != 32) + fHmacOk = false; + + HMAC_CTX_cleanup(&ctx); + + if (!fHmacOk) + { + LogPrintf("Could not generate MAC.\n"); + return 1; + }; + + if (memcmp(MAC, psmsg->mac, 32) != 0) + { + if (fDebugSmsg) + LogPrintf("MAC does not match.\n"); // expected if message is not to address on node + + return 1; + }; + + if (fTestOnly) + return 0; + + SecMsgCrypter crypter; + crypter.SetKey(key_e, psmsg->iv); + std::vector vchPayload; + if (!crypter.Decrypt(pPayload, nPayload, vchPayload)) + { + LogPrintf("Decrypt failed.\n"); + return 1; + }; + + msg.timestamp = psmsg->timestamp; + uint32_t lenData; + uint32_t lenPlain; + + uint8_t* pMsgData; + bool fFromAnonymous; + if ((uint32_t)vchPayload[0] == 250) + { + fFromAnonymous = true; + lenData = vchPayload.size() - (9); + memcpy(&lenPlain, &vchPayload[5], 4); + pMsgData = &vchPayload[9]; + } else + { + fFromAnonymous = false; + lenData = vchPayload.size() - (SMSG_PL_HDR_LEN); + memcpy(&lenPlain, &vchPayload[1+20+65], 4); + pMsgData = &vchPayload[SMSG_PL_HDR_LEN]; + }; + + try { + msg.vchMessage.resize(lenPlain + 1); + } catch (std::exception& e) { + LogPrintf("msg.vchMessage.resize %u threw: %s.\n", lenPlain + 1, e.what()); + return 8; + }; + + + if (lenPlain > 128) + { + // -- decompress + if (LZ4_decompress_safe((char*) pMsgData, (char*) &msg.vchMessage[0], lenData, lenPlain) != (int) lenPlain) + { + LogPrintf("Could not decompress message data.\n"); + return 1; + }; + } else + { + // -- plaintext + memcpy(&msg.vchMessage[0], pMsgData, lenPlain); + }; + + msg.vchMessage[lenPlain] = '\0'; + + if (fFromAnonymous) + { + // -- Anonymous sender + msg.sFromAddress = "anon"; + } else + { + std::vector vchUint160; + vchUint160.resize(20); + + memcpy(&vchUint160[0], &vchPayload[1], 20); + + uint160 ui160(vchUint160); + CKeyID ckidFrom(ui160); + + CBitcoinAddress coinAddrFrom; + coinAddrFrom.Set(ckidFrom); + if (!coinAddrFrom.IsValid()) + { + LogPrintf("From Addess is invalid.\n"); + return 1; + }; + + std::vector vchSig; + vchSig.resize(65); + + memcpy(&vchSig[0], &vchPayload[1+20], 65); + + CPubKey cpkFromSig; + cpkFromSig.RecoverCompact(Hash(msg.vchMessage.begin(), msg.vchMessage.end()-1), vchSig); + if (!cpkFromSig.IsValid()) + { + LogPrintf("Signature validation failed.\n"); + return 1; + }; + + // -- get address for the compressed public key + CBitcoinAddress coinAddrFromSig; + coinAddrFromSig.Set(cpkFromSig.GetID()); + + if (!(coinAddrFrom == coinAddrFromSig)) + { + LogPrintf("Signature validation failed.\n"); + return 1; + }; + + int rv = 5; + try { + rv = SecureMsgInsertAddress(ckidFrom, cpkFromSig); + } catch (std::exception& e) { + LogPrintf("SecureMsgInsertAddress(), exception: %s.\n", e.what()); + //return 1; + }; + + switch(rv) + { + case 0: + LogPrintf("Sender public key added to db.\n"); + break; + case 4: + LogPrintf("Sender public key already in db.\n"); + break; + default: + LogPrintf("Error adding sender public key to db.\n"); + break; + }; + + msg.sFromAddress = coinAddrFrom.ToString(); + }; + + if (fDebugSmsg) + LogPrintf("Decrypted message for %s.\n", address.c_str()); + + return 0; +}; + +int SecureMsgDecrypt(bool fTestOnly, std::string& address, SecureMessage& smsg, MessageData& msg) +{ + return SecureMsgDecrypt(fTestOnly, address, &smsg.hash[0], smsg.pPayload, smsg.nPayload, msg); +}; + diff --git a/src/smessage.h b/src/smessage.h new file mode 100644 index 0000000..3f141ea --- /dev/null +++ b/src/smessage.h @@ -0,0 +1,379 @@ +// Copyright (c) 2014 The ShadowCoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. +#ifndef SEC_MESSAGE_H +#define SEC_MESSAGE_H + +#include +#include + +#include "net.h" +#include "db.h" +#include "wallet.h" +#include "lz4/lz4.h" +#include "base58.h" + +const unsigned int SMSG_HDR_LEN = 104; // length of unencrypted header, 4 + 2 + 1 + 8 + 16 + 33 + 32 + 4 +4 +const unsigned int SMSG_PL_HDR_LEN = 1+20+65+4; // length of encrypted header in payload + +const unsigned int SMSG_BUCKET_LEN = 60 * 10; // in seconds +const unsigned int SMSG_RETENTION = 60 * 60 * 48; // in seconds +const unsigned int SMSG_SEND_DELAY = 2; // in seconds, SecureMsgSendData will delay this long between firing +const unsigned int SMSG_THREAD_DELAY = 20; + +const unsigned int SMSG_TIME_LEEWAY = 60; +const unsigned int SMSG_TIME_IGNORE = 90; // seconds that a peer is ignored for if they fail to deliver messages for a smsgWant + + +const unsigned int SMSG_MAX_MSG_BYTES = 4096; // the user input part + +// max size of payload worst case compression +const unsigned int SMSG_MAX_MSG_WORST = LZ4_COMPRESSBOUND(SMSG_MAX_MSG_BYTES+SMSG_PL_HDR_LEN); + + + +#define SMSG_MASK_UNREAD (1 << 0) + + + +extern bool fSecMsgEnabled; + +class SecMsgStored; + +// Inbox db changed, called with lock cs_smsgDB held. +extern boost::signals2::signal NotifySecMsgInboxChanged; + +// Outbox db changed, called with lock cs_smsgDB held. +extern boost::signals2::signal NotifySecMsgOutboxChanged; + +// Wallet Unlocked, called after all messages received while locked have been processed. +extern boost::signals2::signal NotifySecMsgWalletUnlocked; + + +class SecMsgBucket; +class SecMsgAddress; +class SecMsgOptions; + +extern std::map smsgBuckets; +extern std::vector smsgAddresses; +extern SecMsgOptions smsgOptions; + +extern CCriticalSection cs_smsg; // all except inbox and outbox +extern CCriticalSection cs_smsgDB; + + +#pragma pack(push, 1) +class SecureMessage +{ +public: + SecureMessage() + { + nPayload = 0; + pPayload = NULL; + }; + + ~SecureMessage() + { + if (pPayload) + delete[] pPayload; + pPayload = NULL; + }; + + uint8_t hash[4]; + uint8_t version[2]; + uint8_t flags; + int64_t timestamp; + uint8_t iv[16]; + uint8_t cpkR[33]; + uint8_t mac[32]; + uint8_t nonse[4]; + uint32_t nPayload; + uint8_t* pPayload; + +}; +#pragma pack(pop) + + +class MessageData +{ +// -- Decrypted SecureMessage data +public: + int64_t timestamp; + std::string sToAddress; + std::string sFromAddress; + std::vector vchMessage; // null terminated plaintext +}; + + +class SecMsgToken +{ +public: + SecMsgToken(int64_t ts, uint8_t* p, int np, long int o) + { + timestamp = ts; + + if (np < 8) // payload will always be > 8, just make sure + memset(sample, 0, 8); + else + memcpy(sample, p, 8); + offset = o; + }; + + SecMsgToken() {}; + + ~SecMsgToken() {}; + + bool operator <(const SecMsgToken& y) const + { + // pack and memcmp from timesent? + if (timestamp == y.timestamp) + return memcmp(sample, y.sample, 8) < 0; + return timestamp < y.timestamp; + } + + int64_t timestamp; // doesn't need to be full 64 bytes? + uint8_t sample[8]; // first 8 bytes of payload - a hash + int64_t offset; // offset + +}; + + +class SecMsgBucket +{ +public: + SecMsgBucket() + { + timeChanged = 0; + hash = 0; + nLockCount = 0; + nLockPeerId = 0; + }; + ~SecMsgBucket() {}; + + void hashBucket(); + + int64_t timeChanged; + uint32_t hash; // token set should get ordered the same on each node + uint32_t nLockCount; // set when smsgWant first sent, unset at end of smsgMsg, ticks down in ThreadSecureMsg() + NodeId nLockPeerId; // id of peer that bucket is locked for + std::set setTokens; + +}; + + +// -- get at the data +class CBitcoinAddress_B : public CBitcoinAddress +{ +public: + uint8_t getVersion() + { + // TODO: fix + if (vchVersion.size() > 0) + return vchVersion[0]; + return 0; + } +}; + +class CKeyID_B : public CKeyID +{ +public: + uint32_t* GetPPN() + { + return pn; + } +}; + + +class SecMsgAddress +{ +public: + SecMsgAddress() {}; + SecMsgAddress(std::string sAddr, bool receiveOn, bool receiveAnon) + { + sAddress = sAddr; + fReceiveEnabled = receiveOn; + fReceiveAnon = receiveAnon; + }; + + std::string sAddress; + bool fReceiveEnabled; + bool fReceiveAnon; + + IMPLEMENT_SERIALIZE + ( + READWRITE(this->sAddress); + READWRITE(this->fReceiveEnabled); + READWRITE(this->fReceiveAnon); + ); +}; + +class SecMsgOptions +{ +public: + SecMsgOptions() + { + // -- default options + fNewAddressRecv = true; + fNewAddressAnon = true; + } + + bool fNewAddressRecv; + bool fNewAddressAnon; +}; + + +class SecMsgCrypter +{ +private: + uint8_t chKey[32]; + uint8_t chIV[16]; + bool fKeySet; +public: + + SecMsgCrypter() + { + // Try to keep the key data out of swap (and be a bit over-careful to keep the IV that we don't even use out of swap) + // Note that this does nothing about suspend-to-disk (which will put all our key data on disk) + // Note as well that at no point in this program is any attempt made to prevent stealing of keys by reading the memory of the running process. + LockedPageManager::instance.LockRange(&chKey[0], sizeof chKey); + LockedPageManager::instance.LockRange(&chIV[0], sizeof chIV); + fKeySet = false; + } + + ~SecMsgCrypter() + { + // clean key + memset(&chKey, 0, sizeof chKey); + memset(&chIV, 0, sizeof chIV); + fKeySet = false; + + LockedPageManager::instance.UnlockRange(&chKey[0], sizeof chKey); + LockedPageManager::instance.UnlockRange(&chIV[0], sizeof chIV); + } + + bool SetKey(const std::vector& vchNewKey, uint8_t* chNewIV); + bool SetKey(const uint8_t* chNewKey, uint8_t* chNewIV); + bool Encrypt(uint8_t* chPlaintext, uint32_t nPlain, std::vector &vchCiphertext); + bool Decrypt(uint8_t* chCiphertext, uint32_t nCipher, std::vector& vchPlaintext); +}; + + +class SecMsgStored +{ +public: + int64_t timeReceived; + char status; // read etc + uint16_t folderId; + std::string sAddrTo; // when in owned addr, when sent remote addr + std::string sAddrOutbox; // owned address this copy was encrypted with + std::vector vchMessage; // message header + encryped payload + + IMPLEMENT_SERIALIZE + ( + READWRITE(this->timeReceived); + READWRITE(this->status); + READWRITE(this->folderId); + READWRITE(this->sAddrTo); + READWRITE(this->sAddrOutbox); + READWRITE(this->vchMessage); + ); +}; + +class SecMsgDB +{ +public: + SecMsgDB() + { + activeBatch = NULL; + }; + + ~SecMsgDB() + { + // -- deletes only data scoped to this TxDB object. + + if (activeBatch) + delete activeBatch; + }; + + bool Open(const char* pszMode="r+"); + + bool ScanBatch(const CDataStream& key, std::string* value, bool* deleted) const; + + bool TxnBegin(); + bool TxnCommit(); + bool TxnAbort(); + + bool ReadPK(CKeyID& addr, CPubKey& pubkey); + bool WritePK(CKeyID& addr, CPubKey& pubkey); + bool ExistsPK(CKeyID& addr); + + bool NextSmesg(leveldb::Iterator* it, std::string& prefix, uint8_t* vchKey, SecMsgStored& smsgStored); + bool NextSmesgKey(leveldb::Iterator* it, std::string& prefix, uint8_t* vchKey); + bool ReadSmesg(uint8_t* chKey, SecMsgStored& smsgStored); + bool WriteSmesg(uint8_t* chKey, SecMsgStored& smsgStored); + bool ExistsSmesg(uint8_t* chKey); + bool EraseSmesg(uint8_t* chKey); + + leveldb::DB *pdb; // points to the global instance + leveldb::WriteBatch *activeBatch; + +}; + + +int SecureMsgBuildBucketSet(); +int SecureMsgAddWalletAddresses(); + +int SecureMsgReadIni(); +int SecureMsgWriteIni(); + +bool SecureMsgStart(bool fDontStart, bool fScanChain); +bool SecureMsgShutdown(); + +bool SecureMsgEnable(); +bool SecureMsgDisable(); + +bool SecureMsgReceiveData(CNode* pfrom, std::string strCommand, CDataStream& vRecv); +bool SecureMsgSendData(CNode* pto, bool fSendTrickle); + + +bool SecureMsgScanBlock(CBlock& block); +bool ScanChainForPublicKeys(CBlockIndex* pindexStart); +bool SecureMsgScanBlockChain(); +bool SecureMsgScanBuckets(); + + +int SecureMsgWalletUnlocked(); +int SecureMsgWalletKeyChanged(std::string sAddress, std::string sLabel, ChangeType mode); + +int SecureMsgScanMessage(uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload, bool reportToGui); + +int SecureMsgGetStoredKey(CKeyID& ckid, CPubKey& cpkOut); +int SecureMsgGetLocalKey(CKeyID& ckid, CPubKey& cpkOut); +int SecureMsgGetLocalPublicKey(std::string& strAddress, std::string& strPublicKey); + +int SecureMsgAddAddress(std::string& address, std::string& publicKey); + +int SecureMsgRetrieve(SecMsgToken &token, std::vector& vchData); + +int SecureMsgReceive(CNode* pfrom, std::vector& vchData); + +int SecureMsgStoreUnscanned(uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload); +int SecureMsgStore(uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload, bool fUpdateBucket); +int SecureMsgStore(SecureMessage& smsg, bool fUpdateBucket); + + + +int SecureMsgSend(std::string& addressFrom, std::string& addressTo, std::string& message, std::string& sError); + +int SecureMsgValidate(uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload); +int SecureMsgSetHash(uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload); + +int SecureMsgEncrypt(SecureMessage& smsg, std::string& addressFrom, std::string& addressTo, std::string& message); + +int SecureMsgDecrypt(bool fTestOnly, std::string& address, uint8_t *pHeader, uint8_t *pPayload, uint32_t nPayload, MessageData& msg); +int SecureMsgDecrypt(bool fTestOnly, std::string& address, SecureMessage& smsg, MessageData& msg); + + + +#endif // SEC_MESSAGE_H + diff --git a/src/spork.cpp b/src/spork.cpp new file mode 100644 index 0000000..129b7cf --- /dev/null +++ b/src/spork.cpp @@ -0,0 +1,230 @@ +// Copyright (c) 2015 The GENIUS developers +// Copyright (c) 2009-2012 The Darkcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + + +#include "bignum.h" +#include "sync.h" +#include "net.h" +#include "key.h" +#include "util.h" +#include "script.h" +#include "base58.h" +#include "protocol.h" +#include "spork.h" +#include "main.h" +#include + +using namespace std; +using namespace boost; + +class CSporkMessage; +class CSporkManager; + +std::map mapSporks; +std::map mapSporksActive; +CSporkManager sporkManager; + +void ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv) +{ + if(fLiteMode) return; //disable all darksend/masternode related functionality + + if (strCommand == "spork") + { + //LogPrintf("ProcessSpork::spork\n"); + CDataStream vMsg(vRecv); + CSporkMessage spork; + vRecv >> spork; + + if(pindexBest == NULL) return; + + uint256 hash = spork.GetHash(); + if(mapSporks.count(hash) && mapSporksActive.count(spork.nSporkID)) { + if(mapSporksActive[spork.nSporkID].nTimeSigned >= spork.nTimeSigned){ + if(fDebug) LogPrintf("spork - seen %s block %d \n", hash.ToString().c_str(), pindexBest->nHeight); + return; + } else { + if(fDebug) LogPrintf("spork - got updated spork %s block %d \n", hash.ToString().c_str(), pindexBest->nHeight); + } + } + + LogPrintf("spork - new %s ID %d Time %d bestHeight %d\n", hash.ToString().c_str(), spork.nSporkID, spork.nValue, pindexBest->nHeight); + + if(!sporkManager.CheckSignature(spork)){ + LogPrintf("spork - invalid signature\n"); + Misbehaving(pfrom->GetId(), 100); + return; + } + + mapSporks[hash] = spork; + mapSporksActive[spork.nSporkID] = spork; + sporkManager.Relay(spork); + + //does a task if needed + ExecuteSpork(spork.nSporkID, spork.nValue); + } + if (strCommand == "getsporks") + { + std::map::iterator it = mapSporksActive.begin(); + + while(it != mapSporksActive.end()) { + pfrom->PushMessage("spork", it->second); + it++; + } + } + +} + +// grab the spork, otherwise say it's off +bool IsSporkActive(int nSporkID) +{ + int64_t r = 0; + + if(mapSporksActive.count(nSporkID)){ + r = mapSporksActive[nSporkID].nValue; + } else { + if(nSporkID == SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT) r = SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT_DEFAULT; + if(nSporkID == SPORK_2_MAX_VALUE) r = SPORK_2_MAX_VALUE_DEFAULT; + if(nSporkID == SPORK_3_REPLAY_BLOCKS) r = SPORK_3_REPLAY_BLOCKS_DEFAULT; + + if(r == 0 && fDebug) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID); + } + if(r == 0) r = 4070908800; //return 2099-1-1 by default + + return r < GetTime(); +} + +// grab the value of the spork on the network, or the default +int GetSporkValue(int nSporkID) +{ + int r = 0; + + if(mapSporksActive.count(nSporkID)){ + r = mapSporksActive[nSporkID].nValue; + } else { + if(nSporkID == SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT) r = SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT_DEFAULT; + if(nSporkID == SPORK_2_MAX_VALUE) r = SPORK_2_MAX_VALUE_DEFAULT; + if(nSporkID == SPORK_3_REPLAY_BLOCKS) r = SPORK_3_REPLAY_BLOCKS_DEFAULT; + + if(r == 0 && fDebug) LogPrintf("GetSpork::Unknown Spork %d\n", nSporkID); + } + + return r; +} + +void ExecuteSpork(int nSporkID, int nValue) +{ + //replay and process blocks (to sync to the longest chain after disabling sporks) + //if(nSporkID == SPORK_3_REPLAY_BLOCKS){ + //DisconnectBlocksAndReprocess(nValue); + //} +} + + +bool CSporkManager::CheckSignature(CSporkMessage& spork) +{ + //note: need to investigate why this is failing + std::string strMessage = boost::lexical_cast(spork.nSporkID) + boost::lexical_cast(spork.nValue) + boost::lexical_cast(spork.nTimeSigned); + std::string strPubKey = strMainPubKey; + CPubKey pubkey(ParseHex(strPubKey)); + + std::string errorMessage = ""; + if(!darkSendSigner.VerifyMessage(pubkey, spork.vchSig, strMessage, errorMessage)){ + return false; + } + + return true; +} + +bool CSporkManager::Sign(CSporkMessage& spork) +{ + std::string strMessage = boost::lexical_cast(spork.nSporkID) + boost::lexical_cast(spork.nValue) + boost::lexical_cast(spork.nTimeSigned); + + CKey key2; + CPubKey pubkey2; + std::string errorMessage = ""; + + if(!darkSendSigner.SetKey(strMasterPrivKey, errorMessage, key2, pubkey2)) + { + LogPrintf("CMasternodePayments::Sign - ERROR: Invalid masternodeprivkey: '%s'\n", errorMessage.c_str()); + return false; + } + + if(!darkSendSigner.SignMessage(strMessage, errorMessage, spork.vchSig, key2)) { + LogPrintf("CMasternodePayments::Sign - Sign message failed"); + return false; + } + + if(!darkSendSigner.VerifyMessage(pubkey2, spork.vchSig, strMessage, errorMessage)) { + LogPrintf("CMasternodePayments::Sign - Verify message failed"); + return false; + } + + return true; +} + +bool CSporkManager::UpdateSpork(int nSporkID, int64_t nValue) +{ + + CSporkMessage msg; + msg.nSporkID = nSporkID; + msg.nValue = nValue; + msg.nTimeSigned = GetTime(); + + if(Sign(msg)){ + Relay(msg); + mapSporks[msg.GetHash()] = msg; + mapSporksActive[nSporkID] = msg; + return true; + } + + return false; +} + +void CSporkManager::Relay(CSporkMessage& msg) +{ + CInv inv(MSG_SPORK, msg.GetHash()); + + vector vInv; + vInv.push_back(inv); + LOCK(cs_vNodes); + BOOST_FOREACH(CNode* pnode, vNodes){ + pnode->PushMessage("inv", vInv); + } +} + +bool CSporkManager::SetPrivKey(std::string strPrivKey) +{ + CSporkMessage msg; + + // Test signing successful, proceed + strMasterPrivKey = strPrivKey; + + Sign(msg); + + if(CheckSignature(msg)){ + LogPrintf("CSporkManager::SetPrivKey - Successfully initialized as spork signer\n"); + return true; + } else { + return false; + } +} + +int CSporkManager::GetSporkIDByName(std::string strName) +{ + if(strName == "SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT") return SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT; + if(strName == "SPORK_2_MAX_VALUE") return SPORK_2_MAX_VALUE; + if(strName == "SPORK_3_REPLAY_BLOCKS") return SPORK_3_REPLAY_BLOCKS; + + return -1; +} + +std::string CSporkManager::GetSporkNameByID(int id) +{ + if(id == SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT) return "SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT"; + if(id == SPORK_2_MAX_VALUE) return "SPORK_2_MAX_VALUE"; + if(id == SPORK_3_REPLAY_BLOCKS) return "SPORK_3_REPLAY_BLOCKS"; + + return "Unknown"; +} diff --git a/src/spork.h b/src/spork.h new file mode 100644 index 0000000..703ab62 --- /dev/null +++ b/src/spork.h @@ -0,0 +1,113 @@ +// Copyright (c) 2015 The GENIUS developers +// Copyright (c) 2009-2012 The Darkcoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. +#ifndef SPORK_H +#define SPORK_H + +#include "bignum.h" +#include "sync.h" +#include "net.h" +#include "key.h" + +#include "util.h" +#include "script.h" +#include "base58.h" +#include "main.h" + +using namespace std; +using namespace boost; + +// Don't ever reuse these IDs for other sporks +#define SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT 10000 +#define SPORK_2_MAX_VALUE 10002 +#define SPORK_3_REPLAY_BLOCKS 10003 +#define SPORK_4_NOTUSED 10004 + + +#define SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT_DEFAULT 2428537599 //2015-4-8 23:59:59 GMT +#define SPORK_2_MAX_VALUE_DEFAULT 500 //500 GENIUS +#define SPORK_3_REPLAY_BLOCKS_DEFAULT 0 +#define SPORK_4_RECONVERGE_DEFAULT 1420070400 //2047-1-1 + +class CSporkMessage; +class CSporkManager; + +#include "bignum.h" +#include "net.h" +#include "key.h" +#include "util.h" +#include "protocol.h" +#include "darksend.h" +#include + +using namespace std; +using namespace boost; + +extern std::map mapSporks; +extern std::map mapSporksActive; +extern CSporkManager sporkManager; + +void ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv); +int GetSporkValue(int nSporkID); +bool IsSporkActive(int nSporkID); +void ExecuteSpork(int nSporkID, int nValue); + +// +// Spork Class +// Keeps track of all of the network spork settings +// + +class CSporkMessage +{ +public: + std::vector vchSig; + int nSporkID; + int64_t nValue; + int64_t nTimeSigned; + + uint256 GetHash(){ + uint256 n = Hash(BEGIN(nSporkID), END(nTimeSigned)); + return n; + } + + ADD_SERIALIZE_METHODS; + + template + inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) { + unsigned int nSerSize = 0; + READWRITE(nSporkID); + READWRITE(nValue); + READWRITE(nTimeSigned); + READWRITE(vchSig); + } +}; + + +class CSporkManager +{ +private: + std::vector vchSig; + + std::string strMasterPrivKey; + std::string strTestPubKey; + std::string strMainPubKey; + +public: + + CSporkManager() { + strMainPubKey = "0419e538a30d8acd730f592f1fe49e71c09ff4dd24ff09ae43e93a39c32bc5b2c17d762cfd332078075525e0882a92848b411f578d5b91ca6f71f78cd518e2a260"; + strTestPubKey = "0419e538a30d8acd730f592f1fe49e71c09ff4dd24ff09ae43e93a39c32bc5b2c17d762cfd332078075525e0882a92848b411f578d5b91ca6f71f78cd518e2a260"; + } + + std::string GetSporkNameByID(int id); + int GetSporkIDByName(std::string strName); + bool UpdateSpork(int nSporkID, int64_t nValue); + bool SetPrivKey(std::string strPrivKey); + bool CheckSignature(CSporkMessage& spork); + bool Sign(CSporkMessage& spork); + void Relay(CSporkMessage& msg); + +}; + +#endif diff --git a/src/stealth.cpp b/src/stealth.cpp new file mode 100644 index 0000000..eabd853 --- /dev/null +++ b/src/stealth.cpp @@ -0,0 +1,682 @@ +// Copyright (c) 2014 The ShadowCoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file license.txt or http://www.opensource.org/licenses/mit-license.php. + +#include "stealth.h" +#include "base58.h" + + +#include +#include +#include +#include + +const uint8_t stealth_version_byte = 0x1c; + + +bool CStealthAddress::SetEncoded(const std::string& encodedAddress) +{ + data_chunk raw; + + if (!DecodeBase58(encodedAddress, raw)) + { + if (fDebug) + printf("CStealthAddress::SetEncoded DecodeBase58 falied.\n"); + return false; + }; + + if (!VerifyChecksum(raw)) + { + if (fDebug) + printf("CStealthAddress::SetEncoded verify_checksum falied.\n"); + return false; + }; + + if (raw.size() < 1 + 1 + 33 + 1 + 33 + 1 + 1 + 4) + { + if (fDebug) + printf("CStealthAddress::SetEncoded() too few bytes provided.\n"); + return false; + }; + + + uint8_t* p = &raw[0]; + uint8_t version = *p++; + + if (version != stealth_version_byte) + { + printf("CStealthAddress::SetEncoded version mismatch 0x%x != 0x%x.\n", version, stealth_version_byte); + return false; + }; + + options = *p++; + + scan_pubkey.resize(33); + memcpy(&scan_pubkey[0], p, 33); + p += 33; + //uint8_t spend_pubkeys = *p++; + p++; + + spend_pubkey.resize(33); + memcpy(&spend_pubkey[0], p, 33); + + return true; +}; + +std::string CStealthAddress::Encoded() const +{ + // https://wiki.unsystem.net/index.php/DarkWallet/Stealth#Address_format + // [version] [options] [scan_key] [N] ... [Nsigs] [prefix_length] ... + + data_chunk raw; + raw.push_back(stealth_version_byte); + + raw.push_back(options); + + raw.insert(raw.end(), scan_pubkey.begin(), scan_pubkey.end()); + raw.push_back(1); // number of spend pubkeys + raw.insert(raw.end(), spend_pubkey.begin(), spend_pubkey.end()); + raw.push_back(0); // number of signatures + raw.push_back(0); // ? + + AppendChecksum(raw); + + return EncodeBase58(raw); +}; + + +uint32_t BitcoinChecksum(uint8_t* p, uint32_t nBytes) +{ + if (!p || nBytes == 0) + return 0; + + uint8_t hash1[32]; + SHA256(p, nBytes, (uint8_t*)hash1); + uint8_t hash2[32]; + SHA256((uint8_t*)hash1, sizeof(hash1), (uint8_t*)hash2); + + // -- checksum is the 1st 4 bytes of the hash + uint32_t checksum = from_little_endian(&hash2[0]); + + return checksum; +}; + +void AppendChecksum(data_chunk& data) +{ + uint32_t checksum = BitcoinChecksum(&data[0], data.size()); + + // -- to_little_endian + std::vector tmp(4); + + //memcpy(&tmp[0], &checksum, 4); + for (int i = 0; i < 4; ++i) + { + tmp[i] = checksum & 0xFF; + checksum >>= 8; + }; + + data.insert(data.end(), tmp.begin(), tmp.end()); +}; + +bool VerifyChecksum(const data_chunk& data) +{ + if (data.size() < 4) + return false; + + uint32_t checksum = from_little_endian(data.end() - 4); + + return BitcoinChecksum((uint8_t*)&data[0], data.size()-4) == checksum; +}; + + +int GenerateRandomSecret(ec_secret& out) +{ + RandAddSeedPerfmon(); + + static uint256 max("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364140"); + static uint256 min(16000); // increase? min valid key is 1 + + uint256 test; + + int i; + // -- check max, try max 32 times + for (i = 0; i < 32; ++i) + { + RAND_bytes((unsigned char*) test.begin(), 32); + if (test > min && test < max) + { + memcpy(&out.e[0], test.begin(), 32); + break; + }; + }; + + if (i > 31) + { + printf("Error: GenerateRandomSecret failed to generate a valid key.\n"); + return 1; + }; + + return 0; +}; + +int SecretToPublicKey(const ec_secret& secret, ec_point& out) +{ + // -- public key = private * G + int rv = 0; + + EC_GROUP *ecgrp = EC_GROUP_new_by_curve_name(NID_secp256k1); + + if (!ecgrp) + { + printf("SecretToPublicKey(): EC_GROUP_new_by_curve_name failed.\n"); + return 1; + }; + + BIGNUM* bnIn = BN_bin2bn(&secret.e[0], ec_secret_size, BN_new()); + if (!bnIn) + { + EC_GROUP_free(ecgrp); + printf("SecretToPublicKey(): BN_bin2bn failed\n"); + return 1; + }; + + EC_POINT* pub = EC_POINT_new(ecgrp); + + + EC_POINT_mul(ecgrp, pub, bnIn, NULL, NULL, NULL); + + BIGNUM* bnOut = EC_POINT_point2bn(ecgrp, pub, POINT_CONVERSION_COMPRESSED, BN_new(), NULL); + if (!bnOut) + { + printf("SecretToPublicKey(): point2bn failed\n"); + rv = 1; + } else + { + out.resize(ec_compressed_size); + if (BN_num_bytes(bnOut) != (int) ec_compressed_size + || BN_bn2bin(bnOut, &out[0]) != (int) ec_compressed_size) + { + printf("SecretToPublicKey(): bnOut incorrect length.\n"); + rv = 1; + }; + + BN_free(bnOut); + }; + + EC_GROUP_free(ecgrp); + BN_free(bnIn); + EC_POINT_free(pub); + + return rv; +}; + + +int StealthSecret(ec_secret& secret, ec_point& pubkey, const ec_point& pkSpend, ec_secret& sharedSOut, ec_point& pkOut) +{ + /* + + send: + secret = ephem_secret, pubkey = scan_pubkey + + receive: + secret = scan_secret, pubkey = ephem_pubkey + c = H(dP) + + Q = public scan key (EC point, 33 bytes) + d = private scan key (integer, 32 bytes) + R = public spend key + f = private spend key + + Q = dG + R = fG + + Sender (has Q and R, not d or f): + + P = eG + + c = H(eQ) = H(dP) + R' = R + cG + + + Recipient gets R' and P + + test 0 and infinity? + */ + + int rv = 0; + std::vector vchOutQ; + + BN_CTX* bnCtx = NULL; + BIGNUM* bnEphem = NULL; + BIGNUM* bnQ = NULL; + EC_POINT* Q = NULL; + BIGNUM* bnOutQ = NULL; + BIGNUM* bnc = NULL; + EC_POINT* C = NULL; + BIGNUM* bnR = NULL; + EC_POINT* R = NULL; + EC_POINT* Rout = NULL; + BIGNUM* bnOutR = NULL; + + EC_GROUP* ecgrp = EC_GROUP_new_by_curve_name(NID_secp256k1); + + if (!ecgrp) + { + printf("StealthSecret(): EC_GROUP_new_by_curve_name failed.\n"); + return 1; + }; + + if (!(bnCtx = BN_CTX_new())) + { + printf("StealthSecret(): BN_CTX_new failed.\n"); + rv = 1; + goto End; + }; + + if (!(bnEphem = BN_bin2bn(&secret.e[0], ec_secret_size, BN_new()))) + { + printf("StealthSecret(): bnEphem BN_bin2bn failed.\n"); + rv = 1; + goto End; + }; + + if (!(bnQ = BN_bin2bn(&pubkey[0], pubkey.size(), BN_new()))) + { + printf("StealthSecret(): bnQ BN_bin2bn failed\n"); + rv = 1; + goto End; + }; + + if (!(Q = EC_POINT_bn2point(ecgrp, bnQ, NULL, bnCtx))) + { + printf("StealthSecret(): Q EC_POINT_bn2point failed\n"); + rv = 1; + goto End; + }; + + // -- eQ + // EC_POINT_mul(const EC_GROUP *group, EC_POINT *r, const BIGNUM *n, const EC_POINT *q, const BIGNUM *m, BN_CTX *ctx); + // EC_POINT_mul calculates the value generator * n + q * m and stores the result in r. The value n may be NULL in which case the result is just q * m. + if (!EC_POINT_mul(ecgrp, Q, NULL, Q, bnEphem, bnCtx)) + { + printf("StealthSecret(): eQ EC_POINT_mul failed\n"); + rv = 1; + goto End; + }; + + if (!(bnOutQ = EC_POINT_point2bn(ecgrp, Q, POINT_CONVERSION_COMPRESSED, BN_new(), bnCtx))) + { + printf("StealthSecret(): Q EC_POINT_bn2point failed\n"); + rv = 1; + goto End; + }; + + + vchOutQ.resize(ec_compressed_size); + if (BN_num_bytes(bnOutQ) != (int) ec_compressed_size + || BN_bn2bin(bnOutQ, &vchOutQ[0]) != (int) ec_compressed_size) + { + printf("StealthSecret(): bnOutQ incorrect length.\n"); + rv = 1; + goto End; + }; + + SHA256(&vchOutQ[0], vchOutQ.size(), &sharedSOut.e[0]); + + if (!(bnc = BN_bin2bn(&sharedSOut.e[0], ec_secret_size, BN_new()))) + { + printf("StealthSecret(): BN_bin2bn failed\n"); + rv = 1; + goto End; + }; + + // -- cG + if (!(C = EC_POINT_new(ecgrp))) + { + printf("StealthSecret(): C EC_POINT_new failed\n"); + rv = 1; + goto End; + }; + + if (!EC_POINT_mul(ecgrp, C, bnc, NULL, NULL, bnCtx)) + { + printf("StealthSecret(): C EC_POINT_mul failed\n"); + rv = 1; + goto End; + }; + + if (!(bnR = BN_bin2bn(&pkSpend[0], pkSpend.size(), BN_new()))) + { + printf("StealthSecret(): bnR BN_bin2bn failed\n"); + rv = 1; + goto End; + }; + + + if (!(R = EC_POINT_bn2point(ecgrp, bnR, NULL, bnCtx))) + { + printf("StealthSecret(): R EC_POINT_bn2point failed\n"); + rv = 1; + goto End; + }; + + if (!EC_POINT_mul(ecgrp, C, bnc, NULL, NULL, bnCtx)) + { + printf("StealthSecret(): C EC_POINT_mul failed\n"); + rv = 1; + goto End; + }; + + if (!(Rout = EC_POINT_new(ecgrp))) + { + printf("StealthSecret(): Rout EC_POINT_new failed\n"); + rv = 1; + goto End; + }; + + if (!EC_POINT_add(ecgrp, Rout, R, C, bnCtx)) + { + printf("StealthSecret(): Rout EC_POINT_add failed\n"); + rv = 1; + goto End; + }; + + if (!(bnOutR = EC_POINT_point2bn(ecgrp, Rout, POINT_CONVERSION_COMPRESSED, BN_new(), bnCtx))) + { + printf("StealthSecret(): Rout EC_POINT_bn2point failed\n"); + rv = 1; + goto End; + }; + + + pkOut.resize(ec_compressed_size); + if (BN_num_bytes(bnOutR) != (int) ec_compressed_size + || BN_bn2bin(bnOutR, &pkOut[0]) != (int) ec_compressed_size) + { + printf("StealthSecret(): pkOut incorrect length.\n"); + rv = 1; + goto End; + }; + + End: + if (bnOutR) BN_free(bnOutR); + if (Rout) EC_POINT_free(Rout); + if (R) EC_POINT_free(R); + if (bnR) BN_free(bnR); + if (C) EC_POINT_free(C); + if (bnc) BN_free(bnc); + if (bnOutQ) BN_free(bnOutQ); + if (Q) EC_POINT_free(Q); + if (bnQ) BN_free(bnQ); + if (bnEphem) BN_free(bnEphem); + if (bnCtx) BN_CTX_free(bnCtx); + EC_GROUP_free(ecgrp); + + return rv; +}; + + +int StealthSecretSpend(ec_secret& scanSecret, ec_point& ephemPubkey, ec_secret& spendSecret, ec_secret& secretOut) +{ + /* + + c = H(dP) + R' = R + cG [without decrypting wallet] + = (f + c)G [after decryption of wallet] + Remember: mod curve.order, pad with 0x00s where necessary? + */ + + int rv = 0; + std::vector vchOutP; + + BN_CTX* bnCtx = NULL; + BIGNUM* bnScanSecret = NULL; + BIGNUM* bnP = NULL; + EC_POINT* P = NULL; + BIGNUM* bnOutP = NULL; + BIGNUM* bnc = NULL; + BIGNUM* bnOrder = NULL; + BIGNUM* bnSpend = NULL; + + EC_GROUP* ecgrp = EC_GROUP_new_by_curve_name(NID_secp256k1); + + if (!ecgrp) + { + printf("StealthSecretSpend(): EC_GROUP_new_by_curve_name failed.\n"); + return 1; + }; + + if (!(bnCtx = BN_CTX_new())) + { + printf("StealthSecretSpend(): BN_CTX_new failed.\n"); + rv = 1; + goto End; + }; + + if (!(bnScanSecret = BN_bin2bn(&scanSecret.e[0], ec_secret_size, BN_new()))) + { + printf("StealthSecretSpend(): bnScanSecret BN_bin2bn failed.\n"); + rv = 1; + goto End; + }; + + if (!(bnP = BN_bin2bn(&ephemPubkey[0], ephemPubkey.size(), BN_new()))) + { + printf("StealthSecretSpend(): bnP BN_bin2bn failed\n"); + rv = 1; + goto End; + }; + + if (!(P = EC_POINT_bn2point(ecgrp, bnP, NULL, bnCtx))) + { + printf("StealthSecretSpend(): P EC_POINT_bn2point failed\n"); + rv = 1; + goto End; + }; + + // -- dP + if (!EC_POINT_mul(ecgrp, P, NULL, P, bnScanSecret, bnCtx)) + { + printf("StealthSecretSpend(): dP EC_POINT_mul failed\n"); + rv = 1; + goto End; + }; + + if (!(bnOutP = EC_POINT_point2bn(ecgrp, P, POINT_CONVERSION_COMPRESSED, BN_new(), bnCtx))) + { + printf("StealthSecretSpend(): P EC_POINT_bn2point failed\n"); + rv = 1; + goto End; + }; + + + vchOutP.resize(ec_compressed_size); + if (BN_num_bytes(bnOutP) != (int) ec_compressed_size + || BN_bn2bin(bnOutP, &vchOutP[0]) != (int) ec_compressed_size) + { + printf("StealthSecretSpend(): bnOutP incorrect length.\n"); + rv = 1; + goto End; + }; + + uint8_t hash1[32]; + SHA256(&vchOutP[0], vchOutP.size(), (uint8_t*)hash1); + + + if (!(bnc = BN_bin2bn(&hash1[0], 32, BN_new()))) + { + printf("StealthSecretSpend(): BN_bin2bn failed\n"); + rv = 1; + goto End; + }; + + if (!(bnOrder = BN_new()) + || !EC_GROUP_get_order(ecgrp, bnOrder, bnCtx)) + { + printf("StealthSecretSpend(): EC_GROUP_get_order failed\n"); + rv = 1; + goto End; + }; + + if (!(bnSpend = BN_bin2bn(&spendSecret.e[0], ec_secret_size, BN_new()))) + { + printf("StealthSecretSpend(): bnSpend BN_bin2bn failed.\n"); + rv = 1; + goto End; + }; + + //if (!BN_add(r, a, b)) return 0; + //return BN_nnmod(r, r, m, ctx); + if (!BN_mod_add(bnSpend, bnSpend, bnc, bnOrder, bnCtx)) + { + printf("StealthSecretSpend(): bnSpend BN_mod_add failed.\n"); + rv = 1; + goto End; + }; + + if (BN_is_zero(bnSpend)) // possible? + { + printf("StealthSecretSpend(): bnSpend is zero.\n"); + rv = 1; + goto End; + }; + + if (BN_num_bytes(bnSpend) != (int) ec_secret_size + || BN_bn2bin(bnSpend, &secretOut.e[0]) != (int) ec_secret_size) + { + printf("StealthSecretSpend(): bnSpend incorrect length.\n"); + rv = 1; + goto End; + }; + + End: + if (bnSpend) BN_free(bnSpend); + if (bnOrder) BN_free(bnOrder); + if (bnc) BN_free(bnc); + if (bnOutP) BN_free(bnOutP); + if (P) EC_POINT_free(P); + if (bnP) BN_free(bnP); + if (bnScanSecret) BN_free(bnScanSecret); + if (bnCtx) BN_CTX_free(bnCtx); + EC_GROUP_free(ecgrp); + + return rv; +}; + + +int StealthSharedToSecretSpend(ec_secret& sharedS, ec_secret& spendSecret, ec_secret& secretOut) +{ + + int rv = 0; + std::vector vchOutP; + + BN_CTX* bnCtx = NULL; + BIGNUM* bnc = NULL; + BIGNUM* bnOrder = NULL; + BIGNUM* bnSpend = NULL; + + EC_GROUP* ecgrp = EC_GROUP_new_by_curve_name(NID_secp256k1); + + if (!ecgrp) + { + printf("StealthSecretSpend(): EC_GROUP_new_by_curve_name failed.\n"); + return 1; + }; + + if (!(bnCtx = BN_CTX_new())) + { + printf("StealthSecretSpend(): BN_CTX_new failed.\n"); + rv = 1; + goto End; + }; + + if (!(bnc = BN_bin2bn(&sharedS.e[0], ec_secret_size, BN_new()))) + { + printf("StealthSecretSpend(): BN_bin2bn failed\n"); + rv = 1; + goto End; + }; + + if (!(bnOrder = BN_new()) + || !EC_GROUP_get_order(ecgrp, bnOrder, bnCtx)) + { + printf("StealthSecretSpend(): EC_GROUP_get_order failed\n"); + rv = 1; + goto End; + }; + + if (!(bnSpend = BN_bin2bn(&spendSecret.e[0], ec_secret_size, BN_new()))) + { + printf("StealthSecretSpend(): bnSpend BN_bin2bn failed.\n"); + rv = 1; + goto End; + }; + + //if (!BN_add(r, a, b)) return 0; + //return BN_nnmod(r, r, m, ctx); + if (!BN_mod_add(bnSpend, bnSpend, bnc, bnOrder, bnCtx)) + { + printf("StealthSecretSpend(): bnSpend BN_mod_add failed.\n"); + rv = 1; + goto End; + }; + + if (BN_is_zero(bnSpend)) // possible? + { + printf("StealthSecretSpend(): bnSpend is zero.\n"); + rv = 1; + goto End; + }; + + if (BN_num_bytes(bnSpend) != (int) ec_secret_size + || BN_bn2bin(bnSpend, &secretOut.e[0]) != (int) ec_secret_size) + { + printf("StealthSecretSpend(): bnSpend incorrect length.\n"); + rv = 1; + goto End; + }; + + End: + if (bnSpend) BN_free(bnSpend); + if (bnOrder) BN_free(bnOrder); + if (bnc) BN_free(bnc); + if (bnCtx) BN_CTX_free(bnCtx); + EC_GROUP_free(ecgrp); + + return rv; +}; + +bool IsStealthAddress(const std::string& encodedAddress) +{ + data_chunk raw; + + if (!DecodeBase58(encodedAddress, raw)) + { + //printf("IsStealthAddress DecodeBase58 falied.\n"); + return false; + }; + + if (!VerifyChecksum(raw)) + { + //printf("IsStealthAddress verify_checksum falied.\n"); + return false; + }; + + if (raw.size() < 1 + 1 + 33 + 1 + 33 + 1 + 1 + 4) + { + //printf("IsStealthAddress too few bytes provided.\n"); + return false; + }; + + + uint8_t* p = &raw[0]; + uint8_t version = *p++; + + if (version != stealth_version_byte) + { + //printf("IsStealthAddress version mismatch 0x%x != 0x%x.\n", version, stealth_version_byte); + return false; + }; + + return true; +}; diff --git a/src/stealth.h b/src/stealth.h new file mode 100644 index 0000000..c4d104c --- /dev/null +++ b/src/stealth.h @@ -0,0 +1,119 @@ +// Copyright (c) 2014 The ShadowCoin developers +// Distributed under the MIT/X11 software license, see the accompanying +// file license.txt or http://www.opensource.org/licenses/mit-license.php. + +#ifndef BITCOIN_STEALTH_H +#define BITCOIN_STEALTH_H + +#include "util.h" +#include "serialize.h" + +#include +#include +#include +#include + + +typedef std::vector data_chunk; + +const size_t ec_secret_size = 32; +const size_t ec_compressed_size = 33; +const size_t ec_uncompressed_size = 65; + +typedef struct ec_secret { uint8_t e[ec_secret_size]; } ec_secret; +typedef data_chunk ec_point; + +typedef uint32_t stealth_bitfield; + +struct stealth_prefix +{ + uint8_t number_bits; + stealth_bitfield bitfield; +}; + +template +T from_big_endian(Iterator in) +{ + //VERIFY_UNSIGNED(T); + T out = 0; + size_t i = sizeof(T); + while (0 < i) + out |= static_cast(*in++) << (8 * --i); + return out; +} + +template +T from_little_endian(Iterator in) +{ + //VERIFY_UNSIGNED(T); + T out = 0; + size_t i = 0; + while (i < sizeof(T)) + out |= static_cast(*in++) << (8 * i++); + return out; +} + +class CStealthAddress +{ +public: + CStealthAddress() + { + options = 0; + } + + uint8_t options; + ec_point scan_pubkey; + ec_point spend_pubkey; + //std::vector spend_pubkeys; + size_t number_signatures; + stealth_prefix prefix; + + mutable std::string label; + data_chunk scan_secret; + data_chunk spend_secret; + + bool SetEncoded(const std::string& encodedAddress); + std::string Encoded() const; + + bool operator <(const CStealthAddress& y) const + { + return memcmp(&scan_pubkey[0], &y.scan_pubkey[0], ec_compressed_size) < 0; + } + + bool operator ==(const CStealthAddress& y) const + { + return Encoded() == y.Encoded(); + } + + IMPLEMENT_SERIALIZE + ( + READWRITE(this->options); + READWRITE(this->scan_pubkey); + READWRITE(this->spend_pubkey); + READWRITE(this->label); + + READWRITE(this->scan_secret); + READWRITE(this->spend_secret); + ); + + + +}; + +void AppendChecksum(data_chunk& data); + +bool VerifyChecksum(const data_chunk& data); + +int GenerateRandomSecret(ec_secret& out); + +int SecretToPublicKey(const ec_secret& secret, ec_point& out); + +int StealthSecret(ec_secret& secret, ec_point& pubkey, const ec_point& pkSpend, ec_secret& sharedSOut, ec_point& pkOut); +int StealthSecretSpend(ec_secret& scanSecret, ec_point& ephemPubkey, ec_secret& spendSecret, ec_secret& secretOut); +int StealthSharedToSecretSpend(ec_secret& sharedS, ec_secret& spendSecret, ec_secret& secretOut); + +bool IsStealthAddress(const std::string& encodedAddress); + + +#endif // BITCOIN_STEALTH_H + diff --git a/src/txdb-leveldb.cpp b/src/txdb-leveldb.cpp index bcddc08..46ab82e 100644 --- a/src/txdb-leveldb.cpp +++ b/src/txdb-leveldb.cpp @@ -197,6 +197,33 @@ bool CTxDB::ScanBatch(const CDataStream &key, string *value, bool *deleted) cons return scanner.foundEntry; } +bool CTxDB::WriteAddrIndex(uint160 addrHash, uint256 txHash) +{ + std::vector txHashes; + if(!ReadAddrIndex(addrHash, txHashes)) + { + txHashes.push_back(txHash); + return Write(make_pair(string("adr"), addrHash), txHashes); + } + else + { + if(std::find(txHashes.begin(), txHashes.end(), txHash) == txHashes.end()) + { + txHashes.push_back(txHash); + return Write(make_pair(string("adr"), addrHash), txHashes); + } + else + { + return true; // already have this tx hash + } + } +} + +bool CTxDB::ReadAddrIndex(uint160 addrHash, std::vector& txHashes) +{ + return Read(make_pair(string("adr"), addrHash), txHashes); +} + bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex) { txindex.SetNull(); diff --git a/src/txdb-leveldb.h b/src/txdb-leveldb.h index 09b24f6..fd0e85b 100644 --- a/src/txdb-leveldb.h +++ b/src/txdb-leveldb.h @@ -183,6 +183,8 @@ class CTxDB return Write(std::string("version"), nVersion); } + bool ReadAddrIndex(uint160 addrHash, std::vector& txHashes); + bool WriteAddrIndex(uint160 addrHash, uint256 txHash); bool ReadTxIndex(uint256 hash, CTxIndex& txindex); bool UpdateTxIndex(uint256 hash, const CTxIndex& txindex); bool AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight); diff --git a/src/ui_interface.h b/src/ui_interface.h index 19e7da8..e2d8a08 100644 --- a/src/ui_interface.h +++ b/src/ui_interface.h @@ -16,6 +16,7 @@ class CBasicKeyStore; class CWallet; class uint256; +class CAdrenalineNodeConfig; /** General change type (added, updated, removed). */ enum ChangeType @@ -93,6 +94,8 @@ class CClientUIInterface * @note called with lock cs_mapAlerts held. */ boost::signals2::signal NotifyAlertChanged; + + boost::signals2::signal NotifyAdrenalineNodeChanged; }; extern CClientUIInterface uiInterface; diff --git a/src/uint256.h b/src/uint256.h index 3a958ca..c203bc0 100644 --- a/src/uint256.h +++ b/src/uint256.h @@ -351,6 +351,16 @@ class base_uint return (unsigned char*)&pn[WIDTH]; } + const unsigned char* begin() const + { + return (unsigned char*)&pn[0]; + } + + const unsigned char* end() const + { + return (unsigned char*)&pn[WIDTH]; + } + unsigned int size() { return sizeof(pn); diff --git a/src/util.cpp b/src/util.cpp index 9f2a386..5185e46 100644 --- a/src/util.cpp +++ b/src/util.cpp @@ -37,6 +37,7 @@ namespace boost { #include #include #include +#include #include #ifdef WIN32 @@ -66,9 +67,27 @@ namespace boost { using namespace std; +//Dark features +bool fMasterNode = false; +string strMasterNodePrivKey = ""; +string strMasterNodeAddr = ""; +bool fLiteMode = false; +int nInstantXDepth = 1; +int nDarksendRounds = 2; +int nAnonymizeGeniusAmount = 500; +int nLiquidityProvider = 0; +/** Spork enforcement enabled time */ +int64_t enforceMasternodePaymentsTime = 4085657524; +bool fSucessfullyLoaded = false; +bool fEnableDarksend = false; +/** All denominations used by darksend */ +std::vector darkSendDenominations; + map mapArgs; map > mapMultiArgs; bool fDebug = false; +bool fDebugSmsg = false; +bool fNoSmsg = false; bool fPrintToConsole = false; bool fPrintToDebugLog = true; bool fDaemon = false; @@ -194,6 +213,14 @@ uint256 GetRandHash() return hash; } +void GetRandBytes(unsigned char* buf, int num) +{ + if (RAND_bytes(buf, num) != 1) { + LogPrintf("%s: OpenSSL RAND_bytes() failed with error: %s\n", __func__, ERR_error_string(ERR_get_error(), NULL)); + assert(false); + } +} + // LogPrintf() has been broken a couple of times now // by well-meaning people adding mutexes in the most straightforward way. // It breaks because it may be called by global destructors during shutdown. @@ -688,6 +715,63 @@ string DecodeBase64(const string& str) return string((const char*)&vchRet[0], vchRet.size()); } +// Base64 encoding with secure memory allocation +SecureString EncodeBase64Secure(const SecureString& input) +{ + // Init openssl BIO with base64 filter and memory output + BIO *b64, *mem; + b64 = BIO_new(BIO_f_base64()); + BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); // No newlines in output + mem = BIO_new(BIO_s_mem()); + BIO_push(b64, mem); + + // Decode the string + BIO_write(b64, &input[0], input.size()); + (void) BIO_flush(b64); + + // Create output variable from buffer mem ptr + BUF_MEM *bptr; + BIO_get_mem_ptr(b64, &bptr); + SecureString output(bptr->data, bptr->length); + + // Cleanse secure data buffer from memory + OPENSSL_cleanse((void *) bptr->data, bptr->length); + + // Free memory + BIO_free_all(b64); + return output; +} + +// Base64 decoding with secure memory allocation +SecureString DecodeBase64Secure(const SecureString& input) +{ + SecureString output; + + // Init openssl BIO with base64 filter and memory input + BIO *b64, *mem; + b64 = BIO_new(BIO_f_base64()); + BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); //Do not use newlines to flush buffer + mem = BIO_new_mem_buf((void *) &input[0], input.size()); + BIO_push(b64, mem); + + // Prepare buffer to receive decoded data + if(input.size() % 4 != 0) { + throw runtime_error("Input length should be a multiple of 4"); + } + size_t nMaxLen = input.size() / 4 * 3; // upper bound, guaranteed divisible by 4 + output.resize(nMaxLen); + + // Decode the string + size_t nLen; + nLen = BIO_read(b64, (void *) &output[0], input.size()); + output.resize(nLen); + + // Free memory + BIO_free_all(b64); + return output; +} + + string EncodeBase32(const unsigned char* pch, size_t len) { static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567"; @@ -906,9 +990,54 @@ bool WildcardMatch(const string& str, const string& mask) } +bool ParseInt32(const std::string& str, int32_t *out) +{ + char *endp = NULL; + errno = 0; // strtol will not set errno if valid + long int n = strtol(str.c_str(), &endp, 10); + if(out) *out = (int)n; + // Note that strtol returns a *long int*, so even if strtol doesn't report a over/underflow + // we still have to check that the returned value is within the range of an *int32_t*. On 64-bit + // platforms the size of these types may be different. + return endp && *endp == 0 && !errno && + n >= std::numeric_limits::min() && + n <= std::numeric_limits::max(); +} - - +std::string FormatParagraph(const std::string in, size_t width, size_t indent) +{ + std::stringstream out; + size_t col = 0; + size_t ptr = 0; + while(ptr < in.size()) + { + // Find beginning of next word + ptr = in.find_first_not_of(' ', ptr); + if (ptr == std::string::npos) + break; + // Find end of next word + size_t endword = in.find_first_of(' ', ptr); + if (endword == std::string::npos) + endword = in.size(); + // Add newline and indentation if this wraps over the allowed width + if (col > 0) + { + if ((col + endword - ptr) > width) + { + out << '\n'; + for(size_t i=0; i& mapSettingsRet, map >& mapMultiSettingsRet) { @@ -1089,6 +1225,30 @@ void FileCommit(FILE *fileout) #endif } +std::string getTimeString(int64_t timestamp, char *buffer, size_t nBuffer) +{ + struct tm* dt; + time_t t = timestamp; + dt = localtime(&t); + + strftime(buffer, nBuffer, "%Y-%m-%d %H:%M:%S %z", dt); // %Z shows long strings on windows + return std::string(buffer); // copies the null-terminated character sequence +}; + +std::string bytesReadable(uint64_t nBytes) +{ + if (nBytes >= 1024ll*1024ll*1024ll*1024ll) + return strprintf("%.2f TB", nBytes/1024.0/1024.0/1024.0/1024.0); + if (nBytes >= 1024*1024*1024) + return strprintf("%.2f GB", nBytes/1024.0/1024.0/1024.0); + if (nBytes >= 1024*1024) + return strprintf("%.2f MB", nBytes/1024.0/1024.0); + if (nBytes >= 1024) + return strprintf("%.2f KB", nBytes/1024.0); + + return strprintf("%d B", nBytes); +}; + void ShrinkDebugFile() { // Scroll debug.log if it's getting too big @@ -1228,3 +1388,5 @@ std::string DateTimeStrFormat(const char* pszFormat, int64_t nTime) ss << boost::posix_time::from_time_t(nTime); return ss.str(); } + + diff --git a/src/util.h b/src/util.h index 135d889..ef274f4 100644 --- a/src/util.h +++ b/src/util.h @@ -27,6 +27,13 @@ #include #include +#include +#include +#include +#include // for OPENSSL_cleanse() +#include +#include + #include class uint256; @@ -34,6 +41,8 @@ class uint256; static const int64_t COIN = 100000000; static const int64_t CENT = 1000000; +typedef int64_t CAmount; + #define BEGIN(a) ((char*)&(a)) #define END(a) ((char*)&((&(a))[1])) #define UBEGIN(a) ((unsigned char*)&(a)) @@ -45,6 +54,26 @@ static const int64_t CENT = 1000000; #define UINTBEGIN(a) ((uint32_t*)&(a)) #define CUINTBEGIN(a) ((const uint32_t*)&(a)) +/* Format characters for (s)size_t and ptrdiff_t */ +#if defined(_MSC_VER) || defined(__MSVCRT__) + /* (s)size_t and ptrdiff_t have the same size specifier in MSVC: + http://msdn.microsoft.com/en-us/library/tcxf1dw6%28v=vs.100%29.aspx + */ + #define PRIszx "Ix" + #define PRIszu "Iu" + #define PRIszd "Id" + #define PRIpdx "Ix" + #define PRIpdu "Iu" + #define PRIpdd "Id" +#else /* C99 standard */ + #define PRIszx "zx" + #define PRIszu "zu" + #define PRIszd "zd" + #define PRIpdx "tx" + #define PRIpdu "tu" + #define PRIpdd "td" +#endif + // This is needed because the foreach macro can't get over the comma in pair #define PAIRTYPE(t1, t2) std::pair @@ -62,6 +91,8 @@ T* alignup(T* p) return u.ptr; } +boost::filesystem::path GetMasternodeConfigFile(); + #ifdef WIN32 #define MSG_NOSIGNAL 0 #define MSG_DONTWAIT 0 @@ -83,11 +114,27 @@ inline void MilliSleep(int64_t n) #endif } +//Dark features + +extern bool fMasterNode; +extern bool fLiteMode; +extern int nInstantXDepth; +extern int nDarksendRounds; +extern int nAnonymizeGeniusAmount; +extern int nLiquidityProvider; +extern bool fEnableDarksend; +extern int64_t enforceMasternodePaymentsTime; +extern std::string strMasterNodeAddr; +extern int keysLoaded; +extern bool fSucessfullyLoaded; +extern std::vector darkSendDenominations; extern std::map mapArgs; extern std::map > mapMultiArgs; extern bool fDebug; +extern bool fDebugSmsg; +extern bool fNoSmsg; extern bool fPrintToConsole; extern bool fPrintToDebugLog; extern bool fDaemon; @@ -101,6 +148,8 @@ extern volatile bool fReopenDebugLog; void RandAddSeed(); void RandAddSeedPerfmon(); + + /* Return true if log accepts specified category */ bool LogAcceptCategory(const char* category); /* Send a string to the log output */ @@ -158,6 +207,8 @@ std::vector DecodeBase64(const char* p, bool* pfInvalid = NULL); std::string DecodeBase64(const std::string& str); std::string EncodeBase64(const unsigned char* pch, size_t len); std::string EncodeBase64(const std::string& str); +SecureString DecodeBase64Secure(const SecureString& input); +SecureString EncodeBase64Secure(const SecureString& input); std::vector DecodeBase32(const char* p, bool* pfInvalid = NULL); std::string DecodeBase32(const std::string& str); std::string EncodeBase32(const unsigned char* pch, size_t len); @@ -178,7 +229,12 @@ void ReadConfigFile(std::map& mapSettingsRet, std::map #ifdef WIN32 boost::filesystem::path GetSpecialFolderPath(int nFolder, bool fCreate = true); #endif + +std::string getTimeString(int64_t timestamp, char *buffer, size_t nBuffer); +std::string bytesReadable(uint64_t nBytes); + void ShrinkDebugFile(); +void GetRandBytes(unsigned char* buf, int num); int GetRandInt(int nMax); uint64_t GetRand(uint64_t nMax); uint256 GetRandHash(); @@ -191,8 +247,19 @@ void runCommand(std::string strCommand); +/** + * Convert string to signed 32-bit integer with strict parse error feedback. + * @returns true if the entire string could be parsed as valid integer, + * false if not the entire string could be parsed or when overflow or underflow occurred. + */ +bool ParseInt32(const std::string& str, int32_t *out); +/** + * Format a paragraph of text to a fixed width, adding spaces for + * indentation to any added line. + */ +std::string FormatParagraph(const std::string in, size_t width=79, size_t indent=0); diff --git a/src/utilstrencodings.cpp b/src/utilstrencodings.cpp new file mode 100644 index 0000000..64c7d92 --- /dev/null +++ b/src/utilstrencodings.cpp @@ -0,0 +1,489 @@ +// Copyright (c) 2009-2010 Satoshi Nakamoto +// Copyright (c) 2009-2015 The Bitcoin Core developers +// Distributed under the MIT software license, see the accompanying +// file COPYING or http://www.opensource.org/licenses/mit-license.php. + +#include "utilstrencodings.h" + +#include "tinyformat.h" + +#include +#include +#include +#include + +using namespace std; + + + + + + + +string EncodeBase64(const unsigned char* pch, size_t len) +{ + static const char *pbase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + + string strRet=""; + strRet.reserve((len+2)/3*4); + + int mode=0, left=0; + const unsigned char *pchEnd = pch+len; + + while (pch> 2]; + left = (enc & 3) << 4; + mode = 1; + break; + + case 1: // we have two bits + strRet += pbase64[left | (enc >> 4)]; + left = (enc & 15) << 2; + mode = 2; + break; + + case 2: // we have four bits + strRet += pbase64[left | (enc >> 6)]; + strRet += pbase64[enc & 63]; + mode = 0; + break; + } + } + + if (mode) + { + strRet += pbase64[left]; + strRet += '='; + if (mode == 1) + strRet += '='; + } + + return strRet; +} + +string EncodeBase64(const string& str) +{ + return EncodeBase64((const unsigned char*)str.c_str(), str.size()); +} + +vector DecodeBase64(const char* p, bool* pfInvalid) +{ + static const int decode64_table[256] = + { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, 62, -1, -1, -1, 63, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, -1, -1, + -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 26, 27, 28, + 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + }; + + if (pfInvalid) + *pfInvalid = false; + + vector vchRet; + vchRet.reserve(strlen(p)*3/4); + + int mode = 0; + int left = 0; + + while (1) + { + int dec = decode64_table[(unsigned char)*p]; + if (dec == -1) break; + p++; + switch (mode) + { + case 0: // we have no bits and get 6 + left = dec; + mode = 1; + break; + + case 1: // we have 6 bits and keep 4 + vchRet.push_back((left<<2) | (dec>>4)); + left = dec & 15; + mode = 2; + break; + + case 2: // we have 4 bits and get 6, we keep 2 + vchRet.push_back((left<<4) | (dec>>2)); + left = dec & 3; + mode = 3; + break; + + case 3: // we have 2 bits and get 6 + vchRet.push_back((left<<6) | dec); + mode = 0; + break; + } + } + + if (pfInvalid) + switch (mode) + { + case 0: // 4n base64 characters processed: ok + break; + + case 1: // 4n+1 base64 character processed: impossible + *pfInvalid = true; + break; + + case 2: // 4n+2 base64 characters processed: require '==' + if (left || p[0] != '=' || p[1] != '=' || decode64_table[(unsigned char)p[2]] != -1) + *pfInvalid = true; + break; + + case 3: // 4n+3 base64 characters processed: require '=' + if (left || p[0] != '=' || decode64_table[(unsigned char)p[1]] != -1) + *pfInvalid = true; + break; + } + + return vchRet; +} + +string DecodeBase64(const string& str) +{ + vector vchRet = DecodeBase64(str.c_str()); + return (vchRet.size() == 0) ? string() : string((const char*)&vchRet[0], vchRet.size()); +} + +// Base64 encoding with secure memory allocation +SecureString EncodeBase64Secure(const SecureString& input) +{ + // Init openssl BIO with base64 filter and memory output + BIO *b64, *mem; + b64 = BIO_new(BIO_f_base64()); + BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); // No newlines in output + mem = BIO_new(BIO_s_mem()); + BIO_push(b64, mem); + + // Decode the string + BIO_write(b64, &input[0], input.size()); + (void) BIO_flush(b64); + + // Create output variable from buffer mem ptr + BUF_MEM *bptr; + BIO_get_mem_ptr(b64, &bptr); + SecureString output(bptr->data, bptr->length); + + // Cleanse secure data buffer from memory + OPENSSL_cleanse((void *) bptr->data, bptr->length); + + // Free memory + BIO_free_all(b64); + return output; +} + +// Base64 decoding with secure memory allocation +SecureString DecodeBase64Secure(const SecureString& input) +{ + SecureString output; + + // Init openssl BIO with base64 filter and memory input + BIO *b64, *mem; + b64 = BIO_new(BIO_f_base64()); + BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL); //Do not use newlines to flush buffer + mem = BIO_new_mem_buf((void *) &input[0], input.size()); + BIO_push(b64, mem); + + // Prepare buffer to receive decoded data + if(input.size() % 4 != 0) { + throw runtime_error("Input length should be a multiple of 4"); + } + size_t nMaxLen = input.size() / 4 * 3; // upper bound, guaranteed divisible by 4 + output.resize(nMaxLen); + + // Decode the string + size_t nLen; + nLen = BIO_read(b64, (void *) &output[0], input.size()); + output.resize(nLen); + + // Free memory + BIO_free_all(b64); + return output; +} + + + + +string EncodeBase32(const unsigned char* pch, size_t len) +{ + static const char *pbase32 = "abcdefghijklmnopqrstuvwxyz234567"; + + string strRet=""; + strRet.reserve((len+4)/5*8); + + int mode=0, left=0; + const unsigned char *pchEnd = pch+len; + + while (pch> 3]; + left = (enc & 7) << 2; + mode = 1; + break; + + case 1: // we have three bits + strRet += pbase32[left | (enc >> 6)]; + strRet += pbase32[(enc >> 1) & 31]; + left = (enc & 1) << 4; + mode = 2; + break; + + case 2: // we have one bit + strRet += pbase32[left | (enc >> 4)]; + left = (enc & 15) << 1; + mode = 3; + break; + + case 3: // we have four bits + strRet += pbase32[left | (enc >> 7)]; + strRet += pbase32[(enc >> 2) & 31]; + left = (enc & 3) << 3; + mode = 4; + break; + + case 4: // we have two bits + strRet += pbase32[left | (enc >> 5)]; + strRet += pbase32[enc & 31]; + mode = 0; + } + } + + static const int nPadding[5] = {0, 6, 4, 3, 1}; + if (mode) + { + strRet += pbase32[left]; + for (int n=0; n DecodeBase32(const char* p, bool* pfInvalid) +{ + static const int decode32_table[256] = + { + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 26, 27, 28, 29, 30, 31, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, + 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, -1, -1, -1, -1, -1, -1, 0, 1, 2, + 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, + 23, 24, 25, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 + }; + + if (pfInvalid) + *pfInvalid = false; + + vector vchRet; + vchRet.reserve((strlen(p))*5/8); + + int mode = 0; + int left = 0; + + while (1) + { + int dec = decode32_table[(unsigned char)*p]; + if (dec == -1) break; + p++; + switch (mode) + { + case 0: // we have no bits and get 5 + left = dec; + mode = 1; + break; + + case 1: // we have 5 bits and keep 2 + vchRet.push_back((left<<3) | (dec>>2)); + left = dec & 3; + mode = 2; + break; + + case 2: // we have 2 bits and keep 7 + left = left << 5 | dec; + mode = 3; + break; + + case 3: // we have 7 bits and keep 4 + vchRet.push_back((left<<1) | (dec>>4)); + left = dec & 15; + mode = 4; + break; + + case 4: // we have 4 bits, and keep 1 + vchRet.push_back((left<<4) | (dec>>1)); + left = dec & 1; + mode = 5; + break; + + case 5: // we have 1 bit, and keep 6 + left = left << 5 | dec; + mode = 6; + break; + + case 6: // we have 6 bits, and keep 3 + vchRet.push_back((left<<2) | (dec>>3)); + left = dec & 7; + mode = 7; + break; + + case 7: // we have 3 bits, and keep 0 + vchRet.push_back((left<<5) | dec); + mode = 0; + break; + } + } + + if (pfInvalid) + switch (mode) + { + case 0: // 8n base32 characters processed: ok + break; + + case 1: // 8n+1 base32 characters processed: impossible + case 3: // +3 + case 6: // +6 + *pfInvalid = true; + break; + + case 2: // 8n+2 base32 characters processed: require '======' + if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || p[4] != '=' || p[5] != '=' || decode32_table[(unsigned char)p[6]] != -1) + *pfInvalid = true; + break; + + case 4: // 8n+4 base32 characters processed: require '====' + if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || p[3] != '=' || decode32_table[(unsigned char)p[4]] != -1) + *pfInvalid = true; + break; + + case 5: // 8n+5 base32 characters processed: require '===' + if (left || p[0] != '=' || p[1] != '=' || p[2] != '=' || decode32_table[(unsigned char)p[3]] != -1) + *pfInvalid = true; + break; + + case 7: // 8n+7 base32 characters processed: require '=' + if (left || p[0] != '=' || decode32_table[(unsigned char)p[1]] != -1) + *pfInvalid = true; + break; + } + + return vchRet; +} + +string DecodeBase32(const string& str) +{ + vector vchRet = DecodeBase32(str.c_str()); + return (vchRet.size() == 0) ? string() : string((const char*)&vchRet[0], vchRet.size()); +} + +bool ParseInt32(const std::string& str, int32_t *out) +{ + char *endp = NULL; + errno = 0; // strtol will not set errno if valid + long int n = strtol(str.c_str(), &endp, 10); + if(out) *out = (int)n; + // Note that strtol returns a *long int*, so even if strtol doesn't report a over/underflow + // we still have to check that the returned value is within the range of an *int32_t*. On 64-bit + // platforms the size of these types may be different. + return endp && *endp == 0 && !errno && + n >= std::numeric_limits::min() && + n <= std::numeric_limits::max(); +} + +std::string FormatParagraph(const std::string in, size_t width, size_t indent) +{ + std::stringstream out; + size_t col = 0; + size_t ptr = 0; + while(ptr < in.size()) + { + // Find beginning of next word + ptr = in.find_first_not_of(' ', ptr); + if (ptr == std::string::npos) + break; + // Find end of next word + size_t endword = in.find_first_of(' ', ptr); + if (endword == std::string::npos) + endword = in.size(); + // Add newline and indentation if this wraps over the allowed width + if (col > 0) + { + if ((col + endword - ptr) > width) + { + out << '\n'; + for(size_t i=0; i +#include +#include +#include "serialize.h" +#include "allocators.h" + + +#include +#include +#include +#include +#include // for OPENSSL_cleanse() +#include +#include + + +#define BEGIN(a) ((char*)&(a)) +#define END(a) ((char*)&((&(a))[1])) +#define UBEGIN(a) ((unsigned char*)&(a)) +#define UEND(a) ((unsigned char*)&((&(a))[1])) +#define ARRAYLEN(array) (sizeof(array)/sizeof((array)[0])) + +/** This is needed because the foreach macro can't get over the comma in pair */ +#define PAIRTYPE(t1, t2) std::pair + + + +std::vector DecodeBase64(const char* p, bool* pfInvalid = NULL); +std::string DecodeBase64(const std::string& str); +std::string EncodeBase64(const unsigned char* pch, size_t len); +std::string EncodeBase64(const std::string& str); +SecureString DecodeBase64Secure(const SecureString& input); +SecureString EncodeBase64Secure(const SecureString& input); +std::vector DecodeBase32(const char* p, bool* pfInvalid = NULL); +std::string DecodeBase32(const std::string& str); +std::string EncodeBase32(const unsigned char* pch, size_t len); +std::string EncodeBase32(const std::string& str); + + +std::string i64tostr(int64_t n); +std::string itostr(int n); +int64_t atoi64(const char* psz); +int64_t atoi64(const std::string& str); +int atoi(const std::string& str); + +/** + * Convert string to signed 32-bit integer with strict parse error feedback. + * @returns true if the entire string could be parsed as valid integer, + * false if not the entire string could be parsed or when overflow or underflow occurred. + */ +bool ParseInt32(const std::string& str, int32_t *out); + +template +std::string HexStr(const T itbegin, const T itend, bool fSpaces=false) +{ + std::string rv; + static const char hexmap[16] = { '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; + rv.reserve((itend-itbegin)*3); + for(T it = itbegin; it < itend; ++it) + { + unsigned char val = (unsigned char)(*it); + if(fSpaces && it != itbegin) + rv.push_back(' '); + rv.push_back(hexmap[val>>4]); + rv.push_back(hexmap[val&15]); + } + + return rv; +} + +template +inline std::string HexStr(const T& vch, bool fSpaces=false) +{ + return HexStr(vch.begin(), vch.end(), fSpaces); +} + +/** + * Format a paragraph of text to a fixed width, adding spaces for + * indentation to any added line. + */ +std::string FormatParagraph(const std::string in, size_t width=79, size_t indent=0); + +/** + * Timing-attack-resistant comparison. + * Takes time proportional to length + * of first argument. + */ +template +bool TimingResistantEqual(const T& a, const T& b) +{ + if (b.size() == 0) return a.size() == 0; + size_t accumulator = a.size() ^ b.size(); + for (size_t i = 0; i < a.size(); i++) + accumulator |= a[i] ^ b[i%b.size()]; + return accumulator == 0; +} + +#endif // BITCOIN_UTILSTRENCODINGS_H diff --git a/src/version.cpp b/src/version.cpp index ef72d63..75be23a 100644 --- a/src/version.cpp +++ b/src/version.cpp @@ -8,7 +8,7 @@ // Name of client reported in the 'version' message. Report the same name // for both bitcoind and bitcoin-qt, to make it harder for attackers to // target servers or GUI users specifically. -const std::string CLIENT_NAME("Genius"); +const std::string CLIENT_NAME("MonkeyHouse"); // Client version number #define CLIENT_VERSION_SUFFIX "" diff --git a/src/version.h b/src/version.h index 50d19a2..d5772bf 100644 --- a/src/version.h +++ b/src/version.h @@ -30,21 +30,25 @@ static const int DATABASE_VERSION = 70509; // network protocol versioning // -static const int PROTOCOL_VERSION = 60020; +static const int PROTOCOL_VERSION = 61000; // intial proto version, to be increased after version/verack negotiation static const int INIT_PROTO_VERSION = 209; // disconnect from peers older than this proto version -static const int MIN_PEER_PROTO_VERSION = 60020; +static const int MIN_PEER_PROTO_VERSION = 209; + +static const int MIN_INSTANTX_PROTO_VERSION = 209; + +static const int MIN_MN_PROTO_VERSION = 209; // nTime field added to CAddress, starting with this version; // if possible, avoid requesting addresses nodes older than this static const int CADDR_TIME_VERSION = 31402; // only request blocks from nodes outside this range of versions -static const int NOBLKS_VERSION_START = 0; -static const int NOBLKS_VERSION_END = 60020; +static const int NOBLKS_VERSION_START = 209; +static const int NOBLKS_VERSION_END = 60000; // BIP 0031, pong message, is enabled for all versions AFTER this one static const int BIP0031_VERSION = 60000; diff --git a/src/wallet.cpp b/src/wallet.cpp index eea35ca..ce36795 100644 --- a/src/wallet.cpp +++ b/src/wallet.cpp @@ -13,6 +13,14 @@ #include "txdb.h" #include "ui_interface.h" #include "walletdb.h" +#include "crypter.h" +#include "key.h" +#include "spork.h" +#include "darksend.h" +#include "instantx.h" +#include "masternode.h" +#include "chainparams.h" +#include "smessage.h" #include #include @@ -26,7 +34,7 @@ int64_t nReserveBalance = 0; int64_t nMinimumInputValue = 0; static unsigned int GetStakeSplitAge() { return 9 * 24 * 60 * 60; } -static int64_t GetStakeCombineThreshold() { return 10000 * COIN; } +static int64_t GetStakeCombineThreshold() { return 50 * COIN; } int64_t gcd(int64_t n,int64_t m) { return m == 0 ? n : gcd(m, n % m); } static uint64_t CoinWeightCost(const COutput &out) @@ -50,6 +58,11 @@ struct CompareValueOnly } }; + + + + + CPubKey CWallet::GenerateNewKey() { AssertLockHeld(cs_wallet); // mapKeyMetadata @@ -150,8 +163,54 @@ bool CWallet::LoadCScript(const CScript& redeemScript) return CCryptoKeyStore::AddCScript(redeemScript); } -bool CWallet::Unlock(const SecureString& strWalletPassphrase) +bool CWallet::Lock() +{ + if (IsLocked()) + return true; + + if (fDebug) + printf("Locking wallet.\n"); + + { + LOCK(cs_wallet); + CWalletDB wdb(strWalletFile); + + // -- load encrypted spend_secret of stealth addresses + CStealthAddress sxAddrTemp; + std::set::iterator it; + for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it) + { + if (it->scan_secret.size() < 32) + continue; // stealth address is not owned + // -- CStealthAddress are only sorted on spend_pubkey + CStealthAddress &sxAddr = const_cast(*it); + if (fDebug) + printf("Recrypting stealth key %s\n", sxAddr.Encoded().c_str()); + + sxAddrTemp.scan_pubkey = sxAddr.scan_pubkey; + if (!wdb.ReadStealthAddress(sxAddrTemp)) + { + printf("Error: Failed to read stealth key from db %s\n", sxAddr.Encoded().c_str()); + continue; + } + sxAddr.spend_secret = sxAddrTemp.spend_secret; + }; + } + return LockKeyStore(); +}; + +bool CWallet::Unlock(const SecureString& strWalletPassphrase, bool anonymizeOnly) { + SecureString strWalletPassphraseFinal; + + if(!IsLocked()) + { + fWalletUnlockAnonymizeOnly = anonymizeOnly; + return true; + } + + strWalletPassphraseFinal = strWalletPassphrase; + CCrypter crypter; CKeyingMaterial vMasterKey; @@ -159,13 +218,18 @@ bool CWallet::Unlock(const SecureString& strWalletPassphrase) LOCK(cs_wallet); BOOST_FOREACH(const MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { - if(!crypter.SetKeyFromPassphrase(strWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) + if(!crypter.SetKeyFromPassphrase(strWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) - continue; // try another master key - if (CCryptoKeyStore::Unlock(vMasterKey)) - return true; + return false; + if (!CCryptoKeyStore::Unlock(vMasterKey)) + return false; + break; } + + fWalletUnlockAnonymizeOnly = anonymizeOnly; + UnlockStealthAddresses(vMasterKey); + return true; } return false; } @@ -173,7 +237,10 @@ bool CWallet::Unlock(const SecureString& strWalletPassphrase) bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase) { bool fWasLocked = IsLocked(); - + + SecureString strOldWalletPassphraseFinal; + strOldWalletPassphraseFinal = strOldWalletPassphrase; + { LOCK(cs_wallet); Lock(); @@ -182,11 +249,12 @@ bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, CKeyingMaterial vMasterKey; BOOST_FOREACH(MasterKeyMap::value_type& pMasterKey, mapMasterKeys) { - if(!crypter.SetKeyFromPassphrase(strOldWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) + if(!crypter.SetKeyFromPassphrase(strOldWalletPassphraseFinal, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod)) return false; if (!crypter.Decrypt(pMasterKey.second.vchCryptedKey, vMasterKey)) return false; - if (CCryptoKeyStore::Unlock(vMasterKey)) + if (CCryptoKeyStore::Unlock(vMasterKey) + && UnlockStealthAddresses(vMasterKey)) { int64_t nStartTime = GetTimeMillis(); crypter.SetKeyFromPassphrase(strNewWalletPassphrase, pMasterKey.second.vchSalt, pMasterKey.second.nDeriveIterations, pMasterKey.second.nDerivationMethod); @@ -208,6 +276,7 @@ bool CWallet::ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, CWalletDB(strWalletFile).WriteMasterKey(pMasterKey.first, pMasterKey.second); if (fWasLocked) Lock(); + return true; } } @@ -315,6 +384,34 @@ bool CWallet::EncryptWallet(const SecureString& strWalletPassphrase) exit(1); //We now probably have half of our keys encrypted in memory, and half not...die and let the user reload their unencrypted wallet. } + std::set::iterator it; + for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it) + { + if (it->scan_secret.size() < 32) + continue; // stealth address is not owned + // -- CStealthAddress is only sorted on spend_pubkey + CStealthAddress &sxAddr = const_cast(*it); + + if (fDebug) + printf("Encrypting stealth key %s\n", sxAddr.Encoded().c_str()); + + std::vector vchCryptedSecret; + + CSecret vchSecret; + vchSecret.resize(32); + memcpy(&vchSecret[0], &sxAddr.spend_secret[0], 32); + + uint256 iv = Hash(sxAddr.spend_pubkey.begin(), sxAddr.spend_pubkey.end()); + if (!EncryptSecret(vMasterKey, vchSecret, iv, vchCryptedSecret)) + { + printf("Error: Failed encrypting stealth key %s\n", sxAddr.Encoded().c_str()); + continue; + }; + + sxAddr.spend_secret = vchCryptedSecret; + pwalletdbEncryption->WriteStealthAddress(sxAddr); + }; + // Encryption was introduced in version 0.4.0 SetMinVersion(FEATURE_WALLETCRYPT, pwalletdbEncryption, true); @@ -574,9 +671,17 @@ bool CWallet::AddToWalletIfInvolvingMe(const CTransaction& tx, const CBlock* pbl LOCK(cs_wallet); bool fExisted = mapWallet.count(hash); if (fExisted && !fUpdate) return false; + + mapValue_t mapNarr; + FindStealthTransactions(tx, mapNarr); + if (fExisted || IsMine(tx) || IsFromMe(tx)) { CWalletTx wtx(this,tx); + + if (!mapNarr.empty()) + wtx.mapValue.insert(mapNarr.begin(), mapNarr.end()); + // Get merkle branch if transaction was found in a block if (pblock) wtx.SetMerkleBranch(pblock); @@ -648,6 +753,30 @@ int64_t CWallet::GetDebit(const CTxIn &txin) const return 0; } + +bool CWallet::IsDenominated(const CTxIn &txin) const +{ + { + LOCK(cs_wallet); + map::const_iterator mi = mapWallet.find(txin.prevout.hash); + if (mi != mapWallet.end()) + { + const CWalletTx& prev = (*mi).second; + if (txin.prevout.n < prev.vout.size()) return IsDenominatedAmount(prev.vout[txin.prevout.n].nValue); + } + } + return false; +} + +bool CWallet::IsDenominatedAmount(int64_t nInputAmount) const +{ + BOOST_FOREACH(int64_t d, darkSendDenominations) + if(nInputAmount == d) + return true; + return false; +} + + bool CWallet::IsChange(const CTxOut& txout) const { CTxDestination address; @@ -716,6 +845,7 @@ int CWalletTx::GetRequestCount() const void CWalletTx::GetAmounts(list >& listReceived, list >& listSent, int64_t& nFee, string& strSentAccount) const { + LOCK(pwallet->cs_wallet); nFee = 0; listReceived.clear(); listSent.clear(); @@ -743,8 +873,9 @@ void CWalletTx::GetAmounts(list >& listReceived, if (nDebit > 0) { // Don't report 'change' txouts - if (pwallet->IsChange(txout)) - continue; + // GENIUSNOTE: CoinControl possible fix related... with HD wallet we need to report change? + //if (pwallet->IsChange(txout)) + // continue; fIsMine = pwallet->IsMine(txout); } else if (!(fIsMine = pwallet->IsMine(txout))) @@ -773,6 +904,7 @@ void CWalletTx::GetAmounts(list >& listReceived, void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nReceived, int64_t& nSent, int64_t& nFee) const { + LOCK(pwallet->cs_wallet); nReceived = nSent = nFee = 0; int64_t allFee; @@ -788,7 +920,7 @@ void CWalletTx::GetAccountAmounts(const string& strAccount, int64_t& nReceived, nFee = allFee; } { - LOCK(pwallet->cs_wallet); + BOOST_FOREACH(const PAIRTYPE(CTxDestination,int64_t)& r, listReceived) { if (pwallet->mapAddressBook.count(r.first)) @@ -1063,6 +1195,168 @@ int64_t CWallet::GetBalance() const return nTotal; } +int64_t CWallet::GetBalanceNoLocks() const +{ + int64_t nTotal = 0; + { + for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) + { + const CWalletTx* pcoin = &(*it).second; + if (pcoin->IsTrusted()) + nTotal += pcoin->GetAvailableCredit(); + } + } + + return nTotal; +} + +CAmount CWallet::GetAnonymizedBalance() const +{ + int64_t nTotal = 0; + { + LOCK(cs_wallet); + for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) + { + const CWalletTx* pcoin = &(*it).second; + + if (pcoin->IsTrusted()) + { + int nDepth = pcoin->GetDepthInMainChain(); + + for (unsigned int i = 0; i < pcoin->vout.size(); i++) { + //isminetype mine = IsMine(pcoin->vout[i]); + bool mine = IsMine(pcoin->vout[i]); + //COutput out = COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO); + COutput out = COutput(pcoin, i, nDepth, mine); + CTxIn vin = CTxIn(out.tx->GetHash(), out.i); + + //if(IsSpent(out.tx->GetHash(), i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; + if(pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; + + int rounds = GetInputDarksendRounds(vin); + if(rounds >= nDarksendRounds){ + nTotal += pcoin->vout[i].nValue; + } + } + } + } + } + + return nTotal; +} + +double CWallet::GetAverageAnonymizedRounds() const +{ + double fTotal = 0; + double fCount = 0; + + { + LOCK(cs_wallet); + for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) + { + const CWalletTx* pcoin = &(*it).second; + + if (pcoin->IsTrusted()) + { + int nDepth = pcoin->GetDepthInMainChain(); + + for (unsigned int i = 0; i < pcoin->vout.size(); i++) { + //isminetype mine = IsMine(pcoin->vout[i]); + bool mine = IsMine(pcoin->vout[i]); + //COutput out = COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO); + COutput out = COutput(pcoin, i, nDepth, mine); + CTxIn vin = CTxIn(out.tx->GetHash(), out.i); + + //if(IsSpent(out.tx->GetHash(), i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; + if(pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; + + int rounds = GetInputDarksendRounds(vin); + fTotal += (float)rounds; + fCount += 1; + } + } + } + } + + if(fCount == 0) return 0; + + return fTotal/fCount; +} + +CAmount CWallet::GetNormalizedAnonymizedBalance() const +{ + int64_t nTotal = 0; + + { + LOCK(cs_wallet); + for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) + { + const CWalletTx* pcoin = &(*it).second; + + if (pcoin->IsTrusted()) + { + int nDepth = pcoin->GetDepthInMainChain(); + + for (unsigned int i = 0; i < pcoin->vout.size(); i++) { + //isminetype mine = IsMine(pcoin->vout[i]); + bool mine = IsMine(pcoin->vout[i]); + //COutput out = COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO); + COutput out = COutput(pcoin, i, nDepth, mine); + CTxIn vin = CTxIn(out.tx->GetHash(), out.i); + + //if(IsSpent(out.tx->GetHash(), i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; + if(pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; + + int rounds = GetInputDarksendRounds(vin); + nTotal += pcoin->vout[i].nValue * rounds / nDarksendRounds; + } + } + } + } + + return nTotal; +} + +CAmount CWallet::GetDenominatedBalance(bool onlyDenom, bool onlyUnconfirmed) const +{ + int64_t nTotal = 0; + { + LOCK(cs_wallet); + for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) + { + const CWalletTx* pcoin = &(*it).second; + + int nDepth = pcoin->GetDepthInMainChain(); + + // skip conflicted + if(nDepth < 0) continue; + + bool unconfirmed = (!IsFinalTx(*pcoin) || (!pcoin->IsTrusted() && nDepth == 0)); + if(onlyUnconfirmed != unconfirmed) continue; + + for (unsigned int i = 0; i < pcoin->vout.size(); i++) + { + //isminetype mine = IsMine(pcoin->vout[i]); + //bool mine = IsMine(pcoin->vout[i]); + //COutput out = COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO); + //COutput out = COutput(pcoin, i, nDepth, mine); + + //if(IsSpent(out.tx->GetHash(), i)) continue; + if(pcoin->IsSpent(i)) continue; + if(!IsMine(pcoin->vout[i])) continue; + if(onlyDenom != IsDenominatedAmount(pcoin->vout[i].nValue)) continue; + + nTotal += pcoin->vout[i].nValue; + } + } + } + + + + return nTotal; +} + + int64_t CWallet::GetUnconfirmedBalance() const { int64_t nTotal = 0; @@ -1093,8 +1387,9 @@ int64_t CWallet::GetImmatureBalance() const return nTotal; } + // populate vCoins with vector of spendable COutputs -void CWallet::AvailableCoins(vector& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl) const +void CWallet::AvailableCoins(vector& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, AvailableCoinsType coin_type, bool useIX) const { vCoins.clear(); @@ -1117,14 +1412,113 @@ void CWallet::AvailableCoins(vector& vCoins, bool fOnlyConfirmed, const continue; int nDepth = pcoin->GetDepthInMainChain(); - if (nDepth < 0) + if (nDepth <= 0) // GENIUSNOTE: coincontrol fix / ignore 0 confirm continue; - for (unsigned int i = 0; i < pcoin->vout.size(); i++) + /* for (unsigned int i = 0; i < pcoin->vout.size(); i++) + if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue && + (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) + vCoins.push_back(COutput(pcoin, i, nDepth));*/ + // do not use IX for inputs that have less then 6 blockchain confirmations + if (useIX && nDepth < 6) + continue; + + for (unsigned int i = 0; i < pcoin->vout.size(); i++) { + bool found = false; + if(coin_type == ONLY_DENOMINATED) { + //should make this a vector + + found = IsDenominatedAmount(pcoin->vout[i].nValue); + } else if(coin_type == ONLY_NONDENOMINATED || coin_type == ONLY_NONDENOMINATED_NOTMN) { + found = true; + if (IsCollateralAmount(pcoin->vout[i].nValue)) continue; // do not use collateral amounts + found = !IsDenominatedAmount(pcoin->vout[i].nValue); + if(found && coin_type == ONLY_NONDENOMINATED_NOTMN) found = (pcoin->vout[i].nValue != 5000*COIN); // do not use MN funds + } else { + found = true; + } + if(!found) continue; + + //isminetype mine = IsMine(pcoin->vout[i]); + bool mine = IsMine(pcoin->vout[i]); + + //if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO && + // !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 && + // (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) + // vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO)); + //if (!(IsSpent(wtxid, i)) && mine && + if (!(pcoin->IsSpent(i)) && mine && + !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 && + (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) + vCoins.push_back(COutput(pcoin, i, nDepth, mine)); + } + } + } +} + +void CWallet::AvailableCoinsMN(vector& vCoins, bool fOnlyConfirmed, const CCoinControl *coinControl, AvailableCoinsType coin_type, bool useIX) const +{ + vCoins.clear(); + + { + LOCK2(cs_main, cs_wallet); + for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) + { + const CWalletTx* pcoin = &(*it).second; + + if (!IsFinalTx(*pcoin)) + continue; + + if (fOnlyConfirmed && !pcoin->IsTrusted()) + continue; + + if (pcoin->IsCoinBase() && pcoin->GetBlocksToMaturity() > 0) + continue; + + if(pcoin->IsCoinStake() && pcoin->GetBlocksToMaturity() > 0) + continue; + + int nDepth = pcoin->GetDepthInMainChain(); + if (nDepth <= 0) // GENIUSNOTE: coincontrol fix / ignore 0 confirm + continue; + + /* for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue && (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) - vCoins.push_back(COutput(pcoin, i, nDepth)); + vCoins.push_back(COutput(pcoin, i, nDepth));*/ + // do not use IX for inputs that have less then 6 blockchain confirmations + if (useIX && nDepth < 6) + continue; + for (unsigned int i = 0; i < pcoin->vout.size(); i++) { + bool found = false; + if(coin_type == ONLY_DENOMINATED) { + //should make this a vector + + found = IsDenominatedAmount(pcoin->vout[i].nValue); + } else if(coin_type == ONLY_NONDENOMINATED || coin_type == ONLY_NONDENOMINATED_NOTMN) { + found = true; + if (IsCollateralAmount(pcoin->vout[i].nValue)) continue; // do not use collateral amounts + found = !IsDenominatedAmount(pcoin->vout[i].nValue); + if(found && coin_type == ONLY_NONDENOMINATED_NOTMN) found = (pcoin->vout[i].nValue != 5000*COIN); // do not use MN funds + } else { + found = true; + } + if(!found) continue; + + //isminetype mine = IsMine(pcoin->vout[i]); + bool mine = IsMine(pcoin->vout[i]); + + //if (!(IsSpent(wtxid, i)) && mine != ISMINE_NO && + // !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 && + // (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) + // vCoins.push_back(COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO)); + //if (!(IsSpent(wtxid, i)) && mine && + if (!(pcoin->IsSpent(i)) && + !IsLockedCoin((*it).first, i) && pcoin->vout[i].nValue > 0 && + (!coinControl || !coinControl->HasSelected() || coinControl->IsSelected((*it).first, i))) + vCoins.push_back(COutput(pcoin, i, nDepth, mine)); + } } } } @@ -1152,7 +1546,7 @@ void CWallet::AvailableCoinsForStaking(vector& vCoins, unsigned int nSp for (unsigned int i = 0; i < pcoin->vout.size(); i++) if (!(pcoin->IsSpent(i)) && IsMine(pcoin->vout[i]) && pcoin->vout[i].nValue >= nMinimumInputValue) - vCoins.push_back(COutput(pcoin, i, nDepth)); + vCoins.push_back(COutput(pcoin, i, nDepth, true)); } } } @@ -1475,6 +1869,23 @@ bool CWallet::SelectCoinsMinConfByCoinAge(int64_t nTargetValue, unsigned int nSp return true; } +// TODO: find appropriate place for this sort function +// move denoms down +bool less_then_denom (const COutput& out1, const COutput& out2) +{ + const CWalletTx *pcoin1 = out1.tx; + const CWalletTx *pcoin2 = out2.tx; + + bool found1 = false; + bool found2 = false; + BOOST_FOREACH(int64_t d, darkSendDenominations) // loop through predefined denoms + { + if(pcoin1->vout[out1.i].nValue == d) found1 = true; + if(pcoin2->vout[out2.i].nValue == d) found2 = true; + } + return (!found1 && found2); +} + bool CWallet::SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, vector vCoins, set >& setCoinsRet, int64_t& nValueRet) const { setCoinsRet.clear(); @@ -1489,6 +1900,16 @@ bool CWallet::SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, random_shuffle(vCoins.begin(), vCoins.end(), GetRandInt); + // move denoms down on the list + sort(vCoins.begin(), vCoins.end(), less_then_denom); + + // try to find nondenom first to prevent unneeded spending of mixed coins + for (unsigned int tryDenom = 0; tryDenom < 2; tryDenom++) + { + if (fDebug) LogPrint("selectcoins", "tryDenom: %d\n", tryDenom); + vValue.clear(); + nTotalLower = 0; + BOOST_FOREACH(COutput output, vCoins) { const CWalletTx *pcoin = output.tx; @@ -1504,6 +1925,8 @@ bool CWallet::SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, int64_t n = pcoin->vout[i].nValue; + if (tryDenom == 0 && IsDenominatedAmount(n)) continue; // we don't want denom values on first run + pair > coin = make_pair(n,make_pair(pcoin, i)); if (n == nTargetValue) @@ -1575,18 +1998,46 @@ bool CWallet::SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, } return true; + } + return false; } -bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl) const +bool CWallet::SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, set >& setCoinsRet, int64_t& nValueRet, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX) const { vector vCoins; AvailableCoins(vCoins, true, coinControl); + //if we're doing only denominated, we need to round up to the nearest .1GENIUS + if(coin_type == ONLY_DENOMINATED){ + // Make outputs by looping through denominations, from large to small + BOOST_FOREACH(int64_t v, darkSendDenominations) + { + int added = 0; + BOOST_FOREACH(const COutput& out, vCoins) + { + if(out.tx->vout[out.i].nValue == v //make sure it's the denom we're looking for + && nValueRet + out.tx->vout[out.i].nValue < nTargetValue + (0.1*COIN)+100 //round the amount up to .1GENIUS over + && added <= 100){ //don't add more than 100 of one denom type + CTxIn vin = CTxIn(out.tx->GetHash(),out.i); + int rounds = GetInputDarksendRounds(vin); + // make sure it's actually anonymized + if(rounds < nDarksendRounds) continue; + nValueRet += out.tx->vout[out.i].nValue; + setCoinsRet.insert(make_pair(out.tx, out.i)); + added++; + } + } + } + return (nValueRet >= nTargetValue); + } + // coin control -> return all selected outputs (we want all selected to go into the transaction for sure) if (coinControl && coinControl->HasSelected()) { BOOST_FOREACH(const COutput& out, vCoins) { + if(!out.fSpendable) + continue; nValueRet += out.tx->vout[out.i].nValue; setCoinsRet.insert(make_pair(out.tx, out.i)); } @@ -1640,43 +2091,370 @@ bool CWallet::SelectCoinsForStaking(int64_t nTargetValue, unsigned int nSpendTim return true; } -bool CWallet::CreateTransaction(const vector >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl) +struct CompareByPriority { - int64_t nValue = 0; - BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend) + bool operator()(const COutput& t1, + const COutput& t2) const { - if (nValue < 0) - return false; - nValue += s.second; + return t1.Priority() > t2.Priority(); } - if (vecSend.empty() || nValue < 0) - return false; +}; - wtxNew.BindWallet(this); +bool CWallet::SelectCoinsByDenominations(int nDenom, int64_t nValueMin, int64_t nValueMax, std::vector& setCoinsRet, vector& setCoinsRet2, int64_t& nValueRet, int nDarksendRoundsMin, int nDarksendRoundsMax) +{ + setCoinsRet.clear(); + nValueRet = 0; - { - LOCK2(cs_main, cs_wallet); - // txdb must be opened before the mapWallet lock - CTxDB txdb("r"); - { - nFeeRet = nTransactionFee; - while (true) - { - wtxNew.vin.clear(); - wtxNew.vout.clear(); - wtxNew.fFromMe = true; + setCoinsRet2.clear(); + vector vCoins; + AvailableCoins(vCoins); - int64_t nTotalValue = nValue + nFeeRet; - double dPriority = 0; - // vouts to the payees - BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend) - wtxNew.vout.push_back(CTxOut(s.second, s.first)); + //order the array so fees are first, then denominated money, then the rest. + std::random_shuffle(vCoins.rbegin(), vCoins.rend()); - // Choose coins to use - set > setCoins; - int64_t nValueIn = 0; - if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl)) - return false; + //keep track of each denomination that we have + bool fFound100000 = false; + bool fFound10000 = false; + bool fFound1000 = false; + bool fFound100 = false; + bool fFound10 = false; + bool fFound1 = false; + bool fFoundDot1 = false; + + //Check to see if any of the denomination are off, in that case mark them as fulfilled + + + + if(!(nDenom & (1 << 0))) fFound100000 = true; + if(!(nDenom & (1 << 1))) fFound10000 = true; + if(!(nDenom & (1 << 2))) fFound1000 = true; + if(!(nDenom & (1 << 3))) fFound100 = true; + if(!(nDenom & (1 << 4))) fFound10 = true; + if(!(nDenom & (1 << 5))) fFound1 = true; + if(!(nDenom & (1 << 6))) fFoundDot1 = true; + + BOOST_FOREACH(const COutput& out, vCoins) + { + //there's no reason to allow inputs less than 1 COIN into DS (other than denominations smaller than that amount) + if(out.tx->vout[out.i].nValue < 1*COIN && out.tx->vout[out.i].nValue != (.1*COIN)+100) continue; + if(fMasterNode && out.tx->vout[out.i].nValue == 5000*COIN) continue; //masternode input + if(nValueRet + out.tx->vout[out.i].nValue <= nValueMax){ + bool fAccepted = false; + + // Function returns as follows: + // + // bit 0 - 100GENIUS+1 ( bit on if present ) + // bit 1 - 10GENIUS+1 + // bit 2 - 1GENIUS+1 + // bit 3 - .1GENIUS+1 + + CTxIn vin = CTxIn(out.tx->GetHash(),out.i); + + int rounds = GetInputDarksendRounds(vin); + if(rounds >= nDarksendRoundsMax) continue; + if(rounds < nDarksendRoundsMin) continue; + + if(fFound100000 && fFound10000 && fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1){ //if fulfilled + //we can return this for submission + if(nValueRet >= nValueMin){ + //random reduce the max amount we'll submit for anonymity + nValueMax -= (rand() % (nValueMax/5)); + //on average use 50% of the inputs or less + int r = (rand() % (int)vCoins.size()); + if((int)setCoinsRet.size() > r) return true; + } + //Denomination criterion has been met, we can take any matching denominations + if((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((100000*COIN) +100000000)) {fAccepted = true;} + else if((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((10000*COIN) +10000000)) {fAccepted = true;} + else if((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((1000*COIN) +1000000)) {fAccepted = true;} + else if((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((100*COIN) +100000)) {fAccepted = true;} + else if((nDenom & (1 << 4)) && out.tx->vout[out.i].nValue == ((10*COIN) +10000)) {fAccepted = true;} + else if((nDenom & (1 << 5)) && out.tx->vout[out.i].nValue == ((1*COIN) +1000)) {fAccepted = true;} + else if((nDenom & (1 << 6)) && out.tx->vout[out.i].nValue == ((.1*COIN) +100)) {fAccepted = true;} + } else { + //Criterion has not been satisfied, we will only take 1 of each until it is. + if((nDenom & (1 << 0)) && out.tx->vout[out.i].nValue == ((100000*COIN) +100000000)) {fAccepted = true; fFound100000 = true;} + else if((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((10000*COIN) +10000000)) {fAccepted = true; fFound10000 = true;} + else if((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((1000*COIN) +1000000)) {fAccepted = true; fFound1000 = true;} + else if((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((100*COIN) +100000)) {fAccepted = true; fFound100 = true;} + else if((nDenom & (1 << 1)) && out.tx->vout[out.i].nValue == ((10*COIN) +10000)) {fAccepted = true; fFound10 = true;} + else if((nDenom & (1 << 2)) && out.tx->vout[out.i].nValue == ((1*COIN) +1000)) {fAccepted = true; fFound1 = true;} + else if((nDenom & (1 << 3)) && out.tx->vout[out.i].nValue == ((.1*COIN) +100)) {fAccepted = true; fFoundDot1 = true;} + } + if(!fAccepted) continue; + + vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey + nValueRet += out.tx->vout[out.i].nValue; + setCoinsRet.push_back(vin); + setCoinsRet2.push_back(out); + } + } + + return (nValueRet >= nValueMin && fFound100000 && fFound10000 && fFound1000 && fFound100 && fFound10 && fFound1 && fFoundDot1); +} + +bool CWallet::SelectCoinsDark(int64_t nValueMin, int64_t nValueMax, std::vector& setCoinsRet, int64_t& nValueRet, int nDarksendRoundsMin, int nDarksendRoundsMax) const +{ + CCoinControl *coinControl=NULL; + + setCoinsRet.clear(); + nValueRet = 0; + + vector vCoins; + AvailableCoins(vCoins, true, coinControl, nDarksendRoundsMin < 0 ? ONLY_NONDENOMINATED_NOTMN : ONLY_DENOMINATED); + + set > setCoinsRet2; + + //order the array so fees are first, then denominated money, then the rest. + sort(vCoins.rbegin(), vCoins.rend(), CompareByPriority()); + + //the first thing we get is a fee input, then we'll use as many denominated as possible. then the rest + BOOST_FOREACH(const COutput& out, vCoins) + { + //there's no reason to allow inputs less than 1 COIN into DS (other than denominations smaller than that amount) + if(out.tx->vout[out.i].nValue < 1*COIN && out.tx->vout[out.i].nValue != (.1*COIN)+100) continue; + if(fMasterNode && out.tx->vout[out.i].nValue == 5000*COIN) continue; //masternode input + + if(nValueRet + out.tx->vout[out.i].nValue <= nValueMax){ + CTxIn vin = CTxIn(out.tx->GetHash(),out.i); + + int rounds = GetInputDarksendRounds(vin); + if(rounds >= nDarksendRoundsMax) continue; + if(rounds < nDarksendRoundsMin) continue; + + vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey + nValueRet += out.tx->vout[out.i].nValue; + setCoinsRet.push_back(vin); + setCoinsRet2.insert(make_pair(out.tx, out.i)); + } + } + + // if it's more than min, we're good to return + if(nValueRet >= nValueMin) return true; + + return false; +} + +bool CWallet::SelectCoinsCollateral(std::vector& setCoinsRet, int64_t& nValueRet) const +{ + vector vCoins; + + //printf(" selecting coins for collateral\n"); + AvailableCoins(vCoins); + + //printf("found coins %d\n", (int)vCoins.size()); + + set > setCoinsRet2; + + BOOST_FOREACH(const COutput& out, vCoins) + { + // collateral inputs will always be a multiple of DARSEND_COLLATERAL, up to five + if(IsCollateralAmount(out.tx->vout[out.i].nValue)) + { + CTxIn vin = CTxIn(out.tx->GetHash(),out.i); + + vin.prevPubKey = out.tx->vout[out.i].scriptPubKey; // the inputs PubKey + nValueRet += out.tx->vout[out.i].nValue; + setCoinsRet.push_back(vin); + setCoinsRet2.insert(make_pair(out.tx, out.i)); + return true; + } + } + + return false; +} + +int CWallet::CountInputsWithAmount(int64_t nInputAmount) +{ + int64_t nTotal = 0; + { + LOCK(cs_wallet); + for (map::const_iterator it = mapWallet.begin(); it != mapWallet.end(); ++it) + { + const CWalletTx* pcoin = &(*it).second; + if (pcoin->IsTrusted()){ + int nDepth = pcoin->GetDepthInMainChain(); + + for (unsigned int i = 0; i < pcoin->vout.size(); i++) { + //isminetype mine = IsMine(pcoin->vout[i]); + bool mine = IsMine(pcoin->vout[i]); + //COutput out = COutput(pcoin, i, nDepth, (mine & ISMINE_SPENDABLE) != ISMINE_NO); + COutput out = COutput(pcoin, i, nDepth, mine); + CTxIn vin = CTxIn(out.tx->GetHash(), out.i); + + if(out.tx->vout[out.i].nValue != nInputAmount) continue; + if(!IsDenominatedAmount(pcoin->vout[i].nValue)) continue; + //if(IsSpent(out.tx->GetHash(), i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; + if(pcoin->IsSpent(i) || !IsMine(pcoin->vout[i]) || !IsDenominated(vin)) continue; + + nTotal++; + } + } + } + } + + return nTotal; +} + +bool CWallet::HasCollateralInputs() const +{ + vector vCoins; + AvailableCoins(vCoins); + + int nFound = 0; + BOOST_FOREACH(const COutput& out, vCoins) + if(IsCollateralAmount(out.tx->vout[out.i].nValue)) nFound++; + + return nFound > 1; // should have more than one just in case +} + +bool CWallet::IsCollateralAmount(int64_t nInputAmount) const +{ + return nInputAmount == (DARKSEND_COLLATERAL * 5)+DARKSEND_FEE || + nInputAmount == (DARKSEND_COLLATERAL * 4)+DARKSEND_FEE || + nInputAmount == (DARKSEND_COLLATERAL * 3)+DARKSEND_FEE || + nInputAmount == (DARKSEND_COLLATERAL * 2)+DARKSEND_FEE || + nInputAmount == (DARKSEND_COLLATERAL * 1)+DARKSEND_FEE; +} + +bool CWallet::SelectCoinsWithoutDenomination(int64_t nTargetValue, set >& setCoinsRet, int64_t& nValueRet) const +{ + CCoinControl *coinControl=NULL; + + vector vCoins; + AvailableCoins(vCoins, true, coinControl, ONLY_NONDENOMINATED); + + BOOST_FOREACH(const COutput& out, vCoins) + { + nValueRet += out.tx->vout[out.i].nValue; + setCoinsRet.insert(make_pair(out.tx, out.i)); + } + return (nValueRet >= nTargetValue); +} + +bool CWallet::CreateCollateralTransaction(CTransaction& txCollateral, std::string strReason) +{ + /* + To doublespend a collateral transaction, it will require a fee higher than this. So there's + still a significant cost. + */ + int64_t nFeeRet = 0.001*COIN; + + txCollateral.vin.clear(); + txCollateral.vout.clear(); + + CReserveKey reservekey(this); + int64_t nValueIn2 = 0; + std::vector vCoinsCollateral; + + if (!SelectCoinsCollateral(vCoinsCollateral, nValueIn2)) + { + strReason = "Error: Darksend requires a collateral transaction and could not locate an acceptable input!"; + return false; + } + + // make our change address + CScript scriptChange; + CPubKey vchPubKey; + assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked + scriptChange =GetScriptForDestination(vchPubKey.GetID()); + reservekey.KeepKey(); + + BOOST_FOREACH(CTxIn v, vCoinsCollateral) + txCollateral.vin.push_back(v); + + if(nValueIn2 - DARKSEND_COLLATERAL - nFeeRet > 0) { + //pay collateral charge in fees + CTxOut vout3 = CTxOut(nValueIn2 - DARKSEND_COLLATERAL, scriptChange); + txCollateral.vout.push_back(vout3); + } + + int vinNumber = 0; + BOOST_FOREACH(CTxIn v, txCollateral.vin) { + if(!SignSignature(*this, v.prevPubKey, txCollateral, vinNumber, int(SIGHASH_ALL|SIGHASH_ANYONECANPAY))) { + BOOST_FOREACH(CTxIn v, vCoinsCollateral) + UnlockCoin(v.prevout); + + strReason = "CDarkSendPool::Sign - Unable to sign collateral transaction! \n"; + return false; + } + vinNumber++; + } + + return true; +} + +bool CWallet::ConvertList(std::vector vCoins, std::vector& vecAmounts) +{ + BOOST_FOREACH(CTxIn i, vCoins){ + if (mapWallet.count(i.prevout.hash)) + { + CWalletTx& wtx = mapWallet[i.prevout.hash]; + if(i.prevout.n < wtx.vout.size()){ + vecAmounts.push_back(wtx.vout[i.prevout.n].nValue); + } + } else { + LogPrintf("ConvertList -- Couldn't find transaction\n"); + } + } + return true; +} + + +bool CWallet::CreateTransaction(const vector >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, int32_t& nChangePos, std::string& strFailReason, const CCoinControl* coinControl, AvailableCoinsType coin_type, bool useIX) +{ + int64_t nValue = 0; + BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend) + { + if (nValue < 0) + return false; + nValue += s.second; + } + if (vecSend.empty() || nValue < 0) + return false; + + wtxNew.BindWallet(this); + CTransaction txNew; + + { + LOCK2(cs_main, cs_wallet); + // txdb must be opened before the mapWallet lock + CTxDB txdb("r"); + { + nFeeRet = nTransactionFee; + while (true) + { + wtxNew.vin.clear(); + wtxNew.vout.clear(); + wtxNew.fFromMe = true; + + int64_t nTotalValue = nValue + nFeeRet; + double dPriority = 0; + // vouts to the payees + BOOST_FOREACH (const PAIRTYPE(CScript, int64_t)& s, vecSend) + wtxNew.vout.push_back(CTxOut(s.second, s.first)); + + // Choose coins to use + set > setCoins; + int64_t nValueIn = 0; + if (!SelectCoins(nTotalValue, wtxNew.nTime, setCoins, nValueIn, coinControl)) + { + if(coin_type == ALL_COINS) { + strFailReason = _("Insufficient funds."); + } else if (coin_type == ONLY_NONDENOMINATED) { + strFailReason = _("Unable to locate enough Darksend non-denominated funds for this transaction."); + } else if (coin_type == ONLY_NONDENOMINATED_NOTMN) { + strFailReason = _("Unable to locate enough Darksend non-denominated funds for this transaction that are not equal 1000 GENIUS."); + } else { + strFailReason = _("Unable to locate enough Darksend denominated funds for this transaction."); + strFailReason += _("Darksend uses exact denominated amounts to send funds, you might simply need to anonymize some more coins."); + } + + if(useIX){ + strFailReason += _("InstantX requires inputs with at least 6 confirmations, you might need to wait a few minutes and try again."); + } + return false; + } BOOST_FOREACH(PAIRTYPE(const CWalletTx*, unsigned int) pcoin, setCoins) { int64_t nCredit = pcoin.first->vout[pcoin.second].nValue; @@ -1715,7 +2493,20 @@ bool CWallet::CreateTransaction(const vector >& vecSend, // Insert change txn at random position: vector::iterator position = wtxNew.vout.begin()+GetRandInt(wtxNew.vout.size()); + + // -- don't put change output between value and narration outputs + if (position > wtxNew.vout.begin() && position < wtxNew.vout.end()) + { + while (position > wtxNew.vout.begin()) + { + if (position->nValue != 0) + break; + position--; + }; + }; + wtxNew.vout.insert(position, CTxOut(nChange, scriptChange)); + nChangePos = std::distance(wtxNew.vout.begin(), position); } else reservekey.ReturnKey(); @@ -1757,13 +2548,750 @@ bool CWallet::CreateTransaction(const vector >& vecSend, return true; } -bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl) +bool CWallet::CreateTransaction(CScript scriptPubKey, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl) { vector< pair > vecSend; vecSend.push_back(make_pair(scriptPubKey, nValue)); - return CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, coinControl); + + if (sNarr.length() > 0) + { + std::vector vNarr(sNarr.c_str(), sNarr.c_str() + sNarr.length()); + std::vector vNDesc; + + vNDesc.resize(2); + vNDesc[0] = 'n'; + vNDesc[1] = 'p'; + + CScript scriptN = CScript() << OP_RETURN << vNDesc << OP_RETURN << vNarr; + + vecSend.push_back(make_pair(scriptN, 0)); + } + + // -- CreateTransaction won't place change between value and narr output. + // narration output will be for preceding output + + int nChangePos; + std::string strFailReason; + bool rv = CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, nChangePos, strFailReason, coinControl); + + // -- narration will be added to mapValue later in FindStealthTransactions From CommitTransaction + return rv; +} + + +bool CWallet::NewStealthAddress(std::string& sError, std::string& sLabel, CStealthAddress& sxAddr) +{ + ec_secret scan_secret; + ec_secret spend_secret; + + if (GenerateRandomSecret(scan_secret) != 0 + || GenerateRandomSecret(spend_secret) != 0) + { + sError = "GenerateRandomSecret failed."; + printf("Error CWallet::NewStealthAddress - %s\n", sError.c_str()); + return false; + }; + + ec_point scan_pubkey, spend_pubkey; + if (SecretToPublicKey(scan_secret, scan_pubkey) != 0) + { + sError = "Could not get scan public key."; + printf("Error CWallet::NewStealthAddress - %s\n", sError.c_str()); + return false; + }; + + if (SecretToPublicKey(spend_secret, spend_pubkey) != 0) + { + sError = "Could not get spend public key."; + printf("Error CWallet::NewStealthAddress - %s\n", sError.c_str()); + return false; + }; + + if (fDebug) + { + printf("getnewstealthaddress: "); + printf("scan_pubkey "); + for (uint32_t i = 0; i < scan_pubkey.size(); ++i) + printf("%02x", scan_pubkey[i]); + printf("\n"); + + printf("spend_pubkey "); + for (uint32_t i = 0; i < spend_pubkey.size(); ++i) + printf("%02x", spend_pubkey[i]); + printf("\n"); + }; + + + sxAddr.label = sLabel; + sxAddr.scan_pubkey = scan_pubkey; + sxAddr.spend_pubkey = spend_pubkey; + + sxAddr.scan_secret.resize(32); + memcpy(&sxAddr.scan_secret[0], &scan_secret.e[0], 32); + sxAddr.spend_secret.resize(32); + memcpy(&sxAddr.spend_secret[0], &spend_secret.e[0], 32); + + return true; +} + +bool CWallet::AddStealthAddress(CStealthAddress& sxAddr) +{ + LOCK(cs_wallet); + + // must add before changing spend_secret + stealthAddresses.insert(sxAddr); + + bool fOwned = sxAddr.scan_secret.size() == ec_secret_size; + + + + if (fOwned) + { + // -- owned addresses can only be added when wallet is unlocked + if (IsLocked()) + { + printf("Error: CWallet::AddStealthAddress wallet must be unlocked.\n"); + stealthAddresses.erase(sxAddr); + return false; + }; + + if (IsCrypted()) + { + std::vector vchCryptedSecret; + CSecret vchSecret; + vchSecret.resize(32); + memcpy(&vchSecret[0], &sxAddr.spend_secret[0], 32); + + uint256 iv = Hash(sxAddr.spend_pubkey.begin(), sxAddr.spend_pubkey.end()); + if (!EncryptSecret(vMasterKey, vchSecret, iv, vchCryptedSecret)) + { + printf("Error: Failed encrypting stealth key %s\n", sxAddr.Encoded().c_str()); + stealthAddresses.erase(sxAddr); + return false; + }; + sxAddr.spend_secret = vchCryptedSecret; + }; + }; + + + bool rv = CWalletDB(strWalletFile).WriteStealthAddress(sxAddr); + + if (rv) + NotifyAddressBookChanged(this, sxAddr, sxAddr.label, fOwned, CT_NEW); + + return rv; +} + +bool CWallet::UnlockStealthAddresses(const CKeyingMaterial& vMasterKeyIn) +{ + // -- decrypt spend_secret of stealth addresses + std::set::iterator it; + for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it) + { + if (it->scan_secret.size() < 32) + continue; // stealth address is not owned + + // -- CStealthAddress are only sorted on spend_pubkey + CStealthAddress &sxAddr = const_cast(*it); + + if (fDebug) + printf("Decrypting stealth key %s\n", sxAddr.Encoded().c_str()); + + CSecret vchSecret; + uint256 iv = Hash(sxAddr.spend_pubkey.begin(), sxAddr.spend_pubkey.end()); + if(!DecryptSecret(vMasterKeyIn, sxAddr.spend_secret, iv, vchSecret) + || vchSecret.size() != 32) + { + printf("Error: Failed decrypting stealth key %s\n", sxAddr.Encoded().c_str()); + continue; + }; + + ec_secret testSecret; + memcpy(&testSecret.e[0], &vchSecret[0], 32); + ec_point pkSpendTest; + + if (SecretToPublicKey(testSecret, pkSpendTest) != 0 + || pkSpendTest != sxAddr.spend_pubkey) + { + printf("Error: Failed decrypting stealth key, public key mismatch %s\n", sxAddr.Encoded().c_str()); + continue; + }; + + sxAddr.spend_secret.resize(32); + memcpy(&sxAddr.spend_secret[0], &vchSecret[0], 32); + }; + + CryptedKeyMap::iterator mi = mapCryptedKeys.begin(); + for (; mi != mapCryptedKeys.end(); ++mi) + { + CPubKey &pubKey = (*mi).second.first; + std::vector &vchCryptedSecret = (*mi).second.second; + if (vchCryptedSecret.size() != 0) + continue; + + CKeyID ckid = pubKey.GetID(); + CBitcoinAddress addr(ckid); + + StealthKeyMetaMap::iterator mi = mapStealthKeyMeta.find(ckid); + if (mi == mapStealthKeyMeta.end()) + { + printf("Error: No metadata found to add secret for %s\n", addr.ToString().c_str()); + continue; + }; + + CStealthKeyMetadata& sxKeyMeta = mi->second; + + CStealthAddress sxFind; + sxFind.scan_pubkey = sxKeyMeta.pkScan.Raw(); + + std::set::iterator si = stealthAddresses.find(sxFind); + if (si == stealthAddresses.end()) + { + printf("No stealth key found to add secret for %s\n", addr.ToString().c_str()); + continue; + }; + + if (fDebug) + printf("Expanding secret for %s\n", addr.ToString().c_str()); + + ec_secret sSpendR; + ec_secret sSpend; + ec_secret sScan; + + if (si->spend_secret.size() != ec_secret_size + || si->scan_secret.size() != ec_secret_size) + { + printf("Stealth address has no secret key for %s\n", addr.ToString().c_str()); + continue; + } + memcpy(&sScan.e[0], &si->scan_secret[0], ec_secret_size); + memcpy(&sSpend.e[0], &si->spend_secret[0], ec_secret_size); + + ec_point pkEphem = sxKeyMeta.pkEphem.Raw(); + if (StealthSecretSpend(sScan, pkEphem, sSpend, sSpendR) != 0) + { + printf("StealthSecretSpend() failed.\n"); + continue; + }; + + ec_point pkTestSpendR; + if (SecretToPublicKey(sSpendR, pkTestSpendR) != 0) + { + printf("SecretToPublicKey() failed.\n"); + continue; + }; + + CSecret vchSecret; + vchSecret.resize(ec_secret_size); + + memcpy(&vchSecret[0], &sSpendR.e[0], ec_secret_size); + CKey ckey; + + try { + ckey.Set(vchSecret.begin(), vchSecret.end(), true); + //ckey.SetSecret(vchSecret, true); + } catch (std::exception& e) { + printf("ckey.SetSecret() threw: %s.\n", e.what()); + continue; + }; + + CPubKey cpkT = ckey.GetPubKey(); + + if (!cpkT.IsValid()) + { + printf("cpkT is invalid.\n"); + continue; + }; + + if (cpkT != pubKey) + { + printf("Error: Generated secret does not match.\n"); + continue; + }; + + if (!ckey.IsValid()) + { + printf("Reconstructed key is invalid.\n"); + continue; + }; + + if (fDebug) + { + CKeyID keyID = cpkT.GetID(); + CBitcoinAddress coinAddress(keyID); + printf("Adding secret to key %s.\n", coinAddress.ToString().c_str()); + }; + + if (!AddKey(ckey)) + { + printf("AddKey failed.\n"); + continue; + }; + + if (!CWalletDB(strWalletFile).EraseStealthKeyMeta(ckid)) + printf("EraseStealthKeyMeta failed for %s\n", addr.ToString().c_str()); + }; + return true; } +bool CWallet::UpdateStealthAddress(std::string &addr, std::string &label, bool addIfNotExist) +{ + if (fDebug) + printf("UpdateStealthAddress %s\n", addr.c_str()); + + + CStealthAddress sxAddr; + + if (!sxAddr.SetEncoded(addr)) + return false; + + std::set::iterator it; + it = stealthAddresses.find(sxAddr); + + ChangeType nMode = CT_UPDATED; + CStealthAddress sxFound; + if (it == stealthAddresses.end()) + { + if (addIfNotExist) + { + sxFound = sxAddr; + sxFound.label = label; + stealthAddresses.insert(sxFound); + nMode = CT_NEW; + } else + { + printf("UpdateStealthAddress %s, not in set\n", addr.c_str()); + return false; + }; + } else + { + sxFound = const_cast(*it); + + if (sxFound.label == label) + { + // no change + return true; + }; + + it->label = label; // update in .stealthAddresses + + if (sxFound.scan_secret.size() == ec_secret_size) + { + printf("UpdateStealthAddress: todo - update owned stealth address.\n"); + return false; + }; + }; + + sxFound.label = label; + + if (!CWalletDB(strWalletFile).WriteStealthAddress(sxFound)) + { + printf("UpdateStealthAddress(%s) Write to db failed.\n", addr.c_str()); + return false; + }; + + bool fOwned = sxFound.scan_secret.size() == ec_secret_size; + NotifyAddressBookChanged(this, sxFound, sxFound.label, fOwned, nMode); + + return true; +} + +bool CWallet::CreateStealthTransaction(CScript scriptPubKey, int64_t nValue, std::vector& P, std::vector& narr, std::string& sNarr, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl) +{ + vector< pair > vecSend; + vecSend.push_back(make_pair(scriptPubKey, nValue)); + + CScript scriptP = CScript() << OP_RETURN << P; + if (narr.size() > 0) + scriptP = scriptP << OP_RETURN << narr; + + vecSend.push_back(make_pair(scriptP, 1)); + + // -- shuffle inputs, change output won't mix enough as it must be not fully random for plantext narrations + std::random_shuffle(vecSend.begin(), vecSend.end()); + + int nChangePos; + std::string strFailReason; + bool rv = CreateTransaction(vecSend, wtxNew, reservekey, nFeeRet, nChangePos, strFailReason, coinControl); + + // -- the change txn is inserted in a random pos, check here to match narr to output + if (rv && narr.size() > 0) + { + for (unsigned int k = 0; k < wtxNew.vout.size(); ++k) + { + if (wtxNew.vout[k].scriptPubKey != scriptPubKey + || wtxNew.vout[k].nValue != nValue) + continue; + + char key[64]; + if (snprintf(key, sizeof(key), "n_%u", k) < 1) + { + printf("CreateStealthTransaction(): Error creating narration key."); + break; + }; + wtxNew.mapValue[key] = sNarr; + break; + }; + }; + + return rv; +} + +string CWallet::SendStealthMoney(CScript scriptPubKey, int64_t nValue, std::vector& P, std::vector& narr, std::string& sNarr, CWalletTx& wtxNew, bool fAskFee) +{ + CReserveKey reservekey(this); + int64_t nFeeRequired; + + if (IsLocked()) + { + string strError = _("Error: Wallet locked, unable to create transaction "); + printf("SendStealthMoney() : %s", strError.c_str()); + return strError; + } + if (fWalletUnlockStakingOnly) + { + string strError = _("Error: Wallet unlocked for staking only, unable to create transaction."); + printf("SendStealthMoney() : %s", strError.c_str()); + return strError; + } + if (!CreateStealthTransaction(scriptPubKey, nValue, P, narr, sNarr, wtxNew, reservekey, nFeeRequired)) + { + string strError; + if (nValue + nFeeRequired > GetBalance()) + strError = strprintf(_("Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds "), FormatMoney(nFeeRequired).c_str()); + else + strError = _("Error: Transaction creation failed "); + printf("SendStealthMoney() : %s", strError.c_str()); + return strError; + } + + if (fAskFee && !uiInterface.ThreadSafeAskFee(nFeeRequired, _("Sending..."))) + return "ABORTED"; + + if (!CommitTransaction(wtxNew, reservekey)) + return _("Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here."); + + return ""; +} + +bool CWallet::SendStealthMoneyToDestination(CStealthAddress& sxAddress, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, std::string& sError, bool fAskFee) +{ + // -- Check amount + if (nValue <= 0) + { + sError = "Invalid amount"; + return false; + }; + if (nValue + nTransactionFee + (1) > GetBalance()) + { + sError = "Insufficient funds"; + return false; + }; + + + ec_secret ephem_secret; + ec_secret secretShared; + ec_point pkSendTo; + ec_point ephem_pubkey; + + if (GenerateRandomSecret(ephem_secret) != 0) + { + sError = "GenerateRandomSecret failed."; + return false; + }; + + if (StealthSecret(ephem_secret, sxAddress.scan_pubkey, sxAddress.spend_pubkey, secretShared, pkSendTo) != 0) + { + sError = "Could not generate receiving public key."; + return false; + }; + + CPubKey cpkTo(pkSendTo); + if (!cpkTo.IsValid()) + { + sError = "Invalid public key generated."; + return false; + }; + + CKeyID ckidTo = cpkTo.GetID(); + + CBitcoinAddress addrTo(ckidTo); + + if (SecretToPublicKey(ephem_secret, ephem_pubkey) != 0) + { + sError = "Could not generate ephem public key."; + return false; + }; + + if (fDebug) + { + printf("Stealth send to generated pubkey %"PRIszu": %s\n", pkSendTo.size(), HexStr(pkSendTo).c_str()); + printf("hash %s\n", addrTo.ToString().c_str()); + printf("ephem_pubkey %"PRIszu": %s\n", ephem_pubkey.size(), HexStr(ephem_pubkey).c_str()); + }; + + std::vector vchNarr; + if (sNarr.length() > 0) + { + SecMsgCrypter crypter; + crypter.SetKey(&secretShared.e[0], &ephem_pubkey[0]); + + if (!crypter.Encrypt((uint8_t*)&sNarr[0], sNarr.length(), vchNarr)) + { + sError = "Narration encryption failed."; + return false; + }; + + if (vchNarr.size() > 48) + { + sError = "Encrypted narration is too long."; + return false; + }; + }; + + // -- Parse Bitcoin address + CScript scriptPubKey; + scriptPubKey.SetDestination(addrTo.Get()); + + if ((sError = SendStealthMoney(scriptPubKey, nValue, ephem_pubkey, vchNarr, sNarr, wtxNew, fAskFee)) != "") + return false; + + + return true; +} + +bool CWallet::FindStealthTransactions(const CTransaction& tx, mapValue_t& mapNarr) +{ + if (fDebug) + LogPrintf("FindStealthTransactions() tx: %s\n", tx.GetHash().GetHex().c_str()); + + mapNarr.clear(); + + LOCK(cs_wallet); + ec_secret sSpendR; + ec_secret sSpend; + ec_secret sScan; + ec_secret sShared; + + ec_point pkExtracted; + + std::vector vchEphemPK; + std::vector vchDataB; + std::vector vchENarr; + opcodetype opCode; + char cbuf[256]; + + int32_t nOutputIdOuter = -1; + BOOST_FOREACH(const CTxOut& txout, tx.vout) + { + nOutputIdOuter++; + // -- for each OP_RETURN need to check all other valid outputs + + //printf("txout scriptPubKey %s\n", txout.scriptPubKey.ToString().c_str()); + CScript::const_iterator itTxA = txout.scriptPubKey.begin(); + + if (!txout.scriptPubKey.GetOp(itTxA, opCode, vchEphemPK) + || opCode != OP_RETURN) + continue; + else + if (!txout.scriptPubKey.GetOp(itTxA, opCode, vchEphemPK) + || vchEphemPK.size() != 33) + { + // -- look for plaintext narrations + if (vchEphemPK.size() > 1 + && vchEphemPK[0] == 'n' + && vchEphemPK[1] == 'p') + { + if (txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr) + && opCode == OP_RETURN + && txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr) + && vchENarr.size() > 0) + { + std::string sNarr = std::string(vchENarr.begin(), vchENarr.end()); + + snprintf(cbuf, sizeof(cbuf), "n_%d", nOutputIdOuter-1); // plaintext narration always matches preceding value output + mapNarr[cbuf] = sNarr; + } else + { + printf("Warning: FindStealthTransactions() tx: %s, Could not extract plaintext narration.\n", tx.GetHash().GetHex().c_str()); + }; + } + + continue; + } + + int32_t nOutputId = -1; + nStealth++; + BOOST_FOREACH(const CTxOut& txoutB, tx.vout) + { + nOutputId++; + + if (&txoutB == &txout) + continue; + + bool txnMatch = false; // only 1 txn will match an ephem pk + //printf("txoutB scriptPubKey %s\n", txoutB.scriptPubKey.ToString().c_str()); + + CTxDestination address; + if (!ExtractDestination(txoutB.scriptPubKey, address)) + continue; + + if (address.type() != typeid(CKeyID)) + continue; + + CKeyID ckidMatch = boost::get(address); + + if (HaveKey(ckidMatch)) // no point checking if already have key + continue; + + std::set::iterator it; + for (it = stealthAddresses.begin(); it != stealthAddresses.end(); ++it) + { + if (it->scan_secret.size() != ec_secret_size) + continue; // stealth address is not owned + + //printf("it->Encodeded() %s\n", it->Encoded().c_str()); + memcpy(&sScan.e[0], &it->scan_secret[0], ec_secret_size); + + if (StealthSecret(sScan, vchEphemPK, it->spend_pubkey, sShared, pkExtracted) != 0) + { + printf("StealthSecret failed.\n"); + continue; + }; + //printf("pkExtracted %"PRIszu": %s\n", pkExtracted.size(), HexStr(pkExtracted).c_str()); + + CPubKey cpkE(pkExtracted); + + if (!cpkE.IsValid()) + continue; + CKeyID ckidE = cpkE.GetID(); + + if (ckidMatch != ckidE) + continue; + + if (fDebug) + printf("Found stealth txn to address %s\n", it->Encoded().c_str()); + + if (IsLocked()) + { + if (fDebug) + printf("Wallet is locked, adding key without secret.\n"); + + // -- add key without secret + std::vector vchEmpty; + AddCryptedKey(cpkE, vchEmpty); + CKeyID keyId = cpkE.GetID(); + CBitcoinAddress coinAddress(keyId); + std::string sLabel = it->Encoded(); + SetAddressBookName(keyId, sLabel); + + CPubKey cpkEphem(vchEphemPK); + CPubKey cpkScan(it->scan_pubkey); + CStealthKeyMetadata lockedSkMeta(cpkEphem, cpkScan); + + if (!CWalletDB(strWalletFile).WriteStealthKeyMeta(keyId, lockedSkMeta)) + printf("WriteStealthKeyMeta failed for %s\n", coinAddress.ToString().c_str()); + + mapStealthKeyMeta[keyId] = lockedSkMeta; + nFoundStealth++; + } else + { + if (it->spend_secret.size() != ec_secret_size) + continue; + memcpy(&sSpend.e[0], &it->spend_secret[0], ec_secret_size); + + + if (StealthSharedToSecretSpend(sShared, sSpend, sSpendR) != 0) + { + printf("StealthSharedToSecretSpend() failed.\n"); + continue; + }; + + ec_point pkTestSpendR; + if (SecretToPublicKey(sSpendR, pkTestSpendR) != 0) + { + printf("SecretToPublicKey() failed.\n"); + continue; + }; + + CSecret vchSecret; + vchSecret.resize(ec_secret_size); + + memcpy(&vchSecret[0], &sSpendR.e[0], ec_secret_size); + CKey ckey; + + try { + ckey.Set(vchSecret.begin(), vchSecret.end(), true); + //ckey.SetSecret(vchSecret, true); + } catch (std::exception& e) { + printf("ckey.SetSecret() threw: %s.\n", e.what()); + continue; + }; + + CPubKey cpkT = ckey.GetPubKey(); + if (!cpkT.IsValid()) + { + printf("cpkT is invalid.\n"); + continue; + }; + + if (!ckey.IsValid()) + { + printf("Reconstructed key is invalid.\n"); + continue; + }; + + CKeyID keyID = cpkT.GetID(); + if (fDebug) + { + CBitcoinAddress coinAddress(keyID); + printf("Adding key %s.\n", coinAddress.ToString().c_str()); + }; + + if (!AddKey(ckey)) + { + printf("AddKey failed.\n"); + continue; + }; + + std::string sLabel = it->Encoded(); + SetAddressBookName(keyID, sLabel); + nFoundStealth++; + }; + + if (txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr) + && opCode == OP_RETURN + && txout.scriptPubKey.GetOp(itTxA, opCode, vchENarr) + && vchENarr.size() > 0) + { + SecMsgCrypter crypter; + crypter.SetKey(&sShared.e[0], &vchEphemPK[0]); + std::vector vchNarr; + if (!crypter.Decrypt(&vchENarr[0], vchENarr.size(), vchNarr)) + { + printf("Decrypt narration failed.\n"); + continue; + }; + std::string sNarr = std::string(vchNarr.begin(), vchNarr.end()); + + snprintf(cbuf, sizeof(cbuf), "n_%d", nOutputId); + mapNarr[cbuf] = sNarr; + }; + + txnMatch = true; + break; + }; + if (txnMatch) + break; + }; + }; + + return true; +}; + + + + uint64_t CWallet::GetStakeWeight() const { // Choose coins to use @@ -1901,7 +3429,7 @@ bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int vwtxPrev.push_back(pcoin.first); txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); - if (GetWeight(nBlockTime, (int64_t)txNew.nTime) < GetStakeSplitAge()) + if(nCredit > 50 * COIN) txNew.vout.push_back(CTxOut(0, scriptPubKeyOut)); //split stake LogPrint("coinstake", "CreateCoinStake : added kernel type=%d\n", whichType); fKernelFound = true; @@ -1948,27 +3476,90 @@ bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int } // Calculate coin age reward + int64_t nReward; { uint64_t nCoinAge; CTxDB txdb("r"); if (!txNew.GetCoinAge(txdb, nCoinAge)) return error("CreateCoinStake : failed to calculate coin age"); - int64_t nReward = GetProofOfStakeReward(nCoinAge, nFees); + nReward = GetProofOfStakeReward(nCoinAge, nFees); if (nReward <= 0) return false; nCredit += nReward; } + + // Masternode Payments + int payments = 1; + // start masternode payments + bool bMasterNodePayment = true; // note was false, set true to test + + if ( Params().NetworkID() == CChainParams::TESTNET ){ + if (GetTime() > START_MASTERNODE_PAYMENTS_TESTNET ){ + bMasterNodePayment = true; + } + }else{ + if (GetTime() > START_MASTERNODE_PAYMENTS){ + bMasterNodePayment = true; + } + } + + CScript payee; + bool hasPayment = true; + if(bMasterNodePayment) { + //spork + if(!masternodePayments.GetBlockPayee(pindexPrev->nHeight+1, payee)){ + int winningNode = GetCurrentMasterNode(1); + if(winningNode >= 0){ + payee =GetScriptForDestination(vecMasternodes[winningNode].pubkey.GetID()); + } else { + LogPrintf("CreateCoinStake: Failed to detect masternode to pay\n"); + hasPayment = false; + } + } + } + + if(hasPayment){ + payments = txNew.vout.size() + 1; + txNew.vout.resize(payments); + + txNew.vout[payments-1].scriptPubKey = payee; + txNew.vout[payments-1].nValue = 0; + + CTxDestination address1; + ExtractDestination(payee, address1); + CBitcoinAddress address2(address1); + + LogPrintf("Masternode payment to %s\n", address2.ToString().c_str()); + } + + int64_t blockValue = nCredit; + int64_t masternodePayment = GetMasternodePayment(pindexPrev->nHeight+1, nReward); + + // Set output amount - if (txNew.vout.size() == 3) + if (!hasPayment && txNew.vout.size() == 3) // 2 stake outputs, stake was split, no masternode payment { - txNew.vout[1].nValue = (nCredit / 2 / CENT) * CENT; - txNew.vout[2].nValue = nCredit - txNew.vout[1].nValue; + txNew.vout[1].nValue = (blockValue / 2 / CENT) * CENT; + txNew.vout[2].nValue = blockValue - txNew.vout[1].nValue; + } + else if(hasPayment && txNew.vout.size() == 4) // 2 stake outputs, stake was split, plus a masternode payment + { + txNew.vout[payments-1].nValue = masternodePayment; + blockValue -= masternodePayment; + txNew.vout[1].nValue = (blockValue / 2 / CENT) * CENT; + txNew.vout[2].nValue = blockValue - txNew.vout[1].nValue; + } + else if(!hasPayment && txNew.vout.size() == 2) // only 1 stake output, was not split, no masternode payment + txNew.vout[1].nValue = blockValue; + else if(hasPayment && txNew.vout.size() == 3) // only 1 stake output, was not split, plus a masternode payment + { + txNew.vout[payments-1].nValue = masternodePayment; + blockValue -= masternodePayment; + txNew.vout[1].nValue = blockValue; } - else - txNew.vout[1].nValue = nCredit; // Sign int nIn = 0; @@ -1991,6 +3582,15 @@ bool CWallet::CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int // Call after CreateTransaction unless you want to abort bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey) { + mapValue_t mapNarr; + FindStealthTransactions(wtxNew, mapNarr); + + if (!mapNarr.empty()) + { + BOOST_FOREACH(const PAIRTYPE(string,string)& item, mapNarr) + wtxNew.mapValue[item.first] = item.second; + }; + { LOCK2(cs_main, cs_wallet); LogPrintf("CommitTransaction:\n%s", wtxNew.ToString()); @@ -2040,7 +3640,7 @@ bool CWallet::CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey) -string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee) +string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, bool fAskFee) { CReserveKey reservekey(this); int64_t nFeeRequired; @@ -2057,7 +3657,7 @@ string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNe LogPrintf("SendMoney() : %s", strError); return strError; } - if (!CreateTransaction(scriptPubKey, nValue, wtxNew, reservekey, nFeeRequired)) + if (!CreateTransaction(scriptPubKey, nValue, sNarr, wtxNew, reservekey, nFeeRequired)) { string strError; if (nValue + nFeeRequired > GetBalance()) @@ -2079,7 +3679,7 @@ string CWallet::SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNe -string CWallet::SendMoneyToDestination(const CTxDestination& address, int64_t nValue, CWalletTx& wtxNew, bool fAskFee) +string CWallet::SendMoneyToDestination(const CTxDestination& address, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, bool fAskFee) { // Check amount if (nValue <= 0) @@ -2087,14 +3687,178 @@ string CWallet::SendMoneyToDestination(const CTxDestination& address, int64_t nV if (nValue + nTransactionFee > GetBalance()) return _("Insufficient funds"); + if (sNarr.length() > 24) + return _("Narration must be 24 characters or less."); + // Parse Bitcoin address CScript scriptPubKey; scriptPubKey.SetDestination(address); - return SendMoney(scriptPubKey, nValue, wtxNew, fAskFee); + return SendMoney(scriptPubKey, nValue, sNarr, wtxNew, fAskFee); } +string CWallet::PrepareDarksendDenominate(int minRounds, int maxRounds) +{ + if (IsLocked()) + return _("Error: Wallet locked, unable to create transaction!"); + + if(darkSendPool.GetState() != POOL_STATUS_ERROR && darkSendPool.GetState() != POOL_STATUS_SUCCESS) + if(darkSendPool.GetMyTransactionCount() > 0) + return _("Error: You already have pending entries in the Darksend pool"); + + // ** find the coins we'll use + std::vector vCoins; + std::vector vCoins2; + int64_t nValueIn = 0; + CReserveKey reservekey(this); + + /* + Select the coins we'll use + if minRounds >= 0 it means only denominated inputs are going in and coming out + */ + if(minRounds >= 0){ + if (!SelectCoinsByDenominations(darkSendPool.sessionDenom, 0.1*COIN, DARKSEND_POOL_MAX, vCoins, vCoins2, nValueIn, minRounds, maxRounds)) + return _("Insufficient funds"); + } + + // calculate total value out + int64_t nTotalValue = GetTotalValue(vCoins); + LogPrintf("PrepareDarksendDenominate - preparing darksend denominate . Got: %d \n", nTotalValue); + + //-------------- + BOOST_FOREACH(CTxIn v, vCoins) + LockCoin(v.prevout); + + // denominate our funds + int64_t nValueLeft = nTotalValue; + std::vector vOut; + std::vector vDenoms; + + /* + TODO: Front load with needed denominations (e.g. .1, 1 ) + */ + + /* + Add all denominations once + The beginning of the list is front loaded with each possible + denomination in random order. This means we'll at least get 1 + of each that is required as outputs. + */ + BOOST_FOREACH(int64_t d, darkSendDenominations){ + vDenoms.push_back(d); + vDenoms.push_back(d); + } + + //randomize the order of these denominations + std::random_shuffle (vDenoms.begin(), vDenoms.end()); + + /* + Build a long list of denominations + Next we'll build a long random list of denominations to add. + Eventually as the algorithm goes through these it'll find the ones + it nees to get exact change. + */ + for(int i = 0; i <= 500; i++) + BOOST_FOREACH(int64_t d, darkSendDenominations) + vDenoms.push_back(d); + + //randomize the order of inputs we get back + std::random_shuffle (vDenoms.begin() + (int)darkSendDenominations.size() + 1, vDenoms.end()); + + // Make outputs by looping through denominations randomly + BOOST_REVERSE_FOREACH(int64_t v, vDenoms){ + //only use the ones that are approved + bool fAccepted = false; + if((darkSendPool.sessionDenom & (1 << 0)) && v == ((100000*COIN) +100000000)) {fAccepted = true;} + else if((darkSendPool.sessionDenom & (1 << 1)) && v == ((10000*COIN) +10000000)) {fAccepted = true;} + else if((darkSendPool.sessionDenom & (1 << 2)) && v == ((1000*COIN) +1000000)) {fAccepted = true;} + else if((darkSendPool.sessionDenom & (1 << 3)) && v == ((100*COIN) +100000)) {fAccepted = true;} + else if((darkSendPool.sessionDenom & (1 << 4)) && v == ((10*COIN) +10000)) {fAccepted = true;} + else if((darkSendPool.sessionDenom & (1 << 5)) && v == ((1*COIN) +1000)) {fAccepted = true;} + else if((darkSendPool.sessionDenom & (1 << 6)) && v == ((.1*COIN) +100)) {fAccepted = true;} + if(!fAccepted) continue; + + int nOutputs = 0; + + // add each output up to 10 times until it can't be added again + if(nValueLeft - v >= 0 && nOutputs <= 10) { + CScript scriptChange; + CPubKey vchPubKey; + //use a unique change address + assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked + scriptChange =GetScriptForDestination(vchPubKey.GetID()); + reservekey.KeepKey(); + + CTxOut o(v, scriptChange); + vOut.push_back(o); + + //increment outputs and subtract denomination amount + nOutputs++; + nValueLeft -= v; + } + + if(nValueLeft == 0) break; + } + + //back up mode , incase we couldn't successfully make the outputs for some reason + if(vOut.size() > 40 || darkSendPool.GetDenominations(vOut) != darkSendPool.sessionDenom || nValueLeft != 0){ + vOut.clear(); + nValueLeft = nTotalValue; + + // Make outputs by looping through denominations, from small to large + + BOOST_FOREACH(const COutput& out, vCoins2){ + CScript scriptChange; + CPubKey vchPubKey; + //use a unique change address + assert(reservekey.GetReservedKey(vchPubKey)); // should never fail, as we just unlocked + scriptChange =GetScriptForDestination(vchPubKey.GetID()); + reservekey.KeepKey(); + + CTxOut o(out.tx->vout[out.i].nValue, scriptChange); + vOut.push_back(o); + + //increment outputs and subtract denomination amount + nValueLeft -= out.tx->vout[out.i].nValue; + + if(nValueLeft == 0) break; + } + + } + + if(darkSendPool.GetDenominations(vOut) != darkSendPool.sessionDenom) + return "Error: can't make current denominated outputs"; + + // we don't support change at all + if(nValueLeft != 0) + return "Error: change left-over in pool. Must use denominations only"; + + + //randomize the output order + std::random_shuffle (vOut.begin(), vOut.end()); + + darkSendPool.SendDarksendDenominate(vCoins, vOut, nValueIn); + + return ""; +} + +int64_t CWallet::GetTotalValue(std::vector vCoins) { + int64_t nTotalValue = 0; + CWalletTx wtx; + BOOST_FOREACH(CTxIn i, vCoins){ + if (mapWallet.count(i.prevout.hash)) + { + CWalletTx& wtx = mapWallet[i.prevout.hash]; + if(i.prevout.n < wtx.vout.size()){ + nTotalValue += wtx.vout[i.prevout.n].nValue; + } + } else { + LogPrintf("GetTotalValue -- Couldn't find transaction\n"); + } + } + return nTotalValue; +} DBErrors CWallet::LoadWallet(bool& fFirstRunRet) @@ -2581,6 +4345,44 @@ void CWallet::UpdatedTransaction(const uint256 &hashTx) } } + +void CWallet::LockCoin(COutPoint& output) +{ + AssertLockHeld(cs_wallet); // setLockedCoins + setLockedCoins.insert(output); +} + +void CWallet::UnlockCoin(COutPoint& output) +{ + AssertLockHeld(cs_wallet); // setLockedCoins + setLockedCoins.erase(output); +} + +void CWallet::UnlockAllCoins() +{ + AssertLockHeld(cs_wallet); // setLockedCoins + setLockedCoins.clear(); +} + +bool CWallet::IsLockedCoin(uint256 hash, unsigned int n) const +{ + AssertLockHeld(cs_wallet); // setLockedCoins + COutPoint outpt(hash, n); + + return (setLockedCoins.count(outpt) > 0); +} + +void CWallet::ListLockedCoins(std::vector& vOutpts) +{ + AssertLockHeld(cs_wallet); // setLockedCoins + for (std::set::iterator it = setLockedCoins.begin(); + it != setLockedCoins.end(); it++) { + COutPoint outpt = (*it); + vOutpts.push_back(outpt); + } +} + + void CWallet::GetKeyBirthTimes(std::map &mapKeyBirth) const { AssertLockHeld(cs_wallet); // mapKeyMetadata mapKeyBirth.clear(); @@ -2632,3 +4434,53 @@ void CWallet::GetKeyBirthTimes(std::map &mapKeyBirth) const { for (std::map::const_iterator it = mapKeyFirstBlock.begin(); it != mapKeyFirstBlock.end(); it++) mapKeyBirth[it->first] = it->second->nTime - 7200; // block times can be 2h off } + +bool CWallet::GetTransaction(const uint256 &hashTx, CWalletTx& wtx) +{ + { + LOCK(cs_wallet); + map::iterator mi = mapWallet.find(hashTx); + if (mi != mapWallet.end()) + { + wtx = (*mi).second; + return true; + } + } + return false; +} + +int CMerkleTx::GetTransactionLockSignatures() const +{ + if(!IsSporkActive(SPORK_1_MASTERNODE_PAYMENTS_ENFORCEMENT)) return -3; + if(nInstantXDepth == 0) return -1; + + //compile consessus vote + std::map::iterator i = mapTxLocks.find(GetHash()); + if (i != mapTxLocks.end()){ + return (*i).second.CountSignatures(); + } + + return -1; +} + +bool CMerkleTx::IsTransactionLockTimedOut() const +{ + if(nInstantXDepth == 0) return 0; + + //compile consessus vote + std::map::iterator i = mapTxLocks.find(GetHash()); + if (i != mapTxLocks.end()){ + return GetTime() > (*i).second.nTimeout; + } + + return false; +} + +bool CWallet::AddAdrenalineNodeConfig(CAdrenalineNodeConfig nodeConfig) +{ + bool rv = CWalletDB(strWalletFile).WriteAdrenalineNodeConfig(nodeConfig.sAlias, nodeConfig); + if(rv) + uiInterface.NotifyAdrenalineNodeChanged(nodeConfig); + + return rv; +} diff --git a/src/wallet.h b/src/wallet.h index f01522a..487939b 100644 --- a/src/wallet.h +++ b/src/wallet.h @@ -19,6 +19,7 @@ #include "script.h" #include "ui_interface.h" #include "util.h" +#include "stealth.h" // Settings extern int64_t nTransactionFee; @@ -34,6 +35,9 @@ class CReserveKey; class COutput; class CWalletDB; +typedef std::map StealthKeyMetaMap; +typedef std::map mapValue_t; + /** (client) version numbers for particular wallet features */ enum WalletFeature { @@ -45,6 +49,24 @@ enum WalletFeature FEATURE_LATEST = 60000 }; +enum AvailableCoinsType +{ + ALL_COINS = 1, + ONLY_DENOMINATED = 2, + ONLY_NONDENOMINATED = 3, + ONLY_NONDENOMINATED_NOTMN = 4 // ONLY_NONDENOMINATED and not 1000 GENIUS at the same time +}; + +/** IsMine() return codes */ +enum isminetype +{ + ISMINE_NO = 0, + ISMINE_WATCH_ONLY = 1, + ISMINE_SPENDABLE = 2, + ISMINE_ALL = ISMINE_WATCH_ONLY | ISMINE_SPENDABLE +}; + + /** A key pool entry */ class CKeyPool { @@ -79,8 +101,8 @@ class CWallet : public CCryptoKeyStore, public CWalletInterface { private: bool SelectCoinsForStaking(int64_t nTargetValue, unsigned int nSpendTime, std::set >& setCoinsRet, int64_t& nValueRet) const; - bool SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, std::set >& setCoinsRet, int64_t& nValueRet, const CCoinControl *coinControl=NULL) const; - + //bool SelectCoins(int64_t nTargetValue, unsigned int nSpendTime, std::set >& setCoinsRet, int64_t& nValueRet, const CCoinControl *coinControl=NULL) const; + bool SelectCoins(CAmount nTargetValue, unsigned int nSpendTime, std::set >& setCoinsRet, int64_t& nValueRet, const CCoinControl *coinControl = NULL, AvailableCoinsType coin_type=ALL_COINS, bool useIX = false) const; CWalletDB *pwalletdbEncryption; // the current wallet version: clients below this version are not able to load the wallet @@ -97,17 +119,40 @@ class CWallet : public CCryptoKeyStore, public CWalletInterface /// strWalletFile (immutable after instantiation) mutable CCriticalSection cs_wallet; + bool SelectCoinsDark(int64_t nValueMin, int64_t nValueMax, std::vector& setCoinsRet, int64_t& nValueRet, int nDarksendRoundsMin, int nDarksendRoundsMax) const; + bool SelectCoinsByDenominations(int nDenom, int64_t nValueMin, int64_t nValueMax, std::vector& setCoinsRet, vector& vCoins, int64_t& nValueRet, int nDarksendRoundsMin, int nDarksendRoundsMax); + bool SelectCoinsDarkDenominated(int64_t nTargetValue, std::vector& setCoinsRet, int64_t& nValueRet) const; + bool SelectCoinsMasternode(CTxIn& vin, int64_t& nValueRet, CScript& pubScript) const; + bool HasCollateralInputs() const; + bool IsCollateralAmount(int64_t nInputAmount) const; + int CountInputsWithAmount(int64_t nInputAmount); + + bool SelectCoinsCollateral(std::vector& setCoinsRet, int64_t& nValueRet) const ; + bool SelectCoinsWithoutDenomination(int64_t nTargetValue, std::set >& setCoinsRet, int64_t& nValueRet) const; + bool GetTransaction(const uint256 &hashTx, CWalletTx& wtx); + bool fFileBacked; + bool fWalletUnlockAnonymizeOnly; std::string strWalletFile; std::set setKeyPool; std::map mapKeyMetadata; + std::set stealthAddresses; + StealthKeyMetaMap mapStealthKeyMeta; + + int nLastFilteredHeight; + + uint32_t nStealth, nFoundStealth; // for reporting, zero before use + typedef std::map MasterKeyMap; MasterKeyMap mapMasterKeys; unsigned int nMasterKeyMaxID; + std::map mapMyAdrenalineNodes; + bool AddAdrenalineNodeConfig(CAdrenalineNodeConfig nodeConfig); + CWallet() { SetNull(); @@ -119,6 +164,7 @@ class CWallet : public CCryptoKeyStore, public CWalletInterface strWalletFile = strWalletFileIn; fFileBacked = true; } + void SetNull() { nWalletVersion = FEATURE_BASE; @@ -128,6 +174,8 @@ class CWallet : public CCryptoKeyStore, public CWalletInterface pwalletdbEncryption = NULL; nOrderPosNext = 0; nTimeFirstKey = 0; + nLastFilteredHeight = 0; + fWalletUnlockAnonymizeOnly = false; } std::map mapWallet; @@ -137,16 +185,29 @@ class CWallet : public CCryptoKeyStore, public CWalletInterface std::map mapAddressBook; CPubKey vchDefaultKey; + + std::set setLockedCoins; + int64_t nTimeFirstKey; // check whether we are allowed to upgrade (or already support) to the named feature bool CanSupportFeature(enum WalletFeature wf) { AssertLockHeld(cs_wallet); return nWalletMaxVersion >= wf; } void AvailableCoinsForStaking(std::vector& vCoins, unsigned int nSpendTime) const; - void AvailableCoins(std::vector& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl=NULL) const; + void AvailableCoins(std::vector& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL, AvailableCoinsType coin_type=ALL_COINS, bool useIX = false) const; + void AvailableCoinsMN(std::vector& vCoins, bool fOnlyConfirmed=true, const CCoinControl *coinControl = NULL, AvailableCoinsType coin_type=ALL_COINS, bool useIX = false) const; bool SelectCoinsMinConf(int64_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::vector vCoins, std::set >& setCoinsRet, int64_t& nValueRet) const; bool SelectCoinsMinConfByCoinAge(int64_t nTargetValue, unsigned int nSpendTime, int nConfMine, int nConfTheirs, std::vector vCoins, std::set >& setCoinsRet, int64_t& nValueRet) const; + bool IsSpent(const uint256& hash, unsigned int n) const; + + bool IsLockedCoin(uint256 hash, unsigned int n) const; + void LockCoin(COutPoint& output); + void UnlockCoin(COutPoint& output); + void UnlockAllCoins(); + void ListLockedCoins(std::vector& vOutpts); + CAmount GetTotalValue(std::vector vCoins); + // keystore implementation // Generate a new key CPubKey GenerateNewKey(); @@ -166,7 +227,8 @@ class CWallet : public CCryptoKeyStore, public CWalletInterface bool AddCScript(const CScript& redeemScript); bool LoadCScript(const CScript& redeemScript); - bool Unlock(const SecureString& strWalletPassphrase); + bool Lock(); + bool Unlock(const SecureString& strWalletPassphrase, bool anonimizeOnly = false); bool ChangeWalletPassphrase(const SecureString& strOldWalletPassphrase, const SecureString& strNewWalletPassphrase); bool EncryptWallet(const SecureString& strWalletPassphrase); @@ -197,19 +259,40 @@ class CWallet : public CCryptoKeyStore, public CWalletInterface void ReacceptWalletTransactions(); void ResendWalletTransactions(bool fForce = false); int64_t GetBalance() const; + int64_t GetBalanceNoLocks() const; int64_t GetUnconfirmedBalance() const; int64_t GetImmatureBalance() const; int64_t GetStake() const; int64_t GetNewMint() const; - bool CreateTransaction(const std::vector >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL); - bool CreateTransaction(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL); + + CAmount GetAnonymizedBalance() const; + double GetAverageAnonymizedRounds() const; + CAmount GetNormalizedAnonymizedBalance() const; + CAmount GetDenominatedBalance(bool onlyDenom=true, bool onlyUnconfirmed=false) const; + + bool CreateTransaction(const std::vector >& vecSend, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, int32_t& nChangePos, std::string& strFailReason, const CCoinControl *coinControl=NULL, AvailableCoinsType coin_type=ALL_COINS, bool useIX=false); + bool CreateTransaction(CScript scriptPubKey, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl *coinControl=NULL); bool CommitTransaction(CWalletTx& wtxNew, CReserveKey& reservekey); uint64_t GetStakeWeight() const; bool CreateCoinStake(const CKeyStore& keystore, unsigned int nBits, int64_t nSearchInterval, int64_t nFees, CTransaction& txNew, CKey& key); - std::string SendMoney(CScript scriptPubKey, int64_t nValue, CWalletTx& wtxNew, bool fAskFee=false); - std::string SendMoneyToDestination(const CTxDestination &address, int64_t nValue, CWalletTx& wtxNew, bool fAskFee=false); + std::string SendMoney(CScript scriptPubKey, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, bool fAskFee=false); + std::string SendMoneyToDestination(const CTxDestination &address, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, bool fAskFee=false); + + bool NewStealthAddress(std::string& sError, std::string& sLabel, CStealthAddress& sxAddr); + bool AddStealthAddress(CStealthAddress& sxAddr); + bool UnlockStealthAddresses(const CKeyingMaterial& vMasterKeyIn); + bool UpdateStealthAddress(std::string &addr, std::string &label, bool addIfNotExist); + + bool CreateStealthTransaction(CScript scriptPubKey, int64_t nValue, std::vector& P, std::vector& narr, std::string& sNarr, CWalletTx& wtxNew, CReserveKey& reservekey, int64_t& nFeeRet, const CCoinControl* coinControl=NULL); + std::string SendStealthMoney(CScript scriptPubKey, int64_t nValue, std::vector& P, std::vector& narr, std::string& sNarr, CWalletTx& wtxNew, bool fAskFee=false); + bool SendStealthMoneyToDestination(CStealthAddress& sxAddress, int64_t nValue, std::string& sNarr, CWalletTx& wtxNew, std::string& sError, bool fAskFee=false); + bool FindStealthTransactions(const CTransaction& tx, mapValue_t& mapNarr); + + std::string PrepareDarksendDenominate(int minRounds, int maxRounds); + bool CreateCollateralTransaction(CTransaction& txCollateral, std::string strReason); + bool ConvertList(std::vector vCoins, std::vector& vecAmounts); bool NewKeyPool(); bool TopUpKeyPool(unsigned int nSize = 0); @@ -224,6 +307,27 @@ class CWallet : public CCryptoKeyStore, public CWalletInterface std::set< std::set > GetAddressGroupings(); std::map GetAddressBalances(); + + bool IsDenominated(const CTxIn &txin) const; + + bool IsDenominated(const CTransaction& tx) const + { + /* + Return false if ANY inputs are non-denom + */ + bool ret = true; + BOOST_FOREACH(const CTxIn& txin, tx.vin) + { + if(!IsDenominated(txin)) { + ret = false; + } + } + return ret; + } + + bool IsDenominatedAmount(int64_t nInputAmount) const; + + bool IsMine(const CTxIn& txin) const; int64_t GetDebit(const CTxIn& txin) const; bool IsMine(const CTxOut& txout) const @@ -583,6 +687,13 @@ class CWalletTx : public CMerkleTx return (!!vfSpent[nOut]); } + int64_t IsDenominated() const + { + if (vin.empty()) + return 0; + return pwallet->IsDenominated(*this); + } + int64_t GetDebit() const { if (vin.empty()) @@ -728,16 +839,34 @@ class COutput const CWalletTx *tx; int i; int nDepth; + bool fSpendable; - COutput(const CWalletTx *txIn, int iIn, int nDepthIn) + COutput(const CWalletTx *txIn, int iIn, int nDepthIn, bool fSpendableIn) { - tx = txIn; i = iIn; nDepth = nDepthIn; + tx = txIn; i = iIn; nDepth = nDepthIn; fSpendable = fSpendableIn; } std::string ToString() const { return strprintf("COutput(%s, %d, %d) [%s]", tx->GetHash().ToString(), i, nDepth, FormatMoney(tx->vout[i].nValue)); } + + //Used with Darksend. Will return fees, then denominations, everything else, then very small inputs that aren't fees + int Priority() const + { + if(tx->vout[i].nValue == DARKSEND_FEE) return -20000; + BOOST_FOREACH(int64_t d, darkSendDenominations) + if(tx->vout[i].nValue == d) return 10000; + if(tx->vout[i].nValue < 1*COIN) return 20000; + + //nondenom return largest first + return -(tx->vout[i].nValue/COIN); + } + + void print() const + { + LogPrintf("%s\n", ToString().c_str()); + } }; diff --git a/src/walletdb.cpp b/src/walletdb.cpp index ca658d6..17c24b0 100644 --- a/src/walletdb.cpp +++ b/src/walletdb.cpp @@ -51,6 +51,48 @@ bool CWalletDB::EraseTx(uint256 hash) return Erase(std::make_pair(std::string("tx"), hash)); } +bool CWalletDB::WriteStealthKeyMeta(const CKeyID& keyId, const CStealthKeyMetadata& sxKeyMeta) +{ + nWalletDBUpdated++; + return Write(std::make_pair(std::string("sxKeyMeta"), keyId), sxKeyMeta, true); +} + +bool CWalletDB::EraseStealthKeyMeta(const CKeyID& keyId) +{ + nWalletDBUpdated++; + return Erase(std::make_pair(std::string("sxKeyMeta"), keyId)); +} + +bool CWalletDB::WriteStealthAddress(const CStealthAddress& sxAddr) +{ + nWalletDBUpdated++; + + return Write(std::make_pair(std::string("sxAddr"), sxAddr.scan_pubkey), sxAddr, true); +} + +bool CWalletDB::ReadStealthAddress(CStealthAddress& sxAddr) +{ + // -- set scan_pubkey before reading + return Read(std::make_pair(std::string("sxAddr"), sxAddr.scan_pubkey), sxAddr); +} + +bool CWalletDB::WriteAdrenalineNodeConfig(std::string sAlias, const CAdrenalineNodeConfig& nodeConfig) +{ + nWalletDBUpdated++; + return Write(std::make_pair(std::string("adrenaline"), sAlias), nodeConfig, true); +} + +bool CWalletDB::ReadAdrenalineNodeConfig(std::string sAlias, CAdrenalineNodeConfig& nodeConfig) +{ + return Read(std::make_pair(std::string("adrenaline"), sAlias), nodeConfig); +} + +bool CWalletDB::EraseAdrenalineNodeConfig(std::string sAlias) +{ + nWalletDBUpdated++; + return Erase(std::make_pair(std::string("adrenaline"), sAlias)); +} + bool CWalletDB::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta) { nWalletDBUpdated++; @@ -377,7 +419,17 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, // DateTimeStrFormat("%x %H:%M:%S", wtx.GetBlockTime()), // wtx.hashBlock.ToString(), // wtx.mapValue["message"]); - } + } else + if (strType == "sxAddr") + { + if (fDebug) + printf("WalletDB ReadKeyValue sxAddr\n"); + + CStealthAddress sxAddr; + ssValue >> sxAddr; + + pwallet->stealthAddresses.insert(sxAddr); + } else if (strType == "acentry") { string strAccount; @@ -503,6 +555,18 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, (keyMeta.nCreateTime < pwallet->nTimeFirstKey)) pwallet->nTimeFirstKey = keyMeta.nCreateTime; } + else if (strType == "sxKeyMeta") + { + if (fDebug) + printf("WalletDB ReadKeyValue sxKeyMeta\n"); + + CKeyID keyId; + ssKey >> keyId; + CStealthKeyMetadata sxKeyMeta; + ssValue >> sxKeyMeta; + + pwallet->mapStealthKeyMeta[keyId] = sxKeyMeta; + } else if (strType == "defaultkey") { ssValue >> pwallet->vchDefaultKey; @@ -545,6 +609,14 @@ ReadKeyValue(CWallet* pwallet, CDataStream& ssKey, CDataStream& ssValue, { ssValue >> pwallet->nOrderPosNext; } + else if (strType == "adrenaline") + { + std::string sAlias; + ssKey >> sAlias; + CAdrenalineNodeConfig adrenalineNodeConfig; + ssValue >> adrenalineNodeConfig; + pwallet->mapMyAdrenalineNodes.insert(make_pair(sAlias, adrenalineNodeConfig)); + } } catch (...) { return false; diff --git a/src/walletdb.h b/src/walletdb.h index 7a2bf76..ddf4b3b 100644 --- a/src/walletdb.h +++ b/src/walletdb.h @@ -7,6 +7,7 @@ #include "db.h" #include "key.h" +#include "stealth.h" #include #include @@ -66,6 +67,54 @@ class CKeyMetadata } }; +class CStealthKeyMetadata +{ +// -- used to get secret for keys created by stealth transaction with wallet locked +public: + CStealthKeyMetadata() {}; + + CStealthKeyMetadata(CPubKey pkEphem_, CPubKey pkScan_) + { + pkEphem = pkEphem_; + pkScan = pkScan_; + }; + + CPubKey pkEphem; + CPubKey pkScan; + + IMPLEMENT_SERIALIZE + ( + READWRITE(pkEphem); + READWRITE(pkScan); + ) + +}; + +class CAdrenalineNodeConfig +{ +public: + int nVersion; + std::string sAlias; + std::string sAddress; + std::string sCollateralAddress; + std::string sMasternodePrivKey; + bool isLocal; + + CAdrenalineNodeConfig() + { + nVersion = 0; + } + + IMPLEMENT_SERIALIZE( + READWRITE(nVersion); + READWRITE(sAlias); + READWRITE(sAddress); + READWRITE(sCollateralAddress); + READWRITE(sMasternodePrivKey); + READWRITE(isLocal); + ) +}; + /** Access to the wallet database (wallet.dat) */ class CWalletDB : public CDB @@ -85,6 +134,15 @@ class CWalletDB : public CDB bool WriteTx(uint256 hash, const CWalletTx& wtx); bool EraseTx(uint256 hash); + bool WriteStealthKeyMeta(const CKeyID& keyId, const CStealthKeyMetadata& sxKeyMeta); + bool EraseStealthKeyMeta(const CKeyID& keyId); + bool WriteStealthAddress(const CStealthAddress& sxAddr); + bool ReadStealthAddress(CStealthAddress& sxAddr); + + bool WriteAdrenalineNodeConfig(std::string sAlias, const CAdrenalineNodeConfig& nodeConfig); + bool ReadAdrenalineNodeConfig(std::string sAlias, CAdrenalineNodeConfig& nodeConfig); + bool EraseAdrenalineNodeConfig(std::string sAlias); + bool WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata &keyMeta); bool WriteCryptedKey(const CPubKey& vchPubKey, const std::vector& vchCryptedSecret, const CKeyMetadata &keyMeta); bool WriteMasterKey(unsigned int nID, const CMasterKey& kMasterKey); diff --git a/src/xxhash/xxhash.c b/src/xxhash/xxhash.c new file mode 100644 index 0000000..c55b339 --- /dev/null +++ b/src/xxhash/xxhash.c @@ -0,0 +1,476 @@ +/* +xxHash - Fast Hash algorithm +Copyright (C) 2012-2014, Yann Collet. +BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. +* 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. + +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 +OWNER 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. + +You can contact the author at : +- xxHash source repository : http://code.google.com/p/xxhash/ +*/ + + +//************************************** +// Tuning parameters +//************************************** +// Unaligned memory access is automatically enabled for "common" CPU, such as x86. +// For others CPU, the compiler will be more cautious, and insert extra code to ensure aligned access is respected. +// If you know your target CPU supports unaligned memory access, you want to force this option manually to improve performance. +// You can also enable this parameter if you know your input data will always be aligned (boundaries of 4, for U32). +#if defined(__ARM_FEATURE_UNALIGNED) || defined(__i386) || defined(_M_IX86) || defined(__x86_64__) || defined(_M_X64) +# define XXH_USE_UNALIGNED_ACCESS 1 +#endif + +// XXH_ACCEPT_NULL_INPUT_POINTER : +// If the input pointer is a null pointer, xxHash default behavior is to trigger a memory access error, since it is a bad pointer. +// When this option is enabled, xxHash output for null input pointers will be the same as a null-length input. +// This option has a very small performance cost (only measurable on small inputs). +// By default, this option is disabled. To enable it, uncomment below define : +//#define XXH_ACCEPT_NULL_INPUT_POINTER 1 + +// XXH_FORCE_NATIVE_FORMAT : +// By default, xxHash library provides endian-independant Hash values, based on little-endian convention. +// Results are therefore identical for little-endian and big-endian CPU. +// This comes at a performance cost for big-endian CPU, since some swapping is required to emulate little-endian format. +// Should endian-independance be of no importance for your application, you may set the #define below to 1. +// It will improve speed for Big-endian CPU. +// This option has no impact on Little_Endian CPU. +#define XXH_FORCE_NATIVE_FORMAT 0 + + +//************************************** +// Compiler Specific Options +//************************************** +// Disable some Visual warning messages +#ifdef _MSC_VER // Visual Studio +# pragma warning(disable : 4127) // disable: C4127: conditional expression is constant +#endif + +#ifdef _MSC_VER // Visual Studio +# define FORCE_INLINE static __forceinline +#else +# ifdef __GNUC__ +# define FORCE_INLINE static inline __attribute__((always_inline)) +# else +# define FORCE_INLINE static inline +# endif +#endif + + +//************************************** +// Includes & Memory related functions +//************************************** +#include "xxhash.h" +// Modify the local functions below should you wish to use some other memory related routines +// for malloc(), free() +#include +FORCE_INLINE void* XXH_malloc(size_t s) { return malloc(s); } +FORCE_INLINE void XXH_free (void* p) { free(p); } +// for memcpy() +#include +FORCE_INLINE void* XXH_memcpy(void* dest, const void* src, size_t size) { return memcpy(dest,src,size); } + + +//************************************** +// Basic Types +//************************************** +#if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L // C99 +# include + typedef uint8_t BYTE; + typedef uint16_t U16; + typedef uint32_t U32; + typedef int32_t S32; + typedef uint64_t U64; +#else + typedef unsigned char BYTE; + typedef unsigned short U16; + typedef unsigned int U32; + typedef signed int S32; + typedef unsigned long long U64; +#endif + +#if defined(__GNUC__) && !defined(XXH_USE_UNALIGNED_ACCESS) +# define _PACKED_XXH __attribute__ ((packed)) +#else +# define _PACKED_XXH +#endif + +#if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__) +# ifdef __IBMC__ +# pragma pack(1) +# else +# pragma pack(push, 1) +# endif +#endif + + +typedef struct _U32_S { U32 v; } _PACKED_XXH U32_S_XXH; + +#if !defined(XXH_USE_UNALIGNED_ACCESS) && !defined(__GNUC__) +# pragma pack(pop) +#endif + +#define A32_XXH(x) (((U32_S_XXH *)(x))->v) + + +//*************************************** +// Compiler-specific Functions and Macros +//*************************************** +#define GCC_VERSION (__GNUC__ * 100 + __GNUC_MINOR__) + +// Note : although _rotl exists for minGW (GCC under windows), performance seems poor +#if defined(_MSC_VER) +# define XXH_rotl32(x,r) _rotl(x,r) +#else +# define XXH_rotl32(x,r) ((x << r) | (x >> (32 - r))) +#endif + +#if defined(_MSC_VER) // Visual Studio +# define XXH_swap32 _byteswap_ulong +#elif GCC_VERSION >= 403 +# define XXH_swap32 __builtin_bswap32 +#else +static inline U32 XXH_swap32 (U32 x) { + return ((x << 24) & 0xff000000 ) | + ((x << 8) & 0x00ff0000 ) | + ((x >> 8) & 0x0000ff00 ) | + ((x >> 24) & 0x000000ff );} +#endif + + +//************************************** +// Constants +//************************************** +#define PRIME32_1 2654435761U +#define PRIME32_2 2246822519U +#define PRIME32_3 3266489917U +#define PRIME32_4 668265263U +#define PRIME32_5 374761393U + + +//************************************** +// Architecture Macros +//************************************** +typedef enum { XXH_bigEndian=0, XXH_littleEndian=1 } XXH_endianess; +#ifndef XXH_CPU_LITTLE_ENDIAN // It is possible to define XXH_CPU_LITTLE_ENDIAN externally, for example using a compiler switch + static const int one = 1; +# define XXH_CPU_LITTLE_ENDIAN (*(char*)(&one)) +#endif + + +//************************************** +// Macros +//************************************** +#define XXH_STATIC_ASSERT(c) { enum { XXH_static_assert = 1/(!!(c)) }; } // use only *after* variable declarations + + +//**************************** +// Memory reads +//**************************** +typedef enum { XXH_aligned, XXH_unaligned } XXH_alignment; + +FORCE_INLINE U32 XXH_readLE32_align(const U32* ptr, XXH_endianess endian, XXH_alignment align) +{ + if (align==XXH_unaligned) + return endian==XXH_littleEndian ? A32_XXH(ptr) : XXH_swap32(A32_XXH(ptr)); + else + return endian==XXH_littleEndian ? *ptr : XXH_swap32(*ptr); +} + +FORCE_INLINE U32 XXH_readLE32(const U32* ptr, XXH_endianess endian) { return XXH_readLE32_align(ptr, endian, XXH_unaligned); } + + +//**************************** +// Simple Hash Functions +//**************************** +FORCE_INLINE U32 XXH32_endian_align(const void* input, int len, U32 seed, XXH_endianess endian, XXH_alignment align) +{ + const BYTE* p = (const BYTE*)input; + const BYTE* const bEnd = p + len; + U32 h32; + +#ifdef XXH_ACCEPT_NULL_INPUT_POINTER + if (p==NULL) { len=0; p=(const BYTE*)(size_t)16; } +#endif + + if (len>=16) + { + const BYTE* const limit = bEnd - 16; + U32 v1 = seed + PRIME32_1 + PRIME32_2; + U32 v2 = seed + PRIME32_2; + U32 v3 = seed + 0; + U32 v4 = seed - PRIME32_1; + + do + { + v1 += XXH_readLE32_align((const U32*)p, endian, align) * PRIME32_2; v1 = XXH_rotl32(v1, 13); v1 *= PRIME32_1; p+=4; + v2 += XXH_readLE32_align((const U32*)p, endian, align) * PRIME32_2; v2 = XXH_rotl32(v2, 13); v2 *= PRIME32_1; p+=4; + v3 += XXH_readLE32_align((const U32*)p, endian, align) * PRIME32_2; v3 = XXH_rotl32(v3, 13); v3 *= PRIME32_1; p+=4; + v4 += XXH_readLE32_align((const U32*)p, endian, align) * PRIME32_2; v4 = XXH_rotl32(v4, 13); v4 *= PRIME32_1; p+=4; + } while (p<=limit); + + h32 = XXH_rotl32(v1, 1) + XXH_rotl32(v2, 7) + XXH_rotl32(v3, 12) + XXH_rotl32(v4, 18); + } + else + { + h32 = seed + PRIME32_5; + } + + h32 += (U32) len; + + while (p<=bEnd-4) + { + h32 += XXH_readLE32_align((const U32*)p, endian, align) * PRIME32_3; + h32 = XXH_rotl32(h32, 17) * PRIME32_4 ; + p+=4; + } + + while (p> 15; + h32 *= PRIME32_2; + h32 ^= h32 >> 13; + h32 *= PRIME32_3; + h32 ^= h32 >> 16; + + return h32; +} + + +U32 XXH32(const void* input, int len, U32 seed) +{ +#if 0 + // Simple version, good for code maintenance, but unfortunately slow for small inputs + void* state = XXH32_init(seed); + XXH32_update(state, input, len); + return XXH32_digest(state); +#else + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + +# if !defined(XXH_USE_UNALIGNED_ACCESS) + if ((((size_t)input) & 3)) // Input is aligned, let's leverage the speed advantage + { + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_aligned); + else + return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_aligned); + } +# endif + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_endian_align(input, len, seed, XXH_littleEndian, XXH_unaligned); + else + return XXH32_endian_align(input, len, seed, XXH_bigEndian, XXH_unaligned); +#endif +} + + +//**************************** +// Advanced Hash Functions +//**************************** + +struct XXH_state32_t +{ + U64 total_len; + U32 seed; + U32 v1; + U32 v2; + U32 v3; + U32 v4; + int memsize; + char memory[16]; +}; + + +int XXH32_sizeofState() +{ + XXH_STATIC_ASSERT(XXH32_SIZEOFSTATE >= sizeof(struct XXH_state32_t)); // A compilation error here means XXH32_SIZEOFSTATE is not large enough + return sizeof(struct XXH_state32_t); +} + + +XXH_errorcode XXH32_resetState(void* state_in, U32 seed) +{ + struct XXH_state32_t * state = (struct XXH_state32_t *) state_in; + state->seed = seed; + state->v1 = seed + PRIME32_1 + PRIME32_2; + state->v2 = seed + PRIME32_2; + state->v3 = seed + 0; + state->v4 = seed - PRIME32_1; + state->total_len = 0; + state->memsize = 0; + return XXH_OK; +} + + +void* XXH32_init (U32 seed) +{ + void* state = XXH_malloc (sizeof(struct XXH_state32_t)); + XXH32_resetState(state, seed); + return state; +} + + +FORCE_INLINE XXH_errorcode XXH32_update_endian (void* state_in, const void* input, int len, XXH_endianess endian) +{ + struct XXH_state32_t * state = (struct XXH_state32_t *) state_in; + const BYTE* p = (const BYTE*)input; + const BYTE* const bEnd = p + len; + +#ifdef XXH_ACCEPT_NULL_INPUT_POINTER + if (input==NULL) return XXH_ERROR; +#endif + + state->total_len += len; + + if (state->memsize + len < 16) // fill in tmp buffer + { + XXH_memcpy(state->memory + state->memsize, input, len); + state->memsize += len; + return XXH_OK; + } + + if (state->memsize) // some data left from previous update + { + XXH_memcpy(state->memory + state->memsize, input, 16-state->memsize); + { + const U32* p32 = (const U32*)state->memory; + state->v1 += XXH_readLE32(p32, endian) * PRIME32_2; state->v1 = XXH_rotl32(state->v1, 13); state->v1 *= PRIME32_1; p32++; + state->v2 += XXH_readLE32(p32, endian) * PRIME32_2; state->v2 = XXH_rotl32(state->v2, 13); state->v2 *= PRIME32_1; p32++; + state->v3 += XXH_readLE32(p32, endian) * PRIME32_2; state->v3 = XXH_rotl32(state->v3, 13); state->v3 *= PRIME32_1; p32++; + state->v4 += XXH_readLE32(p32, endian) * PRIME32_2; state->v4 = XXH_rotl32(state->v4, 13); state->v4 *= PRIME32_1; p32++; + } + p += 16-state->memsize; + state->memsize = 0; + } + + if (p <= bEnd-16) + { + const BYTE* const limit = bEnd - 16; + U32 v1 = state->v1; + U32 v2 = state->v2; + U32 v3 = state->v3; + U32 v4 = state->v4; + + do + { + v1 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v1 = XXH_rotl32(v1, 13); v1 *= PRIME32_1; p+=4; + v2 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v2 = XXH_rotl32(v2, 13); v2 *= PRIME32_1; p+=4; + v3 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v3 = XXH_rotl32(v3, 13); v3 *= PRIME32_1; p+=4; + v4 += XXH_readLE32((const U32*)p, endian) * PRIME32_2; v4 = XXH_rotl32(v4, 13); v4 *= PRIME32_1; p+=4; + } while (p<=limit); + + state->v1 = v1; + state->v2 = v2; + state->v3 = v3; + state->v4 = v4; + } + + if (p < bEnd) + { + XXH_memcpy(state->memory, p, bEnd-p); + state->memsize = (int)(bEnd-p); + } + + return XXH_OK; +} + +XXH_errorcode XXH32_update (void* state_in, const void* input, int len) +{ + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_update_endian(state_in, input, len, XXH_littleEndian); + else + return XXH32_update_endian(state_in, input, len, XXH_bigEndian); +} + + + +FORCE_INLINE U32 XXH32_intermediateDigest_endian (void* state_in, XXH_endianess endian) +{ + struct XXH_state32_t * state = (struct XXH_state32_t *) state_in; + const BYTE * p = (const BYTE*)state->memory; + BYTE* bEnd = (BYTE*)state->memory + state->memsize; + U32 h32; + + if (state->total_len >= 16) + { + h32 = XXH_rotl32(state->v1, 1) + XXH_rotl32(state->v2, 7) + XXH_rotl32(state->v3, 12) + XXH_rotl32(state->v4, 18); + } + else + { + h32 = state->seed + PRIME32_5; + } + + h32 += (U32) state->total_len; + + while (p<=bEnd-4) + { + h32 += XXH_readLE32((const U32*)p, endian) * PRIME32_3; + h32 = XXH_rotl32(h32, 17) * PRIME32_4; + p+=4; + } + + while (p> 15; + h32 *= PRIME32_2; + h32 ^= h32 >> 13; + h32 *= PRIME32_3; + h32 ^= h32 >> 16; + + return h32; +} + + +U32 XXH32_intermediateDigest (void* state_in) +{ + XXH_endianess endian_detected = (XXH_endianess)XXH_CPU_LITTLE_ENDIAN; + + if ((endian_detected==XXH_littleEndian) || XXH_FORCE_NATIVE_FORMAT) + return XXH32_intermediateDigest_endian(state_in, XXH_littleEndian); + else + return XXH32_intermediateDigest_endian(state_in, XXH_bigEndian); +} + + +U32 XXH32_digest (void* state_in) +{ + U32 h32 = XXH32_intermediateDigest(state_in); + + XXH_free(state_in); + + return h32; +} diff --git a/src/xxhash/xxhash.h b/src/xxhash/xxhash.h new file mode 100644 index 0000000..8491099 --- /dev/null +++ b/src/xxhash/xxhash.h @@ -0,0 +1,164 @@ +/* + xxHash - Fast Hash algorithm + Header File + Copyright (C) 2012-2014, Yann Collet. + BSD 2-Clause License (http://www.opensource.org/licenses/bsd-license.php) + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + * 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. + + 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 + OWNER 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. + + You can contact the author at : + - xxHash source repository : http://code.google.com/p/xxhash/ +*/ + +/* Notice extracted from xxHash homepage : + +xxHash is an extremely fast Hash algorithm, running at RAM speed limits. +It also successfully passes all tests from the SMHasher suite. + +Comparison (single thread, Windows Seven 32 bits, using SMHasher on a Core 2 Duo @3GHz) + +Name Speed Q.Score Author +xxHash 5.4 GB/s 10 +CrapWow 3.2 GB/s 2 Andrew +MumurHash 3a 2.7 GB/s 10 Austin Appleby +SpookyHash 2.0 GB/s 10 Bob Jenkins +SBox 1.4 GB/s 9 Bret Mulvey +Lookup3 1.2 GB/s 9 Bob Jenkins +SuperFastHash 1.2 GB/s 1 Paul Hsieh +CityHash64 1.05 GB/s 10 Pike & Alakuijala +FNV 0.55 GB/s 5 Fowler, Noll, Vo +CRC32 0.43 GB/s 9 +MD5-32 0.33 GB/s 10 Ronald L. Rivest +SHA1-32 0.28 GB/s 10 + +Q.Score is a measure of quality of the hash function. +It depends on successfully passing SMHasher test set. +10 is a perfect score. +*/ + +#pragma once + +#if defined (__cplusplus) +extern "C" { +#endif + + +//**************************** +// Type +//**************************** +typedef enum { XXH_OK=0, XXH_ERROR } XXH_errorcode; + + + +//**************************** +// Simple Hash Functions +//**************************** + +unsigned int XXH32 (const void* input, int len, unsigned int seed); + +/* +XXH32() : + Calculate the 32-bits hash of sequence of length "len" stored at memory address "input". + The memory between input & input+len must be valid (allocated and read-accessible). + "seed" can be used to alter the result predictably. + This function successfully passes all SMHasher tests. + Speed on Core 2 Duo @ 3 GHz (single thread, SMHasher benchmark) : 5.4 GB/s + Note that "len" is type "int", which means it is limited to 2^31-1. + If your data is larger, use the advanced functions below. +*/ + + + +//**************************** +// Advanced Hash Functions +//**************************** + +void* XXH32_init (unsigned int seed); +XXH_errorcode XXH32_update (void* state, const void* input, int len); +unsigned int XXH32_digest (void* state); + +/* +These functions calculate the xxhash of an input provided in several small packets, +as opposed to an input provided as a single block. + +It must be started with : +void* XXH32_init() +The function returns a pointer which holds the state of calculation. + +This pointer must be provided as "void* state" parameter for XXH32_update(). +XXH32_update() can be called as many times as necessary. +The user must provide a valid (allocated) input. +The function returns an error code, with 0 meaning OK, and any other value meaning there is an error. +Note that "len" is type "int", which means it is limited to 2^31-1. +If your data is larger, it is recommended to chunk your data into blocks +of size for example 2^30 (1GB) to avoid any "int" overflow issue. + +Finally, you can end the calculation anytime, by using XXH32_digest(). +This function returns the final 32-bits hash. +You must provide the same "void* state" parameter created by XXH32_init(). +Memory will be freed by XXH32_digest(). +*/ + + +int XXH32_sizeofState(void); +XXH_errorcode XXH32_resetState(void* state, unsigned int seed); + +#define XXH32_SIZEOFSTATE 48 +typedef struct { long long ll[(XXH32_SIZEOFSTATE+(sizeof(long long)-1))/sizeof(long long)]; } XXH32_stateSpace_t; +/* +These functions allow user application to make its own allocation for state. + +XXH32_sizeofState() is used to know how much space must be allocated for the xxHash 32-bits state. +Note that the state must be aligned to access 'long long' fields. Memory must be allocated and referenced by a pointer. +This pointer must then be provided as 'state' into XXH32_resetState(), which initializes the state. + +For static allocation purposes (such as allocation on stack, or freestanding systems without malloc()), +use the structure XXH32_stateSpace_t, which will ensure that memory space is large enough and correctly aligned to access 'long long' fields. +*/ + + +unsigned int XXH32_intermediateDigest (void* state); +/* +This function does the same as XXH32_digest(), generating a 32-bit hash, +but preserve memory context. +This way, it becomes possible to generate intermediate hashes, and then continue feeding data with XXH32_update(). +To free memory context, use XXH32_digest(), or free(). +*/ + + + +//**************************** +// Deprecated function names +//**************************** +// The following translations are provided to ease code transition +// You are encouraged to no longer this function names +#define XXH32_feed XXH32_update +#define XXH32_result XXH32_digest +#define XXH32_getIntermediateResult XXH32_intermediateDigest + + + +#if defined (__cplusplus) +} +#endif