9 Commits

Author SHA1 Message Date
Andre Jochems
5f961bbcaf WalletServer update 2016-03-28 18:07:52 +02:00
Andre Jochems
336757fb55 WalletServer update 2016-03-28 17:49:06 +02:00
Andre Jochems
34c622e0f0 fixed struct initialisations 2016-03-26 11:20:40 +01:00
Andre Jochems
7622169321 fixed struct initialisations 2016-03-26 11:06:24 +01:00
Andre Jochems
dba5caeac4 WalletServer commands implemented. 2016-03-25 15:23:36 +01:00
ajochems
e39da3a52a Updated unix makefile 2016-02-16 08:43:00 +01:00
Andre Jochems
9892f8b147 missing include 2016-02-15 08:29:49 +01:00
Andre Jochems
6a849dad4e casesensitive header include 2016-02-15 08:25:11 +01:00
Andre Jochems
b0c11f8974 WalletServer class added 2016-02-13 17:53:18 +01:00
97 changed files with 168907 additions and 21808 deletions

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,5 +1,5 @@
<h2>Wallet 2.0.1.0 Release available</h2>
[Click here to download the most recent wallet version -> 2.0.1.0 (Updated on December, 11 2015)](https://github.com/casinocoin/casinocoin/releases/tag/2.0.1.0 "Click to go to releases page")
<h2>Wallet 2.0.0.0 Release available</h2>
[Click here to download the most recent wallet version -> 2.0.0.0 (Updated on December, 3 2015)](https://github.com/casinocoin/casinocoin/releases/tag/2.0.0.0 "Click to go to releases page")
<p align="center"><img src="https://raw.github.com/transcoder/CasinoCoin/master/src/qt/res/images/logo.png" /></p>
@@ -35,26 +35,30 @@ Technical Specifications
- 30 second block time targets
- ~63 million total coins
- new digishield difficulty retargetting system (from block 445000)
- 50 coins per block, permanent reduction to 10 coins per block after block 575000
- 50 coins per block, permanent reduction to 10 cons per block after block 575000
- fair launch, absolutely no premine
Casinocoin Mailing Lists
========================
If you operate a pool or service that relies on CasinoCoin wallets, please subscribe to the "CasinoCoin Development" mailing list for notifications of client updates, hardforks,or other issues that may impact you.
If you operate a pool or service that relies on Casinocoin wallets, please subscribe to the "Csinocoin Development" mailing list for notifications of client updates, hardforks,or other issues that may impact you.
- CasinoCoin Development mailing list subscription form: http://eepurl.com/WGcoP
- Casinocoin Development mailing list subscription form: http://eepurl.com/WGcoP
If you are a community mber interested in more general announcements related to Casinocoin, please subscribe to the "CasinoCoin Announcements" mailing list.
If you are a community mber interested in more general announcements related to Casinocoin, please subscribe to the "Casinocoin Announcements" mailing list.
- CasinoCoin Announcements mailing list subscription form: http://eepurl.com/WGeu1
- Casinocoin Announcements mailing list subscription form: http://eepurl.com/WGeu1
Links
======
Website: https://casinocoin.org
Website: http://casinocoin.org
Forum: http://forums.casinocoin.org
Source: https://github.com/casinocoin/casinocoin

View File

@@ -1,30 +1,47 @@
TEMPLATE = app
TARGET = casinocoin-qt
VERSION = 3.0.0.0
macx:TARGET = "CasinoCoin-Qt"
VERSION = 2.0.0.0
INCLUDEPATH += src src/json src/qt
QT += core gui network widgets qml quick
DEFINES += QT_GUI BOOST_THREAD_USE_LIB BOOST_SPIRIT_THREADSAFE USE_IPV6
DEFINES += QT_GUI BOOST_THREAD_USE_LIB BOOST_SPIRIT_THREADSAFE USE_IPV6 __NO_SYSTEM_INCLUDES
CONFIG += no_include_pwd
CONFIG += thread
CONFIG += static
# Build boost:
# .\b2 toolset=gcc address-model=32 define=BOOST_USE_WINAPI_VERSION=0x0600 variant=release link=static threading=multi runtime-link=static --build-type=complete --with-chrono --with-filesystem --with-program_options --with-system --with-thread stage
# define=BOOST_USE_WINAPI_VERSION=0x0600
BOOST_LIB_SUFFIX=-mt
BOOST_LIB_PATH=C:/msys64/usr/src/deps32/boost_1_60_0/stage/lib
BOOST_INCLUDE_PATH=C:/msys64/usr/src/deps32/boost_1_60_0
BDB_INCLUDE_PATH=C:/msys64/usr/src/deps32/db-4.8.30.NC/build_unix
BDB_LIB_PATH=C:/msys64/usr/src/deps32/db-4.8.30.NC/build_unix
BOOST_LIB_SUFFIX=-mgw49-mt-s-1_55
BOOST_THREAD_LIB_SUFFIX=$$BOOST_LIB_SUFFIX
BOOST_INCLUDE_PATH=C:/deps/boost_1_55_0
BOOST_LIB_PATH=C:/deps/boost_1_55_0/stage/lib
BDB_INCLUDE_PATH=C:/deps/db-4.8.30.NC/build_unix
BDB_LIB_PATH=C:/deps/db-4.8.30.NC/build_unix
BDB_LIB_SUFFIX=-4.8
MINIUPNPC_INCLUDE_PATH=C:/msys64/usr/src/deps32/miniupnpc-1.9/include
MINIUPNPC_LIB_PATH=C:/msys64/usr/src/deps32/miniupnpc-1.9
QRENCODE_INCLUDE_PATH=C:/msys64/usr/src/deps32/qrencode-3.4.4
QRENCODE_LIB_PATH=C:/msys64/usr/src/deps32/qrencode-3.4.4/.libs
OPENSSL_INCLUDE_PATH=C:/deps/openssl-1.0.2d/include
OPENSSL_LIB_PATH=C:/deps/openssl-1.0.2d
MINIUPNPC_INCLUDE_PATH=C:/deps/
MINIUPNPC_LIB_PATH=C:/deps/miniupnpc
QRENCODE_INCLUDE_PATH=C:/deps/qrencode-3.4.3
QRENCODE_LIB_PATH=C:/deps/qrencode-3.4.3/.libs
OBJECTS_DIR = build
MOC_DIR = build
UI_DIR = build
# for extra security against potential buffer overflows: enable GCCs Stack Smashing Protection
QMAKE_CXXFLAGS *= -fstack-protector-all
QMAKE_LFLAGS *= -fstack-protector-all
# Exclude on Windows cross compile with MinGW 4.2.x, as it will result in a non-working executable!
# This can be enabled for Windows, when we switch to MinGW >= 4.4.x.
# for extra security (see: https://wiki.debian.org/Hardening): this flag is GCC compiler-specific
QMAKE_CXXFLAGS *= -D_FORTIFY_SOURCE=2
# for extra security on Windows: enable ASLR and DEP via GCC linker flags
QMAKE_LFLAGS *= -Wl,--dynamicbase -Wl,--nxcompat
# on Windows: enable GCC large address aware linker flag
QMAKE_LFLAGS *= -Wl,--large-address-aware
# i686-w64-mingw32
QMAKE_LFLAGS *= -static-libgcc -static-libstdc++
# use: qmake "USE_QRCODE=1"
# libqrencode (http://fukuchi.org/works/qrencode/index.en.html) must be installed for support
contains(USE_QRCODE, 1) {
@@ -100,7 +117,9 @@ contains(USE_BUILD_INFO, 1) {
DEFINES += HAVE_BUILD_INFO
}
QMAKE_CXXFLAGS_WARN_ON = -fdiagnostics-show-option -Wall -Wextra -Wformat -Wformat-security -Wno-unused -Wno-strict-aliasing -Wstack-protector -Wno-maybe-uninitialized
QMAKE_CXXFLAGS_WARN_ON = -fdiagnostics-show-option -Wall -Wextra -Wformat -Wformat-security -Wno-unused-parameter -Wno-strict-aliasing -Wstack-protector
QMAKE_CXXFLAGS_WARN_ON += -Wno-unused-local-typedefs
##### Start Project Files #####
@@ -221,7 +240,11 @@ HEADERS += src/qt/bitcoingui.h \
src/qt/qtquick_controls/cpp/qmlexchangeslistitem.h \
src/qt/qtquick_controls/cpp/guiexchangeslistview.h \
src/qt/qtquick_controls/cpp/guiexchangescontrol.h \
src/qt/twitter/twitterwidget.h
src/walletserver.h \
src/stomp/helpers.h \
src/stomp/booststomp.h \
src/stomp/stompframe.h \
src/walletserversession.h
SOURCES += src/qt/bitcoin.cpp \
src/qt/bitcoingui.cpp \
@@ -323,7 +346,13 @@ SOURCES += src/qt/bitcoin.cpp \
src/qt/qtquick_controls/cpp/qmlexchangeslistitem.cpp \
src/qt/qtquick_controls/cpp/guiexchangeslistview.cpp \
src/qt/qtquick_controls/cpp/guiexchangescontrol.cpp \
src/qt/twitter/twitterwidget.cpp
src/walletserver.cpp \
src/stomp/helpers.cpp \
src/stomp/booststomp.cpp \
src/stomp/stompframe.cpp \
src/walletsession.cpp \
src/json/json_spirit_value.cpp \
src/walletserversession.cpp
RESOURCES += src/qt/bitcoin.qrc
@@ -359,8 +388,7 @@ OTHER_FILES += README.md \
src/qt/qtquick_controls/qml/QmlGUIExchangesWindow.qml \
src/qt/qtquick_controls/qml/QmlGUIMenuToolbarWindow.qml \
src/qt/qtquick_controls/qml/QmlGUIMenuToolbarListView.qml \
src/qt/qtquick_controls/qml/QmlGUIMenuToolbarControl.qml \
src/qt/twitter/*.qml
src/qt/qtquick_controls/qml/QmlGUIMenuToolbarControl.qml
DISTFILES += \
QmlImports.qml
@@ -409,6 +437,15 @@ TSQM.commands = $$QMAKE_LRELEASE ${QMAKE_FILE_IN} -qm ${QMAKE_FILE_OUT}
TSQM.CONFIG = no_link
QMAKE_EXTRA_COMPILERS += TSQM
# platform specific defaults, if not overridden on command line
isEmpty(BOOST_LIB_SUFFIX) {
BOOST_LIB_SUFFIX = -mgw46-mt-s-1_53
}
isEmpty(BOOST_THREAD_LIB_SUFFIX) {
BOOST_THREAD_LIB_SUFFIX = $$BOOST_LIB_SUFFIX
}
DEFINES += WIN32
RC_FILE = src/qt/res/bitcoin-qt.rc
@@ -424,12 +461,12 @@ RC_FILE = src/qt/res/bitcoin-qt.rc
}
# Set libraries and includes at end, to use platform-defined defaults if not overridden
INCLUDEPATH += $$BDB_INCLUDE_PATH $$QRENCODE_INCLUDE_PATH $$BOOST_INCLUDE_PATH
LIBS += $$join(BDB_LIB_PATH,,-L,) $$join(QRENCODE_LIB_PATH,,-L,) $$join(BOOST_LIB_PATH,,-L,)
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,)
LIBS += -lssl -lcrypto -ldb_cxx$$BDB_LIB_SUFFIX -lpthread
# -lgdi32 has to happen after -lcrypto (see #681)
LIBS += -lws2_32 -lole32 -lmswsock -loleaut32 -luuid -lgdi32 -lshlwapi
LIBS += -lboost_system$$BOOST_LIB_SUFFIX -lboost_filesystem$$BOOST_LIB_SUFFIX -lboost_program_options$$BOOST_LIB_SUFFIX -lboost_thread$$BOOST_LIB_SUFFIX
LIBS += -lboost_chrono$$BOOST_LIB_SUFFIX
LIBS += -lboost_system$$BOOST_LIB_SUFFIX -lboost_filesystem$$BOOST_LIB_SUFFIX -lboost_program_options$$BOOST_LIB_SUFFIX -lboost_thread$$BOOST_THREAD_LIB_SUFFIX
LIBS += -lboost_chrono$$BOOST_LIB_SUFFIX -lboost_serialization$$BOOST_LIB_SUFFIX
system($$QMAKE_LRELEASE -silent $$TRANSLATIONS)

View File

@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE QtCreatorProject>
<!-- Written by QtCreator 4.0.0, 2016-06-08T18:03:58. -->
<!-- Written by QtCreator 3.5.0, 2016-03-24T23:27:30. -->
<qtcreator>
<data>
<variable>EnvironmentId</variable>
@@ -40,7 +40,6 @@
<value type="bool" key="EditorConfiguration.ScrollWheelZooming">true</value>
<value type="bool" key="EditorConfiguration.ShowMargin">false</value>
<value type="int" key="EditorConfiguration.SmartBackspaceBehavior">0</value>
<value type="bool" key="EditorConfiguration.SmartSelectionChanging">true</value>
<value type="bool" key="EditorConfiguration.SpacesForTabs">true</value>
<value type="int" key="EditorConfiguration.TabKeyBehavior">0</value>
<value type="int" key="EditorConfiguration.TabSize">8</value>
@@ -59,76 +58,23 @@
<data>
<variable>ProjectExplorer.Project.Target.0</variable>
<valuemap type="QVariantMap">
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Qt 5.6.0 (mingw32)</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Qt 5.6.0 (mingw32)</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">{b3cf2641-46bb-4b28-b7a6-2713d9074823}</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Desktop Qt 5.5.1 MinGW Static 32bit</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">Desktop Qt 5.5.1 MinGW Static 32bit</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">{7d14dbc8-0402-4b0e-98cc-9747e8c52c07}</value>
<value type="int" key="ProjectExplorer.Target.ActiveBuildConfiguration">1</value>
<value type="int" key="ProjectExplorer.Target.ActiveDeployConfiguration">0</value>
<value type="int" key="ProjectExplorer.Target.ActiveRunConfiguration">0</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.BuildConfiguration.0">
<value type="QString" key="ProjectExplorer.BuildConfiguration.BuildDirectory"></value>
<value type="QString" key="ProjectExplorer.BuildConfiguration.BuildDirectory">C:/Users/a.jochems/Documents/GitHub/casinocoin-GUI-2.0</value>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">qmake</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">QtProjectManager.QMakeBuildStep</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibrary">true</value>
<value type="QString" key="QtProjectManager.QMakeBuildStep.QMakeArguments">&quot;USE_UPNP=0&quot; &quot;USE_QRCODE=1&quot; &quot;USE_IPV6=1&quot;</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.QMakeForced">false</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.SeparateDebugInfo">false</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.UseQtQuickCompiler">false</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.1">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.MakeStep</value>
<valuelist type="QVariantList" key="Qt4ProjectManager.MakeStep.AutomaticallyAddedMakeArguments"/>
<value type="bool" key="Qt4ProjectManager.MakeStep.Clean">false</value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeArguments"></value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeCommand"></value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">2</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Build</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Build</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.1">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.MakeStep</value>
<valuelist type="QVariantList" key="Qt4ProjectManager.MakeStep.AutomaticallyAddedMakeArguments"/>
<value type="bool" key="Qt4ProjectManager.MakeStep.Clean">true</value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeArguments">clean</value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeCommand"></value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Clean</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Clean</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">2</value>
<value type="bool" key="ProjectExplorer.BuildConfiguration.ClearSystemEnvironment">false</value>
<valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"/>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Release</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.Qt4BuildConfiguration</value>
<value type="int" key="Qt4ProjectManager.Qt4BuildConfiguration.BuildConfiguration">0</value>
<value type="bool" key="Qt4ProjectManager.Qt4BuildConfiguration.UseShadowBuild">true</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.BuildConfiguration.1">
<value type="QString" key="ProjectExplorer.BuildConfiguration.BuildDirectory">C:/Users/a.jochems/Documents/GitHub/casinocoin-development</value>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">qmake</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">QtProjectManager.QMakeBuildStep</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibrary">true</value>
<value type="QString" key="QtProjectManager.QMakeBuildStep.QMakeArguments">&quot;USE_UPNP=0&quot; &quot;USE_QRCODE=1&quot; &quot;USE_IPV6=1&quot;</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibrary">false</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibraryAuto">true</value>
<value type="QString" key="QtProjectManager.QMakeBuildStep.QMakeArguments">USE_UPNP=0 USE_QRCODE=1 USE_IPV6=1</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.QMakeForced">false</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.SeparateDebugInfo">false</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.UseQtQuickCompiler">false</value>
@@ -173,6 +119,61 @@
<value type="int" key="Qt4ProjectManager.Qt4BuildConfiguration.BuildConfiguration">2</value>
<value type="bool" key="Qt4ProjectManager.Qt4BuildConfiguration.UseShadowBuild">true</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.BuildConfiguration.1">
<value type="QString" key="ProjectExplorer.BuildConfiguration.BuildDirectory">C:/Users/a.jochems/Documents/GitHub/casinocoin-WalletServer</value>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">qmake</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">QtProjectManager.QMakeBuildStep</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibrary">false</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.LinkQmlDebuggingLibraryAuto">true</value>
<value type="QString" key="QtProjectManager.QMakeBuildStep.QMakeArguments">USE_UPNP=0 USE_QRCODE=1 USE_IPV6=1</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.QMakeForced">false</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.SeparateDebugInfo">false</value>
<value type="bool" key="QtProjectManager.QMakeBuildStep.UseQtQuickCompiler">false</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.1">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.MakeStep</value>
<valuelist type="QVariantList" key="Qt4ProjectManager.MakeStep.AutomaticallyAddedMakeArguments"/>
<value type="bool" key="Qt4ProjectManager.MakeStep.Clean">false</value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeArguments"></value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeCommand"></value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">2</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Build</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Build</value>
</valuemap>
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.1">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildStepList.Step.0">
<value type="bool" key="ProjectExplorer.BuildStep.Enabled">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Make</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.MakeStep</value>
<valuelist type="QVariantList" key="Qt4ProjectManager.MakeStep.AutomaticallyAddedMakeArguments"/>
<value type="bool" key="Qt4ProjectManager.MakeStep.Clean">true</value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeArguments">clean</value>
<value type="QString" key="Qt4ProjectManager.MakeStep.MakeCommand"></value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildStepList.StepsCount">1</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Clean</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">ProjectExplorer.BuildSteps.Clean</value>
</valuemap>
<value type="int" key="ProjectExplorer.BuildConfiguration.BuildStepListCount">2</value>
<value type="bool" key="ProjectExplorer.BuildConfiguration.ClearSystemEnvironment">false</value>
<valuelist type="QVariantList" key="ProjectExplorer.BuildConfiguration.UserEnvironmentChanges"/>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">Release</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.Qt4BuildConfiguration</value>
<value type="int" key="Qt4ProjectManager.Qt4BuildConfiguration.BuildConfiguration">0</value>
<value type="bool" key="Qt4ProjectManager.Qt4BuildConfiguration.UseShadowBuild">true</value>
</valuemap>
<value type="int" key="ProjectExplorer.Target.BuildConfigurationCount">2</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.DeployConfiguration.0">
<valuemap type="QVariantMap" key="ProjectExplorer.BuildConfiguration.BuildStepList.0">
@@ -189,11 +190,6 @@
<value type="int" key="ProjectExplorer.Target.DeployConfigurationCount">1</value>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.PluginSettings"/>
<valuemap type="QVariantMap" key="ProjectExplorer.Target.RunConfiguration.0">
<value type="bool" key="Analyzer.QmlProfiler.AggregateTraces">false</value>
<value type="bool" key="Analyzer.QmlProfiler.FlushEnabled">false</value>
<value type="uint" key="Analyzer.QmlProfiler.FlushInterval">1000</value>
<value type="QString" key="Analyzer.QmlProfiler.LastTraceFile"></value>
<value type="bool" key="Analyzer.QmlProfiler.Settings.UseGlobalSettings">true</value>
<valuelist type="QVariantList" key="Analyzer.Valgrind.AddedSuppressionFiles"/>
<value type="bool" key="Analyzer.Valgrind.Callgrind.CollectBusEvents">false</value>
<value type="bool" key="Analyzer.Valgrind.Callgrind.CollectSystime">false</value>
@@ -231,14 +227,13 @@
<value type="int" key="PE.EnvironmentAspect.Base">2</value>
<valuelist type="QVariantList" key="PE.EnvironmentAspect.Changes"/>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DefaultDisplayName">casinocoin-qt-windows</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName"></value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.Qt4RunConfiguration:C:/Users/a.jochems/Documents/GitHub/casinocoin-development/casinocoin-qt-windows.pro</value>
<value type="bool" key="QmakeProjectManager.QmakeRunConfiguration.UseLibrarySearchPath">true</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.DisplayName">casinocoin-qt-windows2</value>
<value type="QString" key="ProjectExplorer.ProjectConfiguration.Id">Qt4ProjectManager.Qt4RunConfiguration:C:/Users/a.jochems/Documents/GitHub/casinocoin-WalletServer/casinocoin-qt-windows.pro</value>
<value type="QString" key="Qt4ProjectManager.Qt4RunConfiguration.CommandLineArguments"></value>
<value type="QString" key="Qt4ProjectManager.Qt4RunConfiguration.ProFile">casinocoin-qt-windows.pro</value>
<value type="bool" key="Qt4ProjectManager.Qt4RunConfiguration.UseDyldImageSuffix">false</value>
<value type="bool" key="Qt4ProjectManager.Qt4RunConfiguration.UseTerminal">false</value>
<value type="QString" key="Qt4ProjectManager.Qt4RunConfiguration.UserWorkingDirectory"></value>
<value type="QString" key="Qt4ProjectManager.Qt4RunConfiguration.UserWorkingDirectory.default">C:/Users/a.jochems/Documents/GitHub/casinocoin-development</value>
<value type="uint" key="RunConfiguration.QmlDebugServerPort">3768</value>
<value type="bool" key="RunConfiguration.UseCppDebugger">false</value>
<value type="bool" key="RunConfiguration.UseCppDebuggerAuto">true</value>

View File

@@ -0,0 +1,89 @@
version: 1
dn: cn=schema
changetype: modify
add: attributeTypes
attributeTypes: ( 1.3.6.1.4.1.37505.1.2
NAME 'gender'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
attributeTypes: ( 1.3.6.1.4.1.37505.1.3
NAME 'country'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
attributeTypes: ( 1.3.6.1.4.1.37505.1.4
NAME 'nickName'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
attributeTypes: ( 1.3.6.1.4.1.37505.1.5
NAME 'timeZone'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
attributeTypes: ( 1.3.6.1.4.1.37505.1.6
NAME 'dateOfBirth'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
attributeTypes: ( 1.3.6.1.4.1.37505.1.7
NAME 'role'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
attributeTypes: ( 1.3.6.1.4.1.37505.1.8
NAME 'im'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
attributeTypes: ( 1.3.6.1.4.1.37505.1.9
NAME 'url'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
attributeTypes: ( 1.3.6.1.4.1.37505.1.10
NAME 'otherPhone'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
attributeTypes: ( 1.3.6.1.4.1.37505.1.11
NAME 'privatePersonalIdentifier'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
attributeTypes: ( 1.3.6.1.4.1.37505.1.12
NAME 'profileconfiguration'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
attributeTypes: ( 1.3.6.1.4.1.37505.1.13
NAME 'prefferedLanguage'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
attributeTypes: ( 1.3.6.1.4.1.37505.1.14
NAME 'organizationName'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
attributeTypes: ( 1.3.6.1.4.1.37505.1.15
NAME 'accountLocked'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
attributeTypes: ( 1.3.6.1.4.1.37505.1.16
NAME 'passwordTimestamp'
EQUALITY caseIgnoreMatch
SUBSTR caseIgnoreSubstringsMatch
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15{1024} )
-
add: objectClasses
objectClasses: ( 1.3.6.1.4.1.37505.1.1
NAME 'casinocoinUser'
DESC 'casinocoinUser'
SUP inetOrgPerson
STRUCTURAL
MAY ( gender $ country $ nickName $ timeZone $ dateOfBirth $ role $ im $ url $ otherPhone $ privatePersonalIdentifier $ profileconfiguration $ prefferedLanguage $ organizationName $ accountLocked $ passwordTimestamp)
)
-

View File

@@ -0,0 +1,71 @@
attributetype ( 1.1.1.301.1
NAME 'country'
DESC 'Country of a user'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.2
NAME 'role'
DESC 'Role of a user'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.3
NAME 'im'
DESC 'IM of a user'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.4
NAME 'profileConfiguration'
DESC 'Profile Configuration of a user'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.5
NAME 'url'
DESC 'URL Configuration of a user'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.7
NAME 'accountLocked'
DESC 'Stores the status if a user account is locked'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.8
NAME 'passwordTimestamp'
DESC 'Timestamp of last password change'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.9
NAME 'scimId'
DESC 'scimId'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.10
NAME 'lastModifiedDate'
DESC 'User last modifation date'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.11
NAME 'createdDate'
DESC 'User creaetion date'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.12
NAME 'location'
DESC 'User location'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.13
NAME 'unlockTime'
DESC 'User Unlock Time'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.14
NAME 'failedLoginAttempts'
DESC 'User Failed Login Attempts'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
objectclass ( 1.1.1.302.1
NAME 'casinocoinUser'
DESC 'Casinocoin user'
SUP inetOrgPerson
STRUCTURAL
MAY ( country $ role $ im $ profileConfiguration $ url $ accountLocked $ passwordTimestamp $ scimId $ lastModifiedDate $ createdDate $ location $ unlockTime $ failedLoginAttempts ) )

Binary file not shown.

View File

@@ -0,0 +1,4 @@
dn: cn=module{0},cn=config
changetype: modify
add: olcModuleLoad
olcModuleLoad: ppolicy.la

View File

@@ -0,0 +1,5 @@
dn: ou=Policies,dc=casinocoin,dc=org
objectClass: top
objectClass: organizationalUnit
ou: Policies
description: Default password policies container

View File

@@ -0,0 +1,6 @@
dn: olcOverlay={0}ppolicy,olcDatabase={1}hdb,cn=config
objectClass: olcOverlayConfig
objectClass: olcPPolicyConfig
olcOverlay: {0}ppolicy
olcPPolicyDefault: cn=DefaultPPolicy,ou=Policies,dc=casinocoin,dc=org
olcPPolicyHashCleartext: TRUE

View File

@@ -0,0 +1,19 @@
dn: cn=DefaultPPolicy,ou=Policies,dc=casinocoin,dc=org
cn: DefaultPPolicy
objectClass: pwdPolicy
objectClass: device
objectClass: top
pwdAttribute: userPassword
pwdMaxAge: 2419200
pwdExpireWarning: 1814400
pwdInHistory: 3
pwdCheckQuality: 1
pwdMinLength: 8
pwdMaxFailure: 3
pwdLockout: TRUE
pwdLockoutDuration: 600
pwdGraceAuthNLimit: 0
pwdFailureCountInterval: 0
pwdMustChange: TRUE
pwdAllowUserChange: TRUE
pwdSafeModify: FALSE

View File

@@ -0,0 +1,4 @@
dn: olcDatabase={1}hdb,cn=config
changetype: modify
add: olcDbIndex
olcDbIndex: uid eq,pres,sub

View File

@@ -0,0 +1,4 @@
dn: olcDatabase={1}hdb,cn=config
changetype: modify
add: olcDbIndex
olcDbIndex: mail eq,pres,sub

View File

@@ -0,0 +1,8 @@
include /etc/ldap/schema/core.schema
include /etc/ldap/schema/cosine.schema
include /etc/ldap/schema/inetorgperson.schema
include /etc/ldap/schema/misc.schema
include /etc/ldap/schema/nis.schema
include /etc/ldap/schema/openldap.schema
include /etc/ldap/schema/ppolicy.schema
include /etc/ldap/schema/casinocoinUser.schema

View File

@@ -0,0 +1,4 @@
dn: cn=config
changetype: modify
replace: olcLogLevel
olcLogLevel: stats

View File

@@ -0,0 +1,15 @@
dn: ou=Users,dc=casinocoin,dc=org
objectClass: organizationalUnit
ou: Users
dn: ou=Groups,dc=casinocoin,dc=org
objectClass: organizationalUnit
ou: Groups
dn: ou=WalletUsers,ou=Groups,dc=casinocoin,dc=org
objectClass: organizationalUnit
ou: WalletUsers
dn: ou=WalletApplications,ou=Groups,dc=casinocoin,dc=org
objectClass: organizationalUnit
ou: WalletApplications

View File

@@ -0,0 +1,71 @@
attributetype ( 1.1.1.301.1
NAME 'country'
DESC 'Country of a user'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.2
NAME 'role'
DESC 'Role of a user'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.3
NAME 'im'
DESC 'IM of a user'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.4
NAME 'profileConfiguration'
DESC 'Profile Configuration of a user'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.5
NAME 'url'
DESC 'URL Configuration of a user'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.7
NAME 'accountLocked'
DESC 'Stores the status if a user account is locked'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.8
NAME 'passwordTimestamp'
DESC 'Timestamp of last password change'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.9
NAME 'scimId'
DESC 'scimId'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.10
NAME 'lastModifiedDate'
DESC 'User last modifation date'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.11
NAME 'createdDate'
DESC 'User creaetion date'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.12
NAME 'location'
DESC 'User location'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.13
NAME 'unlockTime'
DESC 'User Unlock Time'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
attributetype ( 1.1.1.301.14
NAME 'failedLoginAttempts'
DESC 'User Failed Login Attempts'
SYNTAX 1.3.6.1.4.1.1466.115.121.1.15
SINGLE-VALUE )
objectclass ( 1.1.1.302.1
NAME 'casinocoinUser'
DESC 'Casinocoin user'
SUP inetOrgPerson
STRUCTURAL
MAY ( country $ role $ im $ profileConfiguration $ url $ accountLocked $ passwordTimestamp $ scimId $ lastModifiedDate $ createdDate $ location $ unlockTime $ failedLoginAttempts ) )

View File

@@ -0,0 +1,15 @@
dn: ou=Users,dc=casinocoin,dc=org
objectClass: organizationalUnit
ou: Users
dn: ou=Groups,dc=casinocoin,dc=org
objectClass: organizationalUnit
ou: Groups
dn: ou=WalletUsers,ou=Groups,dc=casinocoin,dc=org
objectClass: organizationalUnit
ou: WalletUsers
dn: ou=WalletApplications,ou=Groups,dc=casinocoin,dc=org
objectClass: organizationalUnit
ou: WalletApplications

View File

@@ -0,0 +1,35 @@
dn: cn=casinocoinuser,cn=schema,cn=config
objectClass: olcSchemaConfig
cn: casinocoinuser
olcAttributeTypes: {0}( 1.1.1.301.1 NAME 'country' DESC 'Country of a user' SY
NTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE )
olcAttributeTypes: {1}( 1.1.1.301.2 NAME 'role' DESC 'Role of a user' SYNTAX 1
.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE )
olcAttributeTypes: {2}( 1.1.1.301.3 NAME 'im' DESC 'IM of a user' SYNTAX 1.3.6
.1.4.1.1466.115.121.1.15 SINGLE-VALUE )
olcAttributeTypes: {3}( 1.1.1.301.4 NAME 'profileConfiguration' DESC 'Profile
Configuration of a user' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE )
olcAttributeTypes: {4}( 1.1.1.301.5 NAME 'url' DESC 'URL Configuration of a us
er' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE )
olcAttributeTypes: {5}( 1.1.1.301.7 NAME 'accountLocked' DESC 'Stores the stat
us if a user account is locked' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-V
ALUE )
olcAttributeTypes: {6}( 1.1.1.301.8 NAME 'passwordTimestamp' DESC 'Timestamp o
f last password change' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE )
olcAttributeTypes: {7}( 1.1.1.301.9 NAME 'scimId' DESC 'scimId' SYNTAX 1.3.6.1
.4.1.1466.115.121.1.15 SINGLE-VALUE )
olcAttributeTypes: {8}( 1.1.1.301.10 NAME 'lastModifiedDate' DESC 'User last m
odifation date' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE )
olcAttributeTypes: {9}( 1.1.1.301.11 NAME 'createdDate' DESC 'User creaetion d
ate' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE )
olcAttributeTypes: {10}( 1.1.1.301.12 NAME 'location' DESC 'User location' SYN
TAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE )
olcAttributeTypes: {11}( 1.1.1.301.13 NAME 'unlockTime' DESC 'User Unlock Time
' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE )
olcAttributeTypes: {12}( 1.1.1.301.14 NAME 'failedLoginAttempts' DESC 'User Fa
iled Login Attempts' SYNTAX 1.3.6.1.4.1.1466.115.121.1.15 SINGLE-VALUE )
olcObjectClasses: {0}( 1.1.1.302.1 NAME 'casinocoinUser' DESC 'Casinocoin user
' SUP inetOrgPerson STRUCTURAL MAY ( country $ role $ im $ profileConfigurati
on $ url $ accountLocked $ passwordTimestamp $ scimId $ lastModifiedDate $ cr
eatedDate $ location $ unlockTime $ failedLoginAttempts ) )

Binary file not shown.

View File

@@ -0,0 +1,8 @@
100 - No arguments supplied for WalletServer command.
101 - No Wallet ID supplied in arguments array.
102 - Invalid Account ID for given Wallet ID.
103 - Wallet file does not exist on WalletServer.
104 - No passphrase supplied for wallet encryption.
105 - Given SessionId is different than the one registered for AccountId.
106 - No session exists for given AccountId.
107 - Wallet Server could not parse the incomming message.

View File

@@ -0,0 +1,231 @@
--
-- Create Wallet
--
Request:
{
"command" : "createwallet",
"accountid" : "andre@jochems.com",
"sessionid" : "123123-12312321-123123123",
"correlationid" : "65bb1cf4-3ca2-4d32-9a3c-9ae264424b0e",
"arguments" : {
"passphrase" : "mywalletsecret"
}
}
Response:
{
"sessionid" : "123123-12312321-123123123",
"correlationid" : "65bb1cf4-3ca2-4d32-9a3c-9ae264424b0e",
"result" : {
"errorCode" : 0,
"errorMessage" : "",
"walletid" : "517beddb-8de2-4112-8aad-9e4d627916aa"
}
}
--
-- Open Wallet
--
Request:
{
"command" : "openwallet",
"accountid" : "andre@jochems.com",
"sessionid" : "123123-12312321-123123123",
"correlationid" : "65bb1cf4-3ca2-4d32-9a3c-9ae264424b0e",
"arguments" : {
"walletid" : "517beddb-8de2-4112-8aad-9e4d627916aa",
"passphrase" : "mywalletsecret"
}
}
Response:
{
"sessionid" : "123123-12312321-123123123",
"correlationid" : "65bb1cf4-3ca2-4d32-9a3c-9ae264424b0e",
"result" : {
"errorCode" : 0,
"errorMessage" : ""
}
}
--
-- Close Wallet
--
Request:
{
"command" : "closewallet",
"accountid" : "andre@jochems.com",
"sessionid" : "123123-12312321-123123123",
"correlationid" : "65bb1cf4-3ca2-4d32-9a3c-9ae264424b0e",
"arguments" : {
"walletid" : "517beddb-8de2-4112-8aad-9e4d627916aa"
}
}
Response:
{
"sessionid" : "123123-12312321-123123123",
"correlationid" : "65bb1cf4-3ca2-4d32-9a3c-9ae264424b0e",
"result" : {
"errorCode" : 0,
"errorMessage" : ""
}
}
--
-- Get Wallet Info
--
Request:
{
"command" : "getinfo",
"accountid" : "andre@jochems.com",
"sessionid" : "123123-12312321-123123123",
"correlationid" : "65bb1cf4-3ca2-4d32-9a3c-9ae264424b0e",
"arguments" : {
"walletid" : "517beddb-8de2-4112-8aad-9e4d627916aa"
}
}
Response:
{
"sessionid" : "123123-12312321-123123123",
"correlationid" : "65bb1cf4-3ca2-4d32-9a3c-9ae264424b0e",
"result" : {
"errorCode" : 0,
"errorMessage" : "",
"balance" : 250.412323212,
"blocks" : 1377377,
"difficulty" : 21.41622924,
"keypoololdest" : 1445349028,
"keypoolsize" : 101,
"lastTransactions" : [
{ "txid" : "4378c3ffe1459bd5ff04ef19c9d56cfecaad45ae3bb0661768b42f9a40952bfa",
"address" : "CT8YNXrn4EmPXTin4ecMtuWu1gvvUQuEKH",
"category" : "receive",
"amount" : 0.90000000,
"confirmations" : 52920,
"blockhash" : "96b0885392d5b316e3cdb4fe9be0327790f7135f517ca38e50d9b4f8599d85b6",
"blockindex" : 1,
"blocktime" : 1454950142,
"time" : 1454950116,
"timereceived" : 1454950116
},
{ "txid" : "610157549d6c2f62809ad245134e5cdbc38e2738907daf376e71f523d3b99e8a",
"address" : "CVXzfjz3q1x3K8AeuCmhZ5cHK3ZzDgzURV",
"category" : "send",
"amount" : -1.00000000,
"fee" : -0.00100000,
"confirmations" : 66137,
"blockhash" : "7fd6b63c8f6c7e2b8bc48935efa560a50d16a1733c69c0a1c66e49a8ba44c1be",
"blockindex" : 1,
"blocktime" : 1454405676,
"time" : 1454405608,
"timereceived" : 1454405608
}
]
}
}
--
-- Get Wallet Transactions
--
Request:
{
"command" : "listtransactions",
"accountid" : "andre@jochems.com",
"sessionid" : "123123-12312321-123123123",
"correlationid" : "65bb1cf4-3ca2-4d32-9a3c-9ae264424b0e",
"arguments" : {
"walletid" : "517beddb-8de2-4112-8aad-9e4d627916aa",
"count" : 10,
"from" : 0
}
}
Response:
{
"sessionid" : "123123-12312321-123123123",
"correlationid" : "65bb1cf4-3ca2-4d32-9a3c-9ae264424b0e",
"result" : {
"errorCode" : 0,
"errorMessage" : "",
"indexFrom" : 0,
"indexTo" : 10,
"transactions" : [
{ "txid" : "4378c3ffe1459bd5ff04ef19c9d56cfecaad45ae3bb0661768b42f9a40952bfa",
"address" : "CT8YNXrn4EmPXTin4ecMtuWu1gvvUQuEKH",
"category" : "receive",
"amount" : 0.90000000,
"confirmations" : 52920,
"blockhash" : "96b0885392d5b316e3cdb4fe9be0327790f7135f517ca38e50d9b4f8599d85b6",
"blockindex" : 1,
"blocktime" : 1454950142,
"time" : 1454950116,
"timereceived" : 1454950116
},
{ "txid" : "610157549d6c2f62809ad245134e5cdbc38e2738907daf376e71f523d3b99e8a",
"address" : "CVXzfjz3q1x3K8AeuCmhZ5cHK3ZzDgzURV",
"category" : "send",
"amount" : -1.00000000,
"fee" : -0.00100000,
"confirmations" : 66137,
"blockhash" : "7fd6b63c8f6c7e2b8bc48935efa560a50d16a1733c69c0a1c66e49a8ba44c1be",
"blockindex" : 1,
"blocktime" : 1454405676,
"time" : 1454405608,
"timereceived" : 1454405608
}
]
}
}
--
-- Get Address book
--
Request:
{
"command" : "getaddresslist",
"accountid" : "andre@jochems.com",
"sessionid" : "123123-12312321-123123123",
"correlationid" : "65bb1cf4-3ca2-4d32-9a3c-9ae264424b0e",
"arguments" : {
"walletid" : "517beddb-8de2-4112-8aad-9e4d627916aa"
}
}
Response:
{
"sessionid" : "123123-12312321-123123123",
"correlationid" : "65bb1cf4-3ca2-4d32-9a3c-9ae264424b0e",
"result" : {
"errorCode" : 0,
"errorMessage" : ""
}
}
--
-- Send Coins
--
Request:
{
"command" : "sendtoaddress",
"accountid" : "andre@jochems.com",
"sessionid" : "123123-12312321-123123123",
"correlationid" : "65bb1cf4-3ca2-4d32-9a3c-9ae264424b0e",
"arguments" : {
"walletid" : "517beddb-8de2-4112-8aad-9e4d627916aa",
"address" : "AB3423SDSDFS",
"amount" : 234.67854,
"comment" : "Coins for a test transaction"
}
}
Response:
{
"sessionid" : "123123-12312321-123123123",
"correlationid" : "65bb1cf4-3ca2-4d32-9a3c-9ae264424b0e",
"result" : {
"errorCode" : 0,
"errorMessage" : ""
}
}

View File

@@ -51,8 +51,8 @@ std::string CUnsignedAlert::ToString() const
return strprintf(
"CAlert(\n"
" nVersion = %d\n"
" nRelayUntil = %" PRI64d "\n"
" nExpiration = %" PRI64d "\n"
" nRelayUntil = %"PRI64d"\n"
" nExpiration = %"PRI64d"\n"
" nID = %d\n"
" nCancel = %d\n"
" setCancel = %s\n"

View File

@@ -15,7 +15,7 @@
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0600
#define _WIN32_WINNT 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX

View File

@@ -182,10 +182,10 @@ Value stop(const Array& params, bool fHelp)
if (fHelp || params.size() > 1)
throw runtime_error(
"stop\n"
"Stop "+ COIN_NAME_DISPLAY + " server.");
"Stop CasinoCoin server.");
// Shutdown will take long enough that the response should get back
StartShutdown();
return ""+ COIN_NAME_DISPLAY + " server stopping";
return "CasinoCoin server stopping";
}
@@ -266,6 +266,15 @@ static const CRPCCommand vRPCCommands[] =
{ "listlockunspent", &listlockunspent, false, false, true },
{ "verifychain", &verifychain, true, false, false },
{ "getcoinsupply", &getcoinsupply, true, false, false },
{ "startwalletserversession", &startwalletserversession, true, false, false },
{ "listwalletserversessions", &listwalletserversessions, true, false, false },
{ "stopwalletserversession", &stopwalletserversession, true, false, false },
{ "listwallets", &listwallets, true, false, false },
{ "wsopenwallet", &wsopenwallet, true, false, false },
{ "wsclosewallet", &wsclosewallet, true, false, false },
{ "wsgetinfo", &wsgetinfo, true, false, false },
{ "wsgetaddresslist", &wsgetaddresslist, true, false, false },
{ "wssendtoaddress", &wssendtoaddress, true, false, false },
};
CRPCTable::CRPCTable()
@@ -299,7 +308,7 @@ string HTTPPost(const string& strMsg, const map<string,string>& mapRequestHeader
{
ostringstream s;
s << "POST / HTTP/1.1\r\n"
<< "User-Agent: "+ COIN_NAME + "-json-rpc/" << FormatFullVersion() << "\r\n"
<< "User-Agent: casinocoin-json-rpc/" << FormatFullVersion() << "\r\n"
<< "Host: 127.0.0.1\r\n"
<< "Content-Type: application/json\r\n"
<< "Content-Length: " << strMsg.size() << "\r\n"
@@ -330,7 +339,7 @@ static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
if (nStatus == HTTP_UNAUTHORIZED)
return strprintf("HTTP/1.0 401 Authorization Required\r\n"
"Date: %s\r\n"
"Server: "+ COIN_NAME + "-json-rpc/%s\r\n"
"Server: casinocoin-json-rpc/%s\r\n"
"WWW-Authenticate: Basic realm=\"jsonrpc\"\r\n"
"Content-Type: text/html\r\n"
"Content-Length: 296\r\n"
@@ -355,9 +364,9 @@ static string HTTPReply(int nStatus, const string& strMsg, bool keepalive)
"HTTP/1.1 %d %s\r\n"
"Date: %s\r\n"
"Connection: %s\r\n"
"Content-Length: %" PRIszu "\r\n"
"Content-Length: %"PRIszu"\r\n"
"Content-Type: application/json\r\n"
"Server: "+ COIN_NAME + "-json-rpc/%s\r\n"
"Server: casinocoin-json-rpc/%s\r\n"
"\r\n"
"%s",
nStatus,
@@ -737,7 +746,7 @@ void StartRPCThreads()
{
unsigned char rand_pwd[32];
RAND_bytes(rand_pwd, 32);
string strWhatAmI = "To use "+ COIN_NAME + "d";
string strWhatAmI = "To use casinocoind";
if (mapArgs.count("-server"))
strWhatAmI = strprintf(_("To use the %s option"), "\"-server\"");
else if (mapArgs.count("-daemon"))
@@ -746,13 +755,13 @@ void StartRPCThreads()
_("%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=")+ COIN_NAME + _("rpc\n"
"rpcuser=casinocoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"")+ COIN_NAME_DISPLAY + _(" Alert\" admin@foo.com\n"),
"for example: alertnotify=echo %%s | mail -s \"CasinoCoin Alert\" admin@foo.com\n"),
strWhatAmI.c_str(),
GetConfigFile().string().c_str(),
EncodeBase58(&rand_pwd[0],&rand_pwd[0]+32).c_str()),

View File

@@ -64,6 +64,9 @@ enum RPCErrorCode
RPC_WALLET_WRONG_ENC_STATE = -15, // Command given in wrong wallet encryption state (encrypting an encrypted wallet etc.)
RPC_WALLET_ENCRYPTION_FAILED = -16, // Failed to encrypt the wallet
RPC_WALLET_ALREADY_UNLOCKED = -17, // Wallet is already unlocked
// Wallet Server errors
RPC_WALLETSERVER_INVALID_ID = -100, // Given identifier is already in a session
};
json_spirit::Object JSONRPCError(int code, const std::string& message);
@@ -207,5 +210,15 @@ extern json_spirit::Value gettxout(const json_spirit::Array& params, bool fHelp)
extern json_spirit::Value verifychain(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value getcoinsupply(const json_spirit::Array& params, bool fHelp);
//WalletServer RPC Commands
extern json_spirit::Value startwalletserversession(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value listwalletserversessions(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value stopwalletserversession(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value listwallets(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value wsopenwallet(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value wsclosewallet(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value wsgetinfo(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value wsgetaddresslist(const json_spirit::Array& params, bool fHelp);
extern json_spirit::Value wssendtoaddress(const json_spirit::Array& params, bool fHelp);
#endif

View File

@@ -67,21 +67,13 @@ namespace Checkpoints
( 317777, uint256("0x0458c7effe8348b551f47c3d7115c9347f4121749549650d495b88e8d0a9c666"))
( 347777, uint256("0x9ba10b9cd9b94e903e67da6a1033841a3e66b6a33f09cbaec2146d4f72dbea2d"))
( 377777, uint256("0x6eecff79e07910c69ac5340ad34c74cd95ecdfb0282ac62b30e7ba443114a628"))
( 444429, uint256("0x01f8b85612927fd3660e7e036f559770ebb09d896f54abf70d99be2fe1793155"))
( 750000, uint256("0x4e5e0c5d7ee65cc0cf8cb995ef2c701773026baff189a922d9d51bba21cd8e8f"))
( 1000250, uint256("0x43ae9b7d1fcbe37eeb3dc3460b69a574d13e09cdec7d5da01c32d279a452842a"))
( 1105321, uint256("0xac44589a3914c6ad1e8e1d2d007fd76271abca6e38518e39b131ead11142f29d"))
( 1275800, uint256("0x8d74b3baf71c3f3f31e8d6f8c684d890f65764bded05d67f5d10c3b12ee59c75"))
( 1346290, uint256("0x0711f69754fe7f49b965d90db67f94025c3b89c114b60242513b1634220ce2c7"))
( 1461488, uint256("0xd23bc59328a745a8ed6803fcb7ea9f582dd09470ea24303ab0312ad8d29a5809"))
( 1525492, uint256("0xd315bf68cf03c43ebef827e6db8d5d86a43f261c6e1981a0a5ededa8243a73ce"))
// last solved checkpoint candidate while updating
( 444429, uint256("0x01f8b85612927fd3660e7e036f559770ebb09d896f54abf70d99be2fe1793155")) // last solved checkpoint candidate while updating
// (we need to know the debug.log tx= for the last checkpoint)
;
static const CCheckpointData data = {
&mapCheckpoints,
1465265319, // * UNIX timestamp of last checkpoint block
1923205, // * total number of transactions between genesis and last checkpoint
1400510546, // * UNIX timestamp of last checkpoint block
661156, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
4 // * estimated number of transactions per day after checkpoint
};

View File

@@ -6,9 +6,9 @@
//
// These need to be macros, as version.cpp's and bitcoin-qt.rc's voodoo requires it
#define CLIENT_VERSION_MAJOR 3
#define CLIENT_VERSION_MAJOR 2
#define CLIENT_VERSION_MINOR 0
#define CLIENT_VERSION_REVISION 0
#define CLIENT_VERSION_REVISION 1
#define CLIENT_VERSION_BUILD 0
// Set to true for release, false for prerelease or test build
@@ -16,7 +16,7 @@
// Copyright year (2009-this)
// Todo: update this when changing our copyright comments in the source
#define COPYRIGHT_YEAR 2016
#define COPYRIGHT_YEAR 2015
// Converts the parameter X to a string after macro replacement on X has been performed.
// Don't merge these into one macro!

View File

@@ -6,12 +6,13 @@
#define _BITCOIN_COMPAT_H 1
#ifdef WIN32
#define _WIN32_WINNT 0x0600
#define _WIN32_WINNT 0x0501
#define WIN32_LEAN_AND_MEAN 1
#ifndef NOMINMAX
#define NOMINMAX
#endif
#define FD_SETSIZE 1024 // max number of fds in fd_set
#include <winsock2.h>
#include <mswsock.h>
#include <ws2tcpip.h>
#else
@@ -25,12 +26,12 @@
#include <ifaddrs.h>
#endif
typedef u_int SOCKET;
#ifdef WIN32
#define MSG_NOSIGNAL 0
#define MSG_DONTWAIT 0
typedef int socklen_t;
#else
typedef u_int SOCKET;
#include "errno.h"
#define WSAGetLastError() errno
#define WSAEINVAL EINVAL

View File

@@ -456,7 +456,7 @@ void CDBEnv::Flush(bool fShutdown)
else
mi++;
}
printf("DBFlush(%s)%s ended %15" PRI64d "ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
printf("DBFlush(%s)%s ended %15"PRI64d"ms\n", fShutdown ? "true" : "false", fDbEnvInit ? "" : " db not started", GetTimeMillis() - nStart);
if (fShutdown)
{
char** listp;

View File

@@ -8,9 +8,9 @@
#include "bitcoinrpc.h"
#include "net.h"
#include "init.h"
#include "util.h"
#include "ui_interface.h"
#include "version.h"
#include "walletserver.h"
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
@@ -27,7 +27,9 @@ using namespace std;
using namespace boost;
CWallet* pwalletMain;
WalletServer walletServer;
CClientUIInterface uiInterface;
boost::thread walletServerThread;
#ifdef WIN32
// Win32 LevelDB doesn't use filedescriptors, and the ones used for
@@ -79,7 +81,10 @@ volatile bool fRequestShutdown = false;
void StartShutdown()
{
boost::this_thread::sleep_for( boost::chrono::seconds( 1 ) );
// Stop WalletServer if running
StopWalletServerThread();
// initiate shutdown
boost::this_thread::sleep_for( boost::chrono::seconds( 1 ) );
fRequestShutdown = true;
}
bool ShutdownRequested()
@@ -181,12 +186,12 @@ bool AppInit(int argc, char* argv[])
if (mapArgs.count("-?") || mapArgs.count("--help"))
{
// First part of help message is specific to bitcoind / RPC client
std::string strUsage = COIN_NAME_DISPLAY + " version" + " " + FormatFullVersion() + "\n\n" +
std::string strUsage = _("CasinoCoin version") + " " + FormatFullVersion() + "\n\n" +
_("Usage:") + "\n" +
" "+ COIN_NAME + "d [options] " + "\n" +
" "+ COIN_NAME + "d [options] <command> [params] " + "Send command to -server or "+ COIN_NAME + "d" + "\n" +
" "+ COIN_NAME + "d [options] help " + "List commands" + "\n" +
" "+ COIN_NAME + "d [options] help <command> " + "Get help for a command" + "\n";
" casinocoind [options] " + "\n" +
" casinocoind [options] <command> [params] " + _("Send command to -server or casinocoind") + "\n" +
" casinocoind [options] help " + _("List commands") + "\n" +
" casinocoind [options] help <command> " + _("Get help for a command") + "\n";
strUsage += "\n" + HelpMessage();
@@ -196,7 +201,7 @@ bool AppInit(int argc, char* argv[])
// Command-line RPC
for (int i = 1; i < argc; i++)
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], (std::string("") + COIN_NAME + ":").c_str()))
if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "casinocoin:"))
fCommandLine = true;
if (fCommandLine)
@@ -227,7 +232,9 @@ bool AppInit(int argc, char* argv[])
fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno);
}
#endif
// WalletServer parameter
fWalletServer = GetBoolArg("-walletserver");
// create the thread to detect a shutdown
detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup));
fRet = AppInit2(threadGroup);
}
@@ -257,7 +264,6 @@ extern void noui_connect();
int main(int argc, char* argv[])
{
bool fRet = false;
// Connect bitcoind signal handlers
noui_connect();
@@ -299,8 +305,8 @@ std::string HelpMessage()
{
string strUsage = _("Options:") + "\n" +
" -? " + _("This help message") + "\n" +
" -conf=<file> " + "Specify configuration file (default: "+ COIN_NAME + ".conf)" + "\n" +
" -pid=<file> " + "Specify pid file (default: "+ COIN_NAME + "d.pid)" + "\n" +
" -conf=<file> " + _("Specify configuration file (default: casinocoin.conf)") + "\n" +
" -pid=<file> " + _("Specify pid file (default: casinocoind.pid)") + "\n" +
" -gen " + _("Generate coins (default: 0)") + "\n" +
" -datadir=<dir> " + _("Specify data directory") + "\n" +
" -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" +
@@ -377,7 +383,7 @@ std::string HelpMessage()
" -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" +
" -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" +
"\n" + "SSL options: (see the "+ COIN_NAME_DISPLAY + " Wiki for SSL setup instructions)" + "\n" +
"\n" + _("SSL options: (see the CasinoCoin Wiki for SSL setup instructions)") + "\n" +
" -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" +
" -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" +
" -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" +
@@ -646,13 +652,12 @@ bool AppInit2(boost::thread_group& threadGroup)
if (file) fclose(file);
static boost::interprocess::file_lock lock(pathLockFile.string().c_str());
if (!lock.try_lock())
return InitError(strprintf((std::string("Cannot obtain a lock on data directory %s. ")+ COIN_NAME_DISPLAY + " is probably already running.").c_str(), strDataDir.c_str()));
return InitError(strprintf(_("Cannot obtain a lock on data directory %s. CasinoCoin is probably already running."), strDataDir.c_str()));
if (GetBoolArg("-shrinkdebugfile", !fDebug))
ShrinkDebugFile();
printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
std::string versionString = COIN_NAME_DISPLAY + " version %s (%s)\n";
printf(versionString.c_str(), FormatFullVersion().c_str(), CLIENT_DATE.c_str());
printf("CasinoCoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str());
printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION));
if (!fLogTimestamps)
printf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str());
@@ -662,9 +667,8 @@ bool AppInit2(boost::thread_group& threadGroup)
std::ostringstream strErrors;
if (fDaemon)
{
fprintf(stdout, "%s server starting\n", COIN_NAME_DISPLAY.c_str());
}
fprintf(stdout, "CasinoCoin server starting\n");
if (nScriptCheckThreads) {
printf("Using %u threads for script verification\n", nScriptCheckThreads);
for (int i=0; i<nScriptCheckThreads-1; i++)
@@ -686,7 +690,7 @@ bool AppInit2(boost::thread_group& threadGroup)
{
// try moving the database env out of the way
boost::filesystem::path pathDatabase = GetDataDir() / "database";
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%" PRI64d ".bak", GetTime());
boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRI64d".bak", GetTime());
try {
boost::filesystem::rename(pathDatabase, pathDatabaseBak);
printf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str());
@@ -950,7 +954,7 @@ bool AppInit2(boost::thread_group& threadGroup)
printf("Shutdown requested. Exiting.\n");
return false;
}
printf(" block index %15" PRI64d "ms\n", GetTimeMillis() - nStart);
printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart);
if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree"))
{
@@ -1004,10 +1008,10 @@ bool AppInit2(boost::thread_group& threadGroup)
InitWarning(msg);
}
else if (nLoadWalletRet == DB_TOO_NEW)
strErrors << "Error loading wallet.dat: Wallet requires newer version of " << COIN_NAME_DISPLAY << "\n";
strErrors << _("Error loading wallet.dat: Wallet requires newer version of CasinoCoin") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strErrors << "Wallet needed to be rewritten: restart "<< COIN_NAME_DISPLAY << " to complete" << "\n";
strErrors << _("Wallet needed to be rewritten: restart CasinoCoin to complete") << "\n";
printf("%s", strErrors.str().c_str());
return InitError(strErrors.str());
}
@@ -1047,7 +1051,7 @@ bool AppInit2(boost::thread_group& threadGroup)
}
printf("%s", strErrors.str().c_str());
printf(" wallet %15" PRI64d "ms\n", GetTimeMillis() - nStart);
printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
@@ -1069,7 +1073,7 @@ bool AppInit2(boost::thread_group& threadGroup)
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15" PRI64d "ms\n", GetTimeMillis() - nStart);
printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
nWalletDBUpdated++;
}
@@ -1102,7 +1106,7 @@ bool AppInit2(boost::thread_group& threadGroup)
printf("Invalid or missing peers.dat; recreating\n");
}
printf("Loaded %i addresses from peers.dat %" PRI64d "ms\n",
printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
// ********************************************************* Step 11: start node
@@ -1116,11 +1120,11 @@ bool AppInit2(boost::thread_group& threadGroup)
RandAddSeedPerfmon();
//// debug print
printf("mapBlockIndex.size() = %" PRIszu "\n", mapBlockIndex.size());
printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size());
printf("nBestHeight = %d\n", nBestHeight);
printf("setKeyPool.size() = %" PRIszu "\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
printf("mapWallet.size() = %" PRIszu "\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
printf("mapAddressBook.size() = %" PRIszu "\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->setKeyPool.size() : 0);
printf("mapWallet.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapWallet.size() : 0);
printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain ? pwalletMain->mapAddressBook.size() : 0);
StartNode(threadGroup);
@@ -1133,6 +1137,14 @@ bool AppInit2(boost::thread_group& threadGroup)
if (pwalletMain)
GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain);
// Start The WalletServer if defined
fWalletServer = GetBoolArg("-walletserver", false);
if (fWalletServer)
{
// Run a thread for the WalletServer
threadGroup.create_thread(boost::bind(&StartWalletServerThread));
}
// ********************************************************* Step 12: finished
uiInterface.InitMessage(_("Done loading"));

View File

@@ -6,3 +6,7 @@
// json spirit version 2.00
#include "json_spirit_value.h"
namespace json_spirit {
const char* Value_type_name[]={"obj", "array", "str", "bool", "int", "real", "null"};
}

View File

@@ -24,7 +24,7 @@
namespace json_spirit
{
enum Value_type{ obj_type, array_type, str_type, bool_type, int_type, real_type, null_type };
static const char* Value_type_name[]={"obj", "array", "str", "bool", "int", "real", "null"};
extern const char* Value_type_name[];
template< class Config > // Config determines whether the value uses std::string or std::wstring and
// whether JSON Objects are represented as vectors or maps

View File

@@ -18,7 +18,7 @@ $(shell CC="$(CC)" CXX="$(CXX)" TARGET_OS="$(TARGET_OS)" \
include build_config.mk
CFLAGS += -I. -I./include $(PLATFORM_CCFLAGS) $(OPT)
CXXFLAGS += -I. -I./include $(PLATFORM_CXXFLAGS) $(OPT) -std=c++14
CXXFLAGS += -I. -I./include $(PLATFORM_CXXFLAGS) $(OPT)
LDFLAGS += $(PLATFORM_LDFLAGS)
LIBS += $(PLATFORM_LIBS)

View File

@@ -139,7 +139,7 @@ case "$TARGET_OS" in
;;
OS_WINDOWS_CROSSCOMPILE | NATIVE_WINDOWS)
PLATFORM=OS_WINDOWS
COMMON_FLAGS="-fno-builtin-memcmp -D_REENTRANT -DOS_WINDOWS -DLEVELDB_PLATFORM_WINDOWS -DWINVER=0x0600 -D__USE_MINGW_ANSI_STDIO=1"
COMMON_FLAGS="-fno-builtin-memcmp -D_REENTRANT -DOS_WINDOWS -DLEVELDB_PLATFORM_WINDOWS -DWINVER=0x0500 -D__USE_MINGW_ANSI_STDIO=1"
PLATFORM_SOURCES="util/env_win.cc"
PLATFORM_LIBS="-lshlwapi"
PORT_FILE=port/port_win.cc

View File

@@ -66,7 +66,7 @@ map<uint256, set<uint256> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = COIN_NAME_DISPLAY + " Signed Message:\n";
const string strMessageMagic = "CasinoCoin Signed Message:\n";
double dHashesPerSec = 0.0;
int64 nHPSTimerStart = 0;
@@ -309,7 +309,7 @@ bool AddOrphanTx(const CTransaction& tx)
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(hash);
printf("stored orphan tx %s (mapsz %" PRIszu ")\n", hash.ToString().c_str(),
printf("stored orphan tx %s (mapsz %"PRIszu")\n", hash.ToString().c_str(),
mapOrphanTransactions.size());
return true;
}
@@ -755,7 +755,7 @@ bool CTxMemPool::accept(CValidationState &state, CTransaction &tx, bool fCheckIn
// Don't accept it if it can't get into a block
int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY);
if (fLimitFree && nFees < txMinFee)
return error("CTxMemPool::accept() : not enough fees %s, %" PRI64d " < %" PRI64d,
return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
hash.ToString().c_str(),
nFees, txMinFee);
@@ -1109,24 +1109,18 @@ int64 static GetBlockValue(int nHeight, int64 nFees)
}
// Permantently reduce the number of mined coins to 10 after block 575000
// Permantently reduce the number of minded coins to 1 after block 1575000
// coin supply at that height = 38577206
// Blocks until max coin supply -> 63000000 - 38577206 = 24422794
// New height for reduction to 0 coins -> 1575000 + 24422794 = 25997794
if(nHeight > 575000){
if(nHeight < 1575000)
{
nSubsidy = 10 * COIN;
}
else if(nHeight >= 1575000 && nHeight <= 25997794){
nSubsidy = 1 * COIN;
if(nHeight < 3756000){
nSubsidy = 10 * COIN;
}
else
{
nSubsidy = 0 * COIN;
}
}
// return subsidy + fees
return nSubsidy + nFees;
}
@@ -1139,12 +1133,12 @@ int64 GetTotalCoinSupply(int nHeight, bool noCheckpoints)
int heights[] = {
100000, 200000, 300000, 400000, 500000,
600000, 700000, 800000, 900000, 1000000,
1100000, 1200000, 1300000, 1400000, 1500000
1100000
};
int64 supplies[] = {
482721500000000, 982721500000000, 1482721500000000, 1982721500000000, 2482721500000000,
2882721500000000, 2982721500000000, 3082721500000000, 3182721500000000, 3282721500000000,
3382721500000000, 3482721500000000, 3582721500000000, 3682721500000000, 3782721500000000
3382721500000000
};
if (nHeight>=1 ) {
int numHeights = (int)(sizeof(heights)/sizeof(heights[0]));
@@ -1245,7 +1239,7 @@ unsigned int static GetNextWorkRequired_V1(const CBlockIndex* pindexLast, const
// Limit adjustment step
int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
printf(" nActualTimespan = %" PRI64d " before bounds\n", nActualTimespan);
printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
if (nActualTimespan < nTargetTimespan/4)
nActualTimespan = nTargetTimespan/4;
if (nActualTimespan > nTargetTimespan*4)
@@ -1262,7 +1256,7 @@ unsigned int static GetNextWorkRequired_V1(const CBlockIndex* pindexLast, const
/// debug print
printf("Difficulty Retarget - GetNextWorkRequired_V1 RETARGET\n");
printf("nTargetTimespan = %" PRI64d " nActualTimespan = %" PRI64d "\n", nTargetTimespan, nActualTimespan);
printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
@@ -1396,7 +1390,7 @@ unsigned int static DigiShield(const CBlockIndex* pindexLast, const CBlockHeader
// Limit adjustment step
int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
printf(" nActualTimespan = %" PRI64d " before bounds\n", nActualTimespan);
printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
@@ -1412,7 +1406,7 @@ unsigned int static DigiShield(const CBlockIndex* pindexLast, const CBlockHeader
/// debug print
printf("DigiShield RETARGET \n");
printf("retargetTimespan = %" PRI64d " nActualTimespan = %" PRI64d "\n", retargetTimespan, nActualTimespan);
printf("retargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", retargetTimespan, nActualTimespan);
printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
@@ -1970,7 +1964,7 @@ bool CBlock::ConnectBlock(CValidationState &state, CBlockIndex* pindex, CCoinsVi
printf("- Connect %u transactions: %.2fms (%.3fms/tx, %.3fms/txin)\n", (unsigned)vtx.size(), 0.001 * nTime, 0.001 * nTime / vtx.size(), nInputs <= 1 ? 0 : 0.001 * nTime / (nInputs-1));
if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
return state.DoS(100, error("ConnectBlock() : coinbase pays too much (actual=%" PRI64d " vs limit=%" PRI64d ")", vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees)));
return state.DoS(100, error("ConnectBlock() : coinbase pays too much (actual=%"PRI64d" vs limit=%"PRI64d")", vtx[0].GetValueOut(), GetBlockValue(pindex->nHeight, nFees)));
if (!control.Wait())
return state.DoS(100, false);
@@ -2050,8 +2044,8 @@ bool SetBestChain(CValidationState &state, CBlockIndex* pindexNew)
reverse(vConnect.begin(), vConnect.end());
if (vDisconnect.size() > 0) {
printf("REORGANIZE: Disconnect %" PRIszu " blocks; %s..\n", vDisconnect.size(), pfork->GetBlockHash().ToString().c_str());
printf("REORGANIZE: Connect %" PRIszu " blocks; ..%s\n", vConnect.size(), pindexNew->GetBlockHash().ToString().c_str());
printf("REORGANIZE: Disconnect %"PRIszu" blocks; %s..\n", vDisconnect.size(), pfork->GetBlockHash().ToString().c_str());
printf("REORGANIZE: Connect %"PRIszu" blocks; ..%s\n", vConnect.size(), pindexNew->GetBlockHash().ToString().c_str());
}
// Disconnect shorter branch
@@ -3159,7 +3153,7 @@ void PrintBlockTree()
// print item
CBlock block;
block.ReadFromDisk(pindex);
printf("%d (blk%05u.dat:0x%x) %s tx %" PRIszu "",
printf("%d (blk%05u.dat:0x%x) %s tx %"PRIszu"",
pindex->nHeight,
pindex->GetBlockPos().nFile, pindex->GetBlockPos().nPos,
DateTimeStrFormat("%Y-%m-%d %H:%M:%S", block.GetBlockTime()).c_str(),
@@ -3252,7 +3246,7 @@ bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos *dbp)
AbortNode(_("Error: system error: ") + e.what());
}
if (nLoaded > 0)
printf("Loaded %i blocks from external file in %" PRI64d "ms\n", nLoaded, GetTimeMillis() - nStart);
printf("Loaded %i blocks from external file in %"PRI64d"ms\n", nLoaded, GetTimeMillis() - nStart);
return nLoaded > 0;
}
@@ -3500,37 +3494,21 @@ void static ProcessGetData(CNode* pfrom)
}
}
bool static CheckValidClientVersion(int clientVersion)
{
// From block 1575000 onwards version must be 80001 (MIN_PEER_PROTO_VERSION)
// Before that version was 70004
if(pindexBest->nHeight >= 1575000)
{
if(clientVersion < MIN_PEER_PROTO_VERSION)
return false;
else
return true;
}
else
{
if(clientVersion < 70004)
return false;
else
return true;
}
}
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
RandAddSeedPerfmon();
if (fDebug)
printf("received: %s (%" PRIszu " bytes)\n", strCommand.c_str(), vRecv.size());
printf("received: %s (%"PRIszu" bytes)\n", strCommand.c_str(), vRecv.size());
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
printf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (strCommand == "version")
{
// Each connection can only send one version message
@@ -3545,8 +3523,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
CAddress addrFrom;
uint64 nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
// Check version related to blockheight
if(!CheckValidClientVersion(pfrom->nVersion))
if (pfrom->nVersion < MIN_PEER_PROTO_VERSION)
{
// disconnect from peers older than this proto version
printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
@@ -3660,7 +3637,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
if (vAddr.size() > 1000)
{
pfrom->Misbehaving(20);
return error("message addr size() = %" PRIszu "", vAddr.size());
return error("message addr size() = %"PRIszu"", vAddr.size());
}
// Store the new addresses
@@ -3723,7 +3700,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message inv size() = %" PRIszu "", vInv.size());
return error("message inv size() = %"PRIszu"", vInv.size());
}
// find last block in inv vector
@@ -3772,11 +3749,11 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
if (vInv.size() > MAX_INV_SZ)
{
pfrom->Misbehaving(20);
return error("message getdata size() = %" PRIszu "", vInv.size());
return error("message getdata size() = %"PRIszu"", vInv.size());
}
if (fDebugNet || (vInv.size() != 1))
printf("received getdata (%" PRIszu " invsz)\n", vInv.size());
printf("received getdata (%"PRIszu" invsz)\n", vInv.size());
if ((fDebugNet && vInv.size() > 0) || (vInv.size() == 1))
printf("received getdata for: %s\n", vInv[0].ToString().c_str());
@@ -3877,7 +3854,7 @@ bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
printf("AcceptToMemoryPool: %s %s : accepted %s (poolsz %" PRIszu ")\n",
printf("AcceptToMemoryPool: %s %s : accepted %s (poolsz %"PRIszu")\n",
pfrom->addr.ToString().c_str(), pfrom->cleanSubVer.c_str(),
tx.GetHash().ToString().c_str(),
mempool.mapTx.size());
@@ -4515,7 +4492,7 @@ public:
CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
{
// Create new block
std::unique_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
auto_ptr<CBlockTemplate> pblocktemplate(new CBlockTemplate());
if(!pblocktemplate.get())
return NULL;
CBlock *pblock = &pblocktemplate->block; // pointer for convenience
@@ -4726,7 +4703,7 @@ CBlockTemplate* CreateNewBlock(const CScript& scriptPubKeyIn)
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
printf("CreateNewBlock(): total size %" PRI64u "\n", nBlockSize);
printf("CreateNewBlock(): total size %"PRI64u"\n", nBlockSize);
pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
pblocktemplate->vTxFees[0] = -nFees;
@@ -4883,13 +4860,13 @@ void static CasinoCoinMiner(CWallet *pwallet)
unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrev = pindexBest;
std::unique_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
auto_ptr<CBlockTemplate> pblocktemplate(CreateNewBlockWithKey(reservekey));
if (!pblocktemplate.get())
return;
CBlock *pblock = &pblocktemplate->block;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
printf("Running CasinoCoinMiner with %" PRIszu " transactions in block (%u bytes)\n", pblock->vtx.size(),
printf("Running CasinoCoinMiner with %"PRIszu" transactions in block (%u bytes)\n", pblock->vtx.size(),
::GetSerializeSize(*pblock, SER_NETWORK, PROTOCOL_VERSION));
//

View File

@@ -448,7 +448,7 @@ public:
{
if (scriptPubKey.size() < 6)
return "CTxOut(error)";
return strprintf("CTxOut(nValue=%" PRI64d ".%08" PRI64d ", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
return strprintf("CTxOut(nValue=%"PRI64d".%08"PRI64d", scriptPubKey=%s)", nValue / COIN, nValue % COIN, scriptPubKey.ToString().substr(0,30).c_str());
}
void print() const
@@ -644,7 +644,7 @@ void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCach
std::string ToString() const
{
std::string str;
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%" PRIszu ", vout.size=%" PRIszu ", nLockTime=%u)\n",
str += strprintf("CTransaction(hash=%s, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%u)\n",
GetHash().ToString().c_str(),
nVersion,
vin.size(),
@@ -1488,7 +1488,7 @@ public:
void print() const
{
printf("CBlock(hash=%s, input=%s, PoW=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%" PRIszu ")\n",
printf("CBlock(hash=%s, input=%s, PoW=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu")\n",
GetHash().ToString().c_str(),
HexStr(BEGIN(nVersion),BEGIN(nVersion)+80,false).c_str(),
GetPoWHash().ToString().c_str(),

View File

@@ -25,6 +25,8 @@ BOOST_SUFFIX?=-mgw49-mt-s-1_55
INCLUDEPATHS= \
-I"$(CURDIR)" \
-I"$(CURDIR)\stomp" \
-I"$(CURDIR)\json" \
-I"C:\deps\boost_1_55_0" \
-I"C:\deps\db-4.8.30.NC\build_unix" \
-I"C:\deps\openssl-1.0.2d\include" \
@@ -45,6 +47,7 @@ LIBS= \
-l boost_program_options$(BOOST_SUFFIX) \
-l boost_thread$(BOOST_SUFFIX) \
-l boost_chrono$(BOOST_SUFFIX) \
-l boost_serialization$(BOOST_SUFFIX) \
-l db_cxx \
-l ssl \
-l crypto
@@ -106,7 +109,15 @@ OBJS= \
obj/bloom.o \
obj/noui.o \
obj/leveldb.o \
obj/txdb.o
obj/txdb.o \
obj/json/json_spirit_value.o \
obj/json/json_spirit_reader.o \
obj/json/json_spirit_writer.o \
obj/stomp/helpers.o \
obj/stomp/booststomp.o \
obj/stomp/stompframe.o \
obj/walletserver.o \
obj/walletserversession.o
ifdef USE_SSE2
DEFS += -DUSE_SSE2
@@ -147,7 +158,8 @@ test_casinocoin.exe: $(TESTOBJS) $(filter-out obj/init.o,$(OBJS:obj/%=obj/%))
clean:
rm -f casinocoind.exe test_casinocoin.exe
rm -f obj/*
rm -f obj/stomp/*
rm -f obj/*.o
rm -f obj-test/*
cd leveldb && $(MAKE) TARGET_OS=NATIVE_WINDOWS clean && cd ..

View File

@@ -16,16 +16,16 @@ USE_IPV6:=1
USE_QRCODE=1
# define libraries
BOOST_LIB_PATH=$HOME/deps/boost_1_60_0/stage/lib
BDB_LIB_PATH=$HOME/deps/db-5.1.29.NC/build_unix
OPENSSL_LIB_PATH=$HOME/deps/openssl-1.0.2g
MINIUPNPC_LIB_PATH=$HOME/deps/miniupnpc-1.9
BOOST_LIB_PATH=/home/ubuntu/deps/linux/boost_1_55_0/stage/lib
BDB_LIB_PATH=/home/ubuntu/deps/linux/db-4.8.30.NC/build_unix
OPENSSL_LIB_PATH=/home/ubuntu/deps/linux/openssl-1.0.1h
MINIUPNPC_LIB_PATH=/home/ubuntu/deps/linux/miniupnpc
# define includes
BOOST_INCLUDE_PATH=$HOME/deps/boost_1_60_0
BDB_INCLUDE_PATH=$HOME/deps/db-5.1.29.NC/build_unix
OPENSSL_INCLUDE_PATH=$HOME/deps/openssl-1.0.2g
MINIUPNPC_INCLUDE_PATH=$HOME/deps/miniupnpc-1.9
BOOST_INCLUDE_PATH=/home/ubuntu/deps/linux/boost_1_55_0
BDB_INCLUDE_PATH=/home/ubuntu/deps/linux/db-4.8.30.NC/build_unix
OPENSSL_INCLUDE_PATH=/home/ubuntu/deps/linux/openssl-1.0.1h
MINIUPNPC_INCLUDE_PATH=/home/ubuntu/deps/linux
LINK:=$(CXX)
@@ -54,6 +54,7 @@ LIBS += \
-l boost_filesystem$(BOOST_LIB_SUFFIX) \
-l boost_program_options$(BOOST_LIB_SUFFIX) \
-l boost_thread$(BOOST_LIB_SUFFIX) \
-l boost_serialization$(BOOST_LIB_SUFFIX) \
-l db_cxx$(BDB_LIB_SUFFIX) \
-l ssl \
-l crypto
@@ -119,13 +120,16 @@ DEBUGFLAGS=-g
# CXXFLAGS can be specified on the make command line, so we use xCXXFLAGS that only
# adds some defaults in front. Unfortunately, CXXFLAGS=... $(CXXFLAGS) does not work.
xCXXFLAGS=-O2 -std=c++14 -pthread -Wall -Wextra -Wformat -Wformat-security -Wno-unused-parameter \
xCXXFLAGS=-O2 -pthread -Wall -Wextra -Wformat -Wformat-security -Wno-unused-parameter \
$(DEBUGFLAGS) $(DEFS) $(HARDENING) $(CXXFLAGS)
# LDFLAGS can be specified on the make command line, so we use xLDFLAGS that only
# adds some defaults in front. Unfortunately, LDFLAGS=... $(LDFLAGS) does not work.
xLDFLAGS=$(LDHARDENING) $(LDFLAGS)
HEADERS = $(wildcard *.h) \
stomp/$(wildcar *.h)
OBJS= \
leveldb/libleveldb.a \
obj/alert.o \
@@ -158,7 +162,11 @@ OBJS= \
obj/bloom.o \
obj/noui.o \
obj/leveldb.o \
obj/txdb.o
obj/txdb.o \
obj/stomp/helpers.o \
obj/stomp/booststomp.o \
obj/stomp/stompframe.o \
obj/walletserver.o
ifdef USE_SSE2
@@ -199,6 +207,7 @@ obj/%-sse2.o: %-sse2.cpp
rm -f $(@:%.o=%.d)
obj/%.o: %.cpp
mkdir -p obj/stomp
$(CXX) -c $(xCXXFLAGS) -MMD -MF $(@:%.o=%.d) -o $@ $<
@cp $(@:%.o=%.d) $(@:%.o=%.P); \
sed -e 's/#.*//' -e 's/^[^:]*: *//' -e 's/ *\\$$//' \

View File

@@ -1262,7 +1262,7 @@ void DumpAddresses()
CAddrDB adb;
adb.Write(addrman);
printf("Flushed %d addresses to peers.dat %" PRI64d "ms\n",
printf("Flushed %d addresses to peers.dat %"PRI64d"ms\n",
addrman.size(), GetTimeMillis() - nStart);
}

View File

@@ -366,7 +366,7 @@ public:
else
nRequestTime = 0;
if (fDebugNet)
printf("askfor %s %" PRI64d " (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
printf("askfor %s %"PRI64d" (%s)\n", inv.ToString().c_str(), nRequestTime, DateTimeStrFormat("%H:%M:%S", nRequestTime/1000000).c_str());
// Make sure not to reuse time indexes to keep things in the same order
int64 nNow = (GetTime() - 1) * 1000000;

View File

@@ -3,7 +3,6 @@
#include "guiconstants.h"
#include "walletmodel.h"
#include "version.h"
#include <QMessageBox>
#include <QPushButton>
@@ -99,8 +98,7 @@ void AskPassphraseDialog::accept()
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr((std::string("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR ")
+ COIN_NAME_DISPLAY + "</b>!").c_str()) + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR CASINOCOINS</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
@@ -111,9 +109,9 @@ void AskPassphraseDialog::accept()
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr((std::string("")+ COIN_NAME_DISPLAY + " will close now to finish the encryption process. "
tr("CasinoCoin will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your "+ COIN_NAME + " from being stolen by malware infecting your computer.").c_str()) +
"your casinocoins from being stolen by malware infecting your computer.") +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "

View File

@@ -15,6 +15,7 @@
#include "ui_interface.h"
#include "paymentserver.h"
#include "splashscreen.h"
#include "walletserver.h"
#include <QMessageBox>
#if QT_VERSION < 0x050000
@@ -110,7 +111,7 @@ static std::string Translate(const char* psz)
static void handleRunawayException(std::exception *e)
{
PrintExceptionContinue(e, "Runaway exception");
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr(("A fatal error occurred. "+ COIN_NAME_DISPLAY + " can no longer continue safely and will quit.").c_str()) + QString("\n\n") + QString::fromStdString(strMiscWarning));
QMessageBox::critical(0, "Runaway exception", BitcoinGUI::tr("A fatal error occurred. CasinoCoin can no longer continue safely and will quit.") + QString("\n\n") + QString::fromStdString(strMiscWarning));
exit(1);
}
@@ -146,7 +147,7 @@ int main(int argc, char *argv[])
{
// This message can not be translated, as translation is not initialized yet
// (which not yet possible because lang=XX can be overridden in bitcoin.conf in the data directory)
QMessageBox::critical(0, COIN_NAME_DISPLAY.c_str(),
QMessageBox::critical(0, "CasinoCoin",
QString("Error: Specified data directory \"%1\" does not exist.").arg(QString::fromStdString(mapArgs["-datadir"])));
return 1;
}
@@ -154,12 +155,12 @@ int main(int argc, char *argv[])
// Application identification (must be set before OptionsModel is initialized,
// as it is used to locate QSettings)
QApplication::setOrganizationName(COIN_NAME_DISPLAY.c_str());
QApplication::setOrganizationName("CasinoCoin");
QApplication::setOrganizationDomain("casinocoin.org");
if(GetBoolArg("-testnet")) // Separate UI settings for testnet
QApplication::setApplicationName((""+ COIN_NAME_DISPLAY + "-Qt-testnet").c_str());
QApplication::setApplicationName("CasinoCoin-Qt-testnet");
else
QApplication::setApplicationName((""+ COIN_NAME_DISPLAY + "-Qt").c_str());
QApplication::setApplicationName("CasinoCoin-Qt");
// ... then GUI settings:
OptionsModel optionsModel;
@@ -296,6 +297,7 @@ int main(int argc, char *argv[])
}
else
{
// Shutdown the core and its threads
threadGroup.interrupt_all();
threadGroup.join_all();
Shutdown();

View File

@@ -135,11 +135,5 @@
<file>qtquick_controls/qml/QmlGUIExchangesWindow.qml</file>
<file>qtquick_controls/qml/QmlGUIExchangesListView.qml</file>
<file>qtquick_controls/qml/QmlGUIExchangesControl.qml</file>
<file>twitter/FlipBar.qml</file>
<file>twitter/TweetDelegate.qml</file>
<file>twitter/tweetsearch.js</file>
<file>twitter/TweetsModel.qml</file>
<file>twitter/CasinocoinTwitterFeed.qml</file>
<file>twitter/resources/anonymous.png</file>
</qresource>
</RCC>

View File

@@ -1,5 +1,4 @@
#include <QtGlobal>
#include "version.h"
// Automatically generated by extract_strings.py
#ifdef __GNUC__
#define UNUSED __attribute__((unused))
@@ -7,19 +6,18 @@
#define UNUSED
#endif
static const char UNUSED *bitcoin_strings[] = {
QT_TRANSLATE_NOOP("bitcoin-core", (std::string("") +
"%s, you must set a rpcpassword in the configuration file:\n" +
"%s\n" +
"It is recommended you use the following random password:\n" +
"rpcuser=" + COIN_NAME +"rpc\n" +
"rpcpassword=%s\n" +
"(you do not need to remember this password)\n" +
"The username and password MUST NOT be the same.\n" +
"If the file does not exist, create it with owner-readable-only file " +
"permissions.\n" +
"It is also recommended to set alertnotify so you are notified of problems;\n" +
"for example: alertnotify=echo %%s | mail -s \"" + COIN_NAME_DISPLAY +
" Alert\" admin@foo.com\n").c_str()),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"%s, you must set a rpcpassword in the configuration file:\n"
"%s\n"
"It is recommended you use the following random password:\n"
"rpcuser=casinocoinrpc\n"
"rpcpassword=%s\n"
"(you do not need to remember this password)\n"
"The username and password MUST NOT be the same.\n"
"If the file does not exist, create it with owner-readable-only file "
"permissions.\n"
"It is also recommended to set alertnotify so you are notified of problems;\n"
"for example: alertnotify=echo %%s | mail -s \"CasinoCoin Alert\" admin@foo.com\n"),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:"
"@STRENGTH)"),
@@ -31,9 +29,9 @@ QT_TRANSLATE_NOOP("bitcoin-core", ""
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Bind to given address and always listen on it. Use [host]:port notation for "
"IPv6"),
QT_TRANSLATE_NOOP("bitcoin-core", (std::string("") +
"Cannot obtain a lock on data directory %s. "+ COIN_NAME_DISPLAY + " is probably already "
"running.").c_str()),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Cannot obtain a lock on data directory %s. CasinoCoin is probably already "
"running."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"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 "
@@ -64,17 +62,17 @@ QT_TRANSLATE_NOOP("bitcoin-core", ""
QT_TRANSLATE_NOOP("bitcoin-core", ""
"This is a pre-release test build - use at your own risk - do not use for "
"mining or merchant applications"),
QT_TRANSLATE_NOOP("bitcoin-core", (std::string("") +
"Unable to bind to %s on this computer. "+ COIN_NAME_DISPLAY + " is probably already running.").c_str()),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Unable to bind to %s on this computer. CasinoCoin is probably already running."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: -paytxfee is set very high! This is the transaction fee you will "
"pay if you send a transaction."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: Displayed transactions may not be correct! You may need to upgrade, "
"or other nodes may need to upgrade."),
QT_TRANSLATE_NOOP("bitcoin-core", (std::string("") +
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: Please check that your computer's date and time are correct! If "
"your clock is wrong "+ COIN_NAME_DISPLAY + " will not work properly.").c_str()),
"your clock is wrong CasinoCoin will not work properly."),
QT_TRANSLATE_NOOP("bitcoin-core", ""
"Warning: error reading wallet.dat! All keys read correctly, but transaction "
"data or address book entries might be missing or incorrect."),
@@ -93,7 +91,7 @@ QT_TRANSLATE_NOOP("bitcoin-core", "Add a node to connect to and attempt to keep
QT_TRANSLATE_NOOP("bitcoin-core", "Allow DNS lookups for -addnode, -seednode and -connect"),
QT_TRANSLATE_NOOP("bitcoin-core", "Allow JSON-RPC connections from specified IP address"),
QT_TRANSLATE_NOOP("bitcoin-core", "Attempt to recover private keys from a corrupt wallet.dat"),
QT_TRANSLATE_NOOP("bitcoin-core", (COIN_NAME_DISPLAY + " version").c_str()),
QT_TRANSLATE_NOOP("bitcoin-core", "CasinoCoin version"),
QT_TRANSLATE_NOOP("bitcoin-core", "Block creation options:"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot downgrade wallet"),
QT_TRANSLATE_NOOP("bitcoin-core", "Cannot resolve -bind address: '%s'"),
@@ -111,7 +109,7 @@ QT_TRANSLATE_NOOP("bitcoin-core", "Error initializing wallet database environmen
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading block database"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet corrupted"),
QT_TRANSLATE_NOOP("bitcoin-core", (std::string("Error loading wallet.dat: Wallet requires newer version of ")+ COIN_NAME_DISPLAY + "").c_str()),
QT_TRANSLATE_NOOP("bitcoin-core", "Error loading wallet.dat: Wallet requires newer version of CasinoCoin"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error opening block database"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error"),
QT_TRANSLATE_NOOP("bitcoin-core", "Error: Disk space is low!"),
@@ -164,9 +162,9 @@ QT_TRANSLATE_NOOP("bitcoin-core", "Rebuild block chain index from current blk000
QT_TRANSLATE_NOOP("bitcoin-core", "Rescan the block chain for missing wallet transactions"),
QT_TRANSLATE_NOOP("bitcoin-core", "Rescanning..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Run in the background as a daemon and accept commands"),
QT_TRANSLATE_NOOP("bitcoin-core", (std::string("SSL options: (see the ") + COIN_NAME_DISPLAY + " Wiki for SSL setup instructions)").c_str()),
QT_TRANSLATE_NOOP("bitcoin-core", "SSL options: (see the CasinoCoin Wiki for SSL setup instructions)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Select the version of socks proxy to use (4-5, default: 5)"),
QT_TRANSLATE_NOOP("bitcoin-core", (std::string("Send command to -server or ") + COIN_NAME + "d").c_str()),
QT_TRANSLATE_NOOP("bitcoin-core", "Send command to -server or casinocoind"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send commands to node running on <ip> (default: 127.0.0.1)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to console instead of debug.log file"),
QT_TRANSLATE_NOOP("bitcoin-core", "Send trace/debug info to debugger"),
@@ -179,10 +177,10 @@ QT_TRANSLATE_NOOP("bitcoin-core", "Set minimum block size in bytes (default: 0)"
QT_TRANSLATE_NOOP("bitcoin-core", "Set the number of threads to service RPC calls (default: 4)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Signing transaction failed"),
QT_TRANSLATE_NOOP("bitcoin-core", (std::string("Specify configuration file (default: ") + COIN_NAME + ".conf)").c_str()),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify configuration file (default: casinocoin.conf)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify connection timeout in milliseconds (default: 5000)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify data directory"),
QT_TRANSLATE_NOOP("bitcoin-core", (std::string("Specify pid file (default: ") + COIN_NAME + "d.pid)").c_str()),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify pid file (default: casinocoind.pid)"),
QT_TRANSLATE_NOOP("bitcoin-core", "Specify your own public address"),
QT_TRANSLATE_NOOP("bitcoin-core", "System error: "),
QT_TRANSLATE_NOOP("bitcoin-core", "This help message"),
@@ -204,7 +202,7 @@ QT_TRANSLATE_NOOP("bitcoin-core", "Use the test network"),
QT_TRANSLATE_NOOP("bitcoin-core", "Username for JSON-RPC connections"),
QT_TRANSLATE_NOOP("bitcoin-core", "Verifying blocks..."),
QT_TRANSLATE_NOOP("bitcoin-core", "Verifying wallet..."),
QT_TRANSLATE_NOOP("bitcoin-core", (std::string("Wallet needed to be rewritten: restart ")+ COIN_NAME_DISPLAY + " to complete").c_str()),
QT_TRANSLATE_NOOP("bitcoin-core", "Wallet needed to be rewritten: restart CasinoCoin to complete"),
QT_TRANSLATE_NOOP("bitcoin-core", "Warning"),
QT_TRANSLATE_NOOP("bitcoin-core", "Warning: This version is obsolete, upgrade required!"),
QT_TRANSLATE_NOOP("bitcoin-core", "You need to rebuild the database using -reindex to change -txindex"),

View File

@@ -16,10 +16,6 @@ QList<Currencies::FiatCurrencyID> Currencies::availableCurrencies()
currencylist.append(CNY);
currencylist.append(JPY);
currencylist.append(RUB);
currencylist.append(CAD);
currencylist.append(GBP);
currencylist.append(AUD);
currencylist.append(NZD);
return currencylist;
}
@@ -32,10 +28,6 @@ bool Currencies::valid(int currency)
case CNY:
case JPY:
case RUB:
case CAD:
case GBP:
case AUD:
case NZD:
return true;
default:
return false;
@@ -51,10 +43,6 @@ QString Currencies::name(int currency)
case CNY: return QString("CNY");
case JPY: return QString("JPY");
case RUB: return QString("RUB");
case CAD: return QString("CAD");
case GBP: return QString("GBP");
case AUD: return QString("AUD");
case NZD: return QString("NZD");
default: return QString("???");
}
}
@@ -63,15 +51,11 @@ QString Currencies::description(int currency)
{
switch(currency)
{
case USD: return QString("US Dollar");
case USD: return QString("US Dollars");
case EUR: return QString("European Euro");
case CNY: return QString("Chinese Yuan");
case JPY: return QString("Japanese Yen");
case RUB: return QString("Russian Ruble");
case CAD: return QString("Canadian Dollar");
case GBP: return QString("British Pound");
case AUD: return QString("Australian Dollar");
case NZD: return QString("New Zealand Dollar");
default: return QString("???");
}
}
@@ -85,10 +69,6 @@ QString Currencies::symbol(int currency)
case CNY: return QString("¥");
case JPY: return QString("¥");
case RUB: return QString("");
case CAD: return QString("$");
case GBP: return QString("£");
case AUD: return QString("$");
case NZD: return QString("$");
default: return QString("$");
}
}

View File

@@ -16,10 +16,6 @@ public:
CNY,
JPY,
RUB,
CAD,
GBP,
AUD,
NZD,
};
//! Get list of currencies, for drop-down box

View File

@@ -35,12 +35,50 @@
<property name="horizontalSpacing">
<number>15</number>
</property>
<item row="1" column="0">
<widget class="QFrame" name="exchangeInfoBox">
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Sunken</enum>
</property>
<layout class="QGridLayout" name="gridLayout_4">
<item row="1" column="0">
<layout class="QVBoxLayout" name="verticalLayoutExchanges"/>
</item>
<item row="0" column="0">
<widget class="QLabel" name="lblExchangesHeader">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<pointsize>10</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true">color: rgb(166, 27, 31);</string>
</property>
<property name="text">
<string>Exchanges</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="0" column="0">
<widget class="QFrame" name="coinInfoBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Minimum">
<horstretch>3</horstretch>
<verstretch>1</verstretch>
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="layoutDirection">
@@ -58,12 +96,6 @@
<layout class="QGridLayout" name="gridLayout_2">
<item row="0" column="0">
<widget class="QLabel" name="lblInformationHeader">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<pointsize>10</pointsize>
@@ -88,19 +120,19 @@
<number>15</number>
</property>
<property name="verticalSpacing">
<number>12</number>
<number>10</number>
</property>
<property name="leftMargin">
<number>10</number>
</property>
<property name="topMargin">
<number>5</number>
<number>10</number>
</property>
<property name="rightMargin">
<number>10</number>
</property>
<property name="bottomMargin">
<number>5</number>
<number>10</number>
</property>
<item row="0" column="0">
<widget class="QLabel" name="lblBlockHeight">
@@ -170,7 +202,7 @@
<string notr="true">-</string>
</property>
<property name="wordWrap">
<bool>false</bool>
<bool>true</bool>
</property>
</widget>
</item>
@@ -189,6 +221,178 @@
</item>
<item row="2" column="1">
<widget class="QLabel" name="txtCoinSupply">
<property name="palette">
<palette>
<active>
<colorrole role="WindowText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Button">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
<colorrole role="Text">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="ButtonText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Base">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
<colorrole role="Window">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
</active>
<inactive>
<colorrole role="WindowText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Button">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
<colorrole role="Text">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="ButtonText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Base">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
<colorrole role="Window">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
</inactive>
<disabled>
<colorrole role="WindowText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Button">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
<colorrole role="Text">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="ButtonText">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>0</red>
<green>0</green>
<blue>0</blue>
</color>
</brush>
</colorrole>
<colorrole role="Base">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
<colorrole role="Window">
<brush brushstyle="SolidPattern">
<color alpha="255">
<red>255</red>
<green>255</green>
<blue>255</blue>
</color>
</brush>
</colorrole>
</disabled>
</palette>
</property>
<property name="font">
<font>
<weight>75</weight>
@@ -206,67 +410,7 @@
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="lblCoinValue">
<property name="text">
<string>Coin Value</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QLabel" name="txtCoinValue">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>-</string>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="lblCoinFiatValue">
<property name="text">
<string>Coin Fiat Value</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QLabel" name="txtCoinFiatValue">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>-</string>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QLabel" name="lblEstimatedMarketCapital">
<property name="text">
<string>Estimated Marketcapital</string>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QLabel" name="txtEstimatedMarketCapital">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>-</string>
</property>
</widget>
</item>
<item row="6" column="0">
<widget class="QLabel" name="lblConnections">
<property name="styleSheet">
<string notr="true"/>
@@ -279,7 +423,7 @@
</property>
</widget>
</item>
<item row="6" column="1">
<item row="4" column="1">
<widget class="QLabel" name="txtConnections">
<property name="font">
<font>
@@ -298,7 +442,7 @@
</property>
</widget>
</item>
<item row="7" column="0">
<item row="5" column="0">
<widget class="QLabel" name="lblDifficulty">
<property name="styleSheet">
<string notr="true"/>
@@ -311,7 +455,7 @@
</property>
</widget>
</item>
<item row="7" column="1">
<item row="5" column="1">
<widget class="QLabel" name="txtDifficulty">
<property name="font">
<font>
@@ -330,7 +474,7 @@
</property>
</widget>
</item>
<item row="8" column="0">
<item row="6" column="0">
<widget class="QLabel" name="lblHashRate">
<property name="styleSheet">
<string notr="true"/>
@@ -343,7 +487,7 @@
</property>
</widget>
</item>
<item row="8" column="1">
<item row="6" column="1">
<widget class="QLabel" name="txtHashRate">
<property name="font">
<font>
@@ -362,105 +506,63 @@
</property>
</widget>
</item>
<item row="7" column="0">
<widget class="QLabel" name="lblTransactionCount">
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="text">
<string>Transactions</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item row="7" column="1">
<widget class="QLabel" name="txtTransactionCount">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="text">
<string notr="true">-</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="lblCoinFiatValue">
<property name="text">
<string>Coin Fiat Value</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QLabel" name="txtCoinFiatValue">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="text">
<string>-</string>
</property>
</widget>
</item>
</layout>
</item>
</layout>
</widget>
</item>
<item row="0" column="1">
<widget class="QFrame" name="twitterFeedBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Minimum">
<horstretch>2</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
<property name="layoutDirection">
<enum>Qt::LeftToRight</enum>
</property>
<property name="autoFillBackground">
<bool>false</bool>
</property>
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Sunken</enum>
</property>
<layout class="QGridLayout" name="gridLayout_5">
<item row="1" column="0">
<layout class="QVBoxLayout" name="verticalLayoutTwitter"/>
</item>
<item row="0" column="0">
<widget class="QLabel" name="lblTwitterHeader">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Fixed">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<pointsize>10</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true">color: rgb(166, 27, 31);</string>
</property>
<property name="text">
<string>Twitter</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
<item row="1" column="0" colspan="2">
<widget class="QFrame" name="exchangeInfoBox">
<property name="sizePolicy">
<sizepolicy hsizetype="Minimum" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>1</verstretch>
</sizepolicy>
</property>
<property name="frameShape">
<enum>QFrame::StyledPanel</enum>
</property>
<property name="frameShadow">
<enum>QFrame::Sunken</enum>
</property>
<layout class="QGridLayout" name="gridLayout_4">
<item row="1" column="0">
<layout class="QVBoxLayout" name="verticalLayoutExchanges"/>
</item>
<item row="0" column="0">
<widget class="QLabel" name="lblExchangesHeader">
<property name="sizePolicy">
<sizepolicy hsizetype="Preferred" vsizetype="Minimum">
<horstretch>0</horstretch>
<verstretch>0</verstretch>
</sizepolicy>
</property>
<property name="font">
<font>
<pointsize>10</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true">color: rgb(166, 27, 31);</string>
</property>
<property name="text">
<string>Exchanges</string>
</property>
</widget>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<resources/>

View File

@@ -38,265 +38,230 @@
<number>7</number>
</property>
<item>
<widget class="QGroupBox" name="groupBox">
<property name="minimumSize">
<size>
<width>470</width>
<height>0</height>
</size>
</property>
<property name="maximumSize">
<size>
<width>470</width>
<height>16777215</height>
</size>
</property>
<layout class="QVBoxLayout" name="verticalLayout_4">
<property name="topMargin">
<number>7</number>
<widget class="QGroupBox" name="groupBox">
<property name="minimumSize">
<size>
<width>470</width>
<height>0</height>
</size>
</property>
<property name="bottomMargin">
<number>7</number>
<property name="maximumSize">
<size>
<width>470</width>
<height>16777215</height>
</size>
</property>
<item>
<layout class="QFormLayout" name="formLayout_2">
<property name="fieldGrowthPolicy">
<enum>QFormLayout::AllNonFixedFieldsGrow</enum>
</property>
<property name="horizontalSpacing">
<number>12</number>
</property>
<property name="verticalSpacing">
<number>12</number>
</property>
<item row="0" column="0" colspan="2">
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QLabel" name="label_5">
<property name="font">
<font>
<pointsize>10</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true">color: rgb(166, 27, 31);</string>
</property>
<property name="text">
<string>Wallet</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="labelWalletStatus">
<property name="toolTip">
<string>The displayed information may be out of date. Your wallet automatically synchronizes with the CasinoCoin network after a connection is established, but this process has not completed yet.</string>
</property>
<property name="styleSheet">
<string notr="true">color: rgb(166, 27, 31);</string>
</property>
<property name="text">
<string notr="true">(out of sync)</string>
</property>
<property name="alignment">
<set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
</property>
</widget>
</item>
</layout>
</item>
<item row="1" column="0">
<widget class="QLabel" name="labelBalanceText">
<property name="text">
<string>Balance:</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLabel" name="labelBalance">
<property name="font">
<font>
<pointsize>10</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="cursor">
<cursorShape>IBeamCursor</cursorShape>
</property>
<property name="toolTip">
<string>Your current balance</string>
</property>
<property name="text">
<string notr="true">0 CSC</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="labelUnconfirmedText">
<property name="text">
<string>Unconfirmed:</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLabel" name="labelUnconfirmed">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="cursor">
<cursorShape>IBeamCursor</cursorShape>
</property>
<property name="toolTip">
<string>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</string>
</property>
<property name="text">
<string notr="true">0 CSC</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="labelImmatureText">
<property name="text">
<string>Immature:</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QLabel" name="labelImmature">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="toolTip">
<string>Mined balance that has not yet matured</string>
</property>
<property name="text">
<string notr="true">0 CSC</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="labelBalanceFiatText">
<property name="text">
<string>Estimated Fiat Balance:</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QLabel" name="labelBalanceFiat">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="toolTip">
<string>Estimated Fiat balance calculated against current market value</string>
</property>
<property name="text">
<string notr="true">0</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
<item row="5" column="0">
<widget class="QLabel" name="lblTransactionCount">
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="text">
<string>Transactions:</string>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item row="5" column="1">
<widget class="QLabel" name="txtTransactionCount">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true"/>
</property>
<property name="text">
<string notr="true">-</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="wordWrap">
<bool>true</bool>
</property>
</widget>
</item>
<item row="6" column="0" colspan="2">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>100</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayoutAdvertWidget"/>
</item>
</layout>
</widget>
<layout class="QVBoxLayout" name="verticalLayout_4">
<property name="topMargin">
<number>7</number>
</property>
<property name="bottomMargin">
<number>7</number>
</property>
<item>
<layout class="QFormLayout" name="formLayout_2">
<property name="fieldGrowthPolicy">
<enum>QFormLayout::AllNonFixedFieldsGrow</enum>
</property>
<property name="horizontalSpacing">
<number>12</number>
</property>
<property name="verticalSpacing">
<number>12</number>
</property>
<item row="0" column="0" colspan="2">
<layout class="QHBoxLayout" name="horizontalLayout_4">
<item>
<widget class="QLabel" name="label_5">
<property name="font">
<font>
<pointsize>10</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="styleSheet">
<string notr="true">color: rgb(166, 27, 31);</string>
</property>
<property name="text">
<string>Wallet</string>
</property>
</widget>
</item>
<item>
<spacer name="horizontalSpacer_2">
<property name="orientation">
<enum>Qt::Horizontal</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>40</width>
<height>20</height>
</size>
</property>
</spacer>
</item>
<item>
<widget class="QLabel" name="labelWalletStatus">
<property name="toolTip">
<string>The displayed information may be out of date. Your wallet automatically synchronizes with the CasinoCoin network after a connection is established, but this process has not completed yet.</string>
</property>
<property name="styleSheet">
<string notr="true">color: rgb(166, 27, 31);</string>
</property>
<property name="text">
<string notr="true">(out of sync)</string>
</property>
<property name="alignment">
<set>Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter</set>
</property>
</widget>
</item>
</layout>
</item>
<item row="1" column="0">
<widget class="QLabel" name="labelBalanceText">
<property name="text">
<string>Balance:</string>
</property>
</widget>
</item>
<item row="1" column="1">
<widget class="QLabel" name="labelBalance">
<property name="font">
<font>
<pointsize>10</pointsize>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="cursor">
<cursorShape>IBeamCursor</cursorShape>
</property>
<property name="toolTip">
<string>Your current balance</string>
</property>
<property name="text">
<string notr="true">0 CSC</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
<item row="2" column="0">
<widget class="QLabel" name="labelUnconfirmedText">
<property name="text">
<string>Unconfirmed:</string>
</property>
</widget>
</item>
<item row="2" column="1">
<widget class="QLabel" name="labelUnconfirmed">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="cursor">
<cursorShape>IBeamCursor</cursorShape>
</property>
<property name="toolTip">
<string>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</string>
</property>
<property name="text">
<string notr="true">0 CSC</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
<item row="3" column="0">
<widget class="QLabel" name="labelImmatureText">
<property name="text">
<string>Immature:</string>
</property>
</widget>
</item>
<item row="3" column="1">
<widget class="QLabel" name="labelImmature">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="toolTip">
<string>Mined balance that has not yet matured</string>
</property>
<property name="text">
<string notr="true">0 CSC</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
<item row="4" column="0">
<widget class="QLabel" name="labelBalanceFiatText">
<property name="text">
<string>Estimated Fiat Balance:</string>
</property>
</widget>
</item>
<item row="4" column="1">
<widget class="QLabel" name="labelBalanceFiat">
<property name="font">
<font>
<weight>75</weight>
<bold>true</bold>
</font>
</property>
<property name="toolTip">
<string>Estimated Fiat balance calculated against current market value</string>
</property>
<property name="text">
<string notr="true">0</string>
</property>
<property name="alignment">
<set>Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter</set>
</property>
<property name="textInteractionFlags">
<set>Qt::LinksAccessibleByMouse|Qt::TextSelectableByKeyboard|Qt::TextSelectableByMouse</set>
</property>
</widget>
</item>
<item row="5" column="0" colspan="2">
<spacer name="verticalSpacer">
<property name="orientation">
<enum>Qt::Vertical</enum>
</property>
<property name="sizeHint" stdset="0">
<size>
<width>20</width>
<height>100</height>
</size>
</property>
</spacer>
</item>
</layout>
</item>
<item>
<layout class="QVBoxLayout" name="verticalLayoutAdvertWidget"/>
</item>
</layout>
</widget>
</item>
</layout>
</item>

View File

@@ -32,7 +32,7 @@
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0600
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
@@ -84,7 +84,7 @@ void setupAmountWidget(QLineEdit *widget, QWidget *parent)
bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out)
{
// return if URI is not valid or is no bitcoin URI
if(!uri.isValid() || uri.scheme() != QString(COIN_NAME.c_str()))
if(!uri.isValid() || uri.scheme() != QString("casinocoin"))
return false;
SendCoinsRecipient rv;
@@ -139,9 +139,9 @@ bool parseBitcoinURI(QString uri, SendCoinsRecipient *out)
//
// Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host,
// which will lower-case it (and thus invalidate the address).
if(uri.startsWith(QString((COIN_NAME + "://").c_str())))
if(uri.startsWith("casinocoin://"))
{
uri.replace(0, (COIN_NAME.length()+1), QString((COIN_NAME + ":").c_str()));
uri.replace(0, 11, "casinocoin:");
}
QUrl uriInstance(uri);
return parseBitcoinURI(uriInstance, out);
@@ -301,7 +301,7 @@ bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt)
#ifdef WIN32
boost::filesystem::path static StartupShortcutPath()
{
return GetSpecialFolderPath(CSIDL_STARTUP) / (COIN_NAME_DISPLAY + ".lnk").c_str();
return GetSpecialFolderPath(CSIDL_STARTUP) / "CasinoCoin.lnk";
}
bool GetStartOnSystemStartup()
@@ -383,7 +383,7 @@ boost::filesystem::path static GetAutostartDir()
boost::filesystem::path static GetAutostartFilePath()
{
return GetAutostartDir() / ""+ COIN_NAME + ".desktop";
return GetAutostartDir() / "casinocoin.desktop";
}
bool GetStartOnSystemStartup()
@@ -424,7 +424,7 @@ bool SetStartOnSystemStartup(bool fAutoStart)
// Write a bitcoin.desktop file to the autostart directory:
optionFile << "[Desktop Entry]\n";
optionFile << "Type=Application\n";
optionFile << "Name="+ COIN_NAME_DISPLAY + "\n";
optionFile << "Name=CasinoCoin\n";
optionFile << "Exec=" << pszExePath << " -min\n";
optionFile << "Terminal=false\n";
optionFile << "Hidden=false\n";
@@ -495,10 +495,10 @@ bool SetStartOnSystemStartup(bool fAutoStart) { return false; }
HelpMessageBox::HelpMessageBox(QWidget *parent) :
QMessageBox(parent)
{
header = tr((COIN_NAME_DISPLAY + "-Qt").c_str()) + " " + tr("version") + " " +
header = tr("CasinoCoin-Qt") + " " + tr("version") + " " +
QString::fromStdString(FormatFullVersion()) + "\n\n" +
tr("Usage:") + "\n" +
QString::fromStdString(" "+ COIN_NAME + "-qt [") + tr("command-line options") + "] " + "\n";
" casinocoin-qt [" + tr("command-line options") + "] " + "\n";
coreOptions = QString::fromStdString(HelpMessage());
@@ -507,7 +507,7 @@ HelpMessageBox::HelpMessageBox(QWidget *parent) :
" -min " + tr("Start minimized") + "\n" +
" -splash " + tr("Show splash screen on startup (default: 1)") + "\n";
setWindowTitle(tr((COIN_NAME_DISPLAY + "-Qt").c_str()));
setWindowTitle(tr("CasinoCoin-Qt"));
setTextFormat(Qt::PlainText);
// setMinimumWidth is ignored for QMessageBox so put in non-breaking spaces to make it wider.
setText(header + QString(QChar(0x2003)).repeated(50));

View File

@@ -4,32 +4,33 @@
#include "clientmodel.h"
#include "bitcoinrpc.h"
#include <QDateTime>
#include <QDebug>
#include "bitcoinunits.h"
#include "main.h"
#include "overviewpage.h"
#include "qtquick_controls/cpp/guiexchangeswidget.h"
#include "twitter/twitterwidget.h"
using namespace std;
InfoPage::InfoPage(QWidget *parent) :
QDialog(parent),
ui(new Ui::InfoPage),
exchangesWidget( 0 ),
twitterWidget( 0 )
exchangesWidget( 0 )
{
ui->setupUi(this);
ui->coinInfoBox->setMinimumHeight(250);
ui->twitterFeedBox->setMinimumHeight(250);
ui->exchangeInfoBox->setMinimumHeight(250);
createTwitterWidget();
createExchangesWidget();
}
void InfoPage::setWalletModel(WalletModel *model)
{
this->walletModel = model;
if(model)
{
// subscribe to transaction changes
connect(model, SIGNAL(numTransactionsChanged(int)), this, SLOT(setNumTransactions(int)));
setNumTransactions(model->getNumTransactions());
}
}
void InfoPage::setClientModel(ClientModel *model)
@@ -56,10 +57,7 @@ void InfoPage::setNumBlocks(int count, int countOfPeers)
// block height changed so update all possible values as well
if(clientModel)
{
QDateTime blockTime = clientModel->getLastBlockDate().toTimeSpec(Qt::UTC);
QString formattedBlockTime = blockTime.toString("dd-MM-yyyy HH:mm:ss");
formattedBlockTime.append(" UTC");
ui->txtLastBlockTime->setText(formattedBlockTime);
ui->txtLastBlockTime->setText(clientModel->getLastBlockDate().toString());
ui->txtDifficulty->setText(QString::number(GetDifficulty()));
ui->txtCoinSupply->setText(BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, GetTotalCoinSupply(count, false)));
double megaHash = GetNetworkHashRate(-1, count) / 1000000;
@@ -67,6 +65,11 @@ void InfoPage::setNumBlocks(int count, int countOfPeers)
}
}
void InfoPage::setNumTransactions(int count)
{
ui->txtTransactionCount->setText(QString::number(count));
}
double InfoPage::GetNetworkHashRate(int lookup, int height) {
CBlockIndex *pb = pindexBest;
@@ -109,12 +112,6 @@ InfoPage::~InfoPage()
delete ui;
}
void InfoPage::createTwitterWidget()
{
twitterWidget = new TwitterWidget( this );
ui->verticalLayoutTwitter->addWidget( twitterWidget->dockQmlToWidget() );
}
void InfoPage::createExchangesWidget()
{
exchangesWidget = new GUIExchangesWidget( this );
@@ -122,9 +119,7 @@ void InfoPage::createExchangesWidget()
ui->verticalLayoutExchanges->addWidget( exchangesWidget->dockQmlToWidget() );
}
void InfoPage::setCoinValues(QString coinValue, QString coinFiatValue, QString marketCapital)
void InfoPage::setCoinFiatValue(QString coinValue)
{
ui->txtCoinValue->setText(coinValue);
ui->txtCoinFiatValue->setText(coinFiatValue);
ui->txtEstimatedMarketCapital->setText(marketCapital);
ui->txtCoinFiatValue->setText(coinValue);
}

View File

@@ -6,7 +6,6 @@
class WalletModel;
class ClientModel;
class GUIExchangesWidget;
class TwitterWidget;
namespace Ui {
class InfoPage;
@@ -21,8 +20,10 @@ public slots:
void setNumConnections(int count);
/** Set number of blocks shown in the UI */
void setNumBlocks(int count, int countOfPeers);
/** Set coin values */
void setCoinValues(const QString coinValue, const QString coinFiatValue, const QString marketCapital);
/** Set number of transactions shown in the UI */
void setNumTransactions(int count);
/** Set Fiat coin value */
void setCoinFiatValue(const QString coinValue);
public:
explicit InfoPage(QWidget *parent = 0);
@@ -35,10 +36,8 @@ private:
WalletModel *walletModel;
ClientModel *clientModel;
GUIExchangesWidget* exchangesWidget;
TwitterWidget* twitterWidget;
void createTwitterWidget();
void createExchangesWidget();
void createExchangesWidget();
double GetNetworkHashRate(int lookup, int height);
};

View File

@@ -219,10 +219,6 @@ void OverviewPage::setWalletModel(WalletModel *model)
// set visibility of adverts widget
updateDisplayPromotions(model->getOptionsModel()->getDisplayPromotions());
// subscribe to transaction changes
connect(model, SIGNAL(numTransactionsChanged(int)), this, SLOT(setNumTransactions(int)));
setNumTransactions(model->getNumTransactions());
}
// update the display unit, to not use the default ("BTC")
@@ -267,7 +263,6 @@ void OverviewPage::updateCoinInfoFromWeb( JsonCoinInfoParser* coinInfoParser )
{
qDebug() << "CoinInfo ID: " << coinInfoParser->getCoinInfo().find("ID").value().toDouble();
qDebug() << "CoinInfo InfoTime: " <<coinInfoParser->getCoinInfo().find("InfoTime").value().toString();
qDebug() << "CoinInfo CoinValue: " << QString::number( coinInfoParser->getCoinInfo().find("PriceBTC").value().toDouble(), 'f', 8 );
// save the coin information
coinInformation = coinInfoParser->getCoinInfo();
// calculate and set the estimated fiat balance
@@ -282,15 +277,10 @@ void OverviewPage::updateFiatBalance(int currency)
if(!coinInformation.isEmpty())
{
QString conversionCurrency = QString("Price").append(Currencies::name(currency));
QString coinValue = QString::number( coinInformation.find("PriceBTC").value().toDouble(), 'f', 8 );
double currencyValue = coinInformation.find(conversionCurrency).value().toDouble();
double marketCapValue = coinInformation.find("MarketCapital").value().toDouble();
// create formated fiat value
QString formattedFiatValue = Currencies::format(currency, currencyValue, true, 4, false);
// create formatted market capital value
QString formattedMarketCapital = Currencies::format(Currencies::USD, marketCapValue, true, 2, false);
// emit signal for change value
emit coinValueChanged(coinValue, formattedFiatValue, formattedMarketCapital);
QString coinValue = Currencies::format(currency, currencyValue, true, 4, false);
emit coinFiatValueChanged(coinValue);
// calculate and set fiat balance
double fiatBalance = currentBalance * currencyValue;
QString fiatBalanceString = Currencies::format(currency,fiatBalance,true, 2, true);
@@ -311,11 +301,6 @@ void OverviewPage::updateDisplayPromotions(bool checked)
}
}
void OverviewPage::setNumTransactions(int count)
{
ui->txtTransactionCount->setText(QString::number(count));
}
OverviewPage::~OverviewPage()
{
delete ui;

View File

@@ -36,11 +36,10 @@ public:
public slots:
void setBalance(qint64 balance, qint64 unconfirmedBalance, qint64 immatureBalance);
void setNumTransactions(int count);
signals:
void transactionClicked(const QModelIndex &index);
void coinValueChanged(const QString coinValue, const QString formattedCoinFiatValue, const QString marketCapital);
void coinFiatValueChanged(const QString formattedCoinFiatValue);
private:
Ui::OverviewPage *ui;

View File

@@ -106,7 +106,7 @@ PaymentServer::PaymentServer(QApplication* parent) : QObject(parent), saveURIs(t
uriServer = new QLocalServer(this);
if (!uriServer->listen(name))
qDebug() << tr((std::string("Cannot start ")+ COIN_NAME + ": click-to-pay handler").c_str());
qDebug() << tr("Cannot start casinocoin: click-to-pay handler");
else
connect(uriServer, SIGNAL(newConnection()), this, SLOT(handleURIConnection()));
}

View File

@@ -5,7 +5,6 @@
#include "guiconstants.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "version.h"
#include <QPixmap>
#if QT_VERSION < 0x050000
@@ -86,7 +85,7 @@ void QRCodeDialog::genCode()
QString QRCodeDialog::getURI()
{
QString ret = QString((COIN_NAME + ":%1").c_str()).arg(address);
QString ret = QString("casinocoin:%1").arg(address);
int paramCount = 0;
ui->outUri->clear();

View File

@@ -1,139 +0,0 @@
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** 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 The Qt Company Ltd 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$
**
****************************************************************************/
import QtQuick 2.0
import "tweetsearch.js" as Helper
import QtQuick.Controls 1.4
Rectangle {
id: id_TwitterRoot
width: parent ? parent.width : 0
height: parent ? parent.height : 0
color: GUI20Skin.colorFrameBackground
property int inAnimDur: 250
property int counter: 0
property alias isLoading: tweetsModel.isLoading
property var idx
property var ids
Component.onCompleted: ids = new Array()
function idInModel(id)
{
for (var j = 0; j < ids.length; j++)
if (ids[j] === id)
return 1
return 0
}
TweetsModel {
id: tweetsModel
onIsLoaded: {
console.debug("Reload")
idx = new Array()
for (var i = 0; i < tweetsModel.model.count; i++) {
var id = tweetsModel.model.get(i).id
if (!idInModel(id))
idx.push(i)
}
console.debug(idx.length + " new tweets")
id_TwitterRoot.counter = idx.length
}
}
Timer {
id: timer
interval: 500; running: id_TwitterRoot.counter; repeat: true
onTriggered: {
id_TwitterRoot.counter--;
var id = tweetsModel.model.get(idx[id_TwitterRoot.counter]).id;
var item = tweetsModel.model.get(id_TwitterRoot.counter);
if(item.retweeted_status != undefined){
item = item.retweeted_status;
}
mainListView.add( { "statusText": Helper.insertLinks(item.text, item.entities),
"twitterName": item.user.screen_name,
"name" : item.user.name,
"userImage": item.user.profile_image_url,
"source": item.source,
"id": id,
"uri": Helper.insertLinks(item.user.url, item.user.entities),
"published": item.created_at } );
ids.push(id)
}
}
Timer {
id: refreshTwitterFeedTimer
interval: 600000;
running: true;
repeat: true;
onTriggered: tweetsModel.reload()
}
ScrollView {
id: mainScrollView
anchors.fill: id_TwitterRoot
ListView {
id: mainListView
anchors.fill: mainScrollView
delegate: TweetDelegate { }
model: ListModel { id: finalModel }
add: Transition {
NumberAnimation { property: "hm"; from: 0; to: 1.0; duration: 300; easing.type: Easing.OutQuad }
PropertyAction { property: "appear"; value: 250 }
}
onDragEnded: tweetsModel.reload()
function clear() {
ids = new Array()
model.clear()
}
function add(obj) {
model.insert(0, obj)
}
}
}
}

View File

@@ -1,173 +0,0 @@
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** 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 The Qt Company Ltd 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$
**
****************************************************************************/
import QtQuick 2.0
Item {
id: container
property int animDuration: 300
property Item front: Item {}
property Item back: Item {}
property real factor: 0.1 // amount the edges fold in for the 3D effect
property alias delta: effect.delta
property Item cur: frontShown ? front : back
property Item noncur: frontShown ? back : front
function swap() {
var tmp = front;
front = back;
back = tmp;
resync();
}
width: cur.width
height: cur.height
onFrontChanged: resync();
onBackChanged: resync();
function resync() {//TODO: Are the items ever actually visible?
back.parent = container;
front.parent = container;
frontShown ? back.visible = false : front.visible = false;
}
property bool frontShown: true
onFrontShownChanged: {
back.visible = !frontShown
front.visible = frontShown
}
function flipUp(start) {
effect.visible = true;
effect.sourceA = effect.source1
effect.sourceB = effect.source2
if (start == undefined)
start = 1.0;
deltaAnim.from = start;
deltaAnim.to = 0.0
dAnim.start();
frontShown = false;
}
function flipDown(start) {
effect.visible = true;
effect.sourceA = effect.source1
effect.sourceB = effect.source2
if (start == undefined)
start = 0.0;
deltaAnim.from = start;
deltaAnim.to = 1.0
dAnim.start();
frontShown = true;
}
ShaderEffect {
id: effect
width: cur.width
height: cur.height
property real factor: container.factor * width
property real delta: 1.0
mesh: GridMesh { resolution: Qt.size(8,2) }
SequentialAnimation on delta {
id: dAnim
running: false
NumberAnimation {
id: deltaAnim
duration: animDuration//expose anim
}
}
property variant sourceA: source1
property variant sourceB: source1
property variant source1: ShaderEffectSource {
sourceItem: front
hideSource: effect.visible
}
property variant source2: ShaderEffectSource {
sourceItem: back
hideSource: effect.visible
}
fragmentShader: "
uniform lowp float qt_Opacity;
uniform sampler2D sourceA;
uniform sampler2D sourceB;
uniform highp float delta;
varying highp vec2 qt_TexCoord0;
void main() {
highp vec4 tex = vec4(qt_TexCoord0.x, qt_TexCoord0.y * 2.0, qt_TexCoord0.x, (qt_TexCoord0.y-0.5) * 2.0);
highp float shade = clamp(delta*2.0, 0.5, 1.0);
highp vec4 col;
if (qt_TexCoord0.y < 0.5) {
col = texture2D(sourceA, tex.xy) * (shade);
} else {
col = texture2D(sourceB, tex.zw) * (1.5 - shade);
col.w = 1.0;
}
gl_FragColor = col * qt_Opacity;
}
"
property real h: height
vertexShader: "
uniform highp float delta;
uniform highp float factor;
uniform highp float h;
uniform highp mat4 qt_Matrix;
attribute highp vec4 qt_Vertex;
attribute highp vec2 qt_MultiTexCoord0;
varying highp vec2 qt_TexCoord0;
void main() {
highp vec4 pos = qt_Vertex;
if (qt_MultiTexCoord0.y == 0.0)
pos.x += factor * (1. - delta) * (qt_MultiTexCoord0.x * -2.0 + 1.0);
else if (qt_MultiTexCoord0.y == 1.0)
pos.x += factor * (delta) * (qt_MultiTexCoord0.x * -2.0 + 1.0);
else
pos.y = delta * h;
gl_Position = qt_Matrix * pos;
qt_TexCoord0 = qt_MultiTexCoord0;
}"
}
}

View File

@@ -1,188 +0,0 @@
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** 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 The Qt Company Ltd 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$
**
****************************************************************************/
import QtQuick 2.0
import "tweetsearch.js" as Helper
Item {
id: container
property real hm: 1.0
property int appear: -1
property real startRotation: 1
onAppearChanged: {
container.startRotation = 0.5
flipBar.animDuration = appear;
delayedAnim.start();
}
SequentialAnimation {
id: delayedAnim
PauseAnimation { duration: 50 }
ScriptAction { script: flipBar.flipDown(startRotation); }
}
width: parent ? parent.width : 0
height: flipBar.height * hm
FlipBar {
id: flipBar
property bool flipped: false
delta: startRotation
anchors.bottom: parent.bottom
width: container.ListView.view ? container.ListView.view.width : 0
height: Math.max(72, tweet.y + tweet.height + 10)
front: Rectangle {
width: container.ListView.view ? container.ListView.view.width : 0
height: Math.max(72, tweet.y + tweet.height + 10)
Rectangle { color: GUI20Skin.colorToolbarMainGradientEnd; width: parent.width; height: 1 }
Rectangle { color: GUI20Skin.colorToolbarMainGradientEnd; width: parent.width; height: 1; anchors.bottom: parent.bottom }
Image {
id: placeHolder
source: "resources/anonymous.png"
x: 10; y: 9
visible: avatar.status != Image.Ready
}
Image {
id: avatar
source: model.userImage
anchors.fill: placeHolder
MouseArea {
id: mouseArea
anchors.fill: parent
onClicked: {
flipBar.flipUp()
flipBar.flipped = true
}
}
}
Text {
id: name
text: model.name
anchors { left: avatar.right; leftMargin: 10; top: avatar.top; topMargin: -3 }
font.pixelSize: 12
font.bold: true
color: GUI20Skin.colorToolbarMainGradientEnd
linkColor: "blue"
}
Text {
id: tweet
text: model.statusText
anchors { left: avatar.right; leftMargin: 10; top: name.bottom; topMargin: 0; right: parent.right; rightMargin: 10 }
wrapMode: Text.WordWrap
font.pixelSize: 12
font.bold: false
color: "black"
linkColor: "blue"
onLinkActivated: {
var tag = link.split("https://twitter.com/search?q=%23")
var user = link.split("https://twitter.com/")
if (tag[1] != undefined) {
mainListView.positionViewAtBeginning()
mainListView.clear()
mainListView.autoSearch('tag', tag[1])
tweetsModel.from = ""
tweetsModel.phrase = "#" + tag[1]
} else if (user[1] != undefined) {
mainListView.positionViewAtBeginning()
mainListView.clear()
mainListView.autoSearch('user', user[1])
tweetsModel.phrase = ""
tweetsModel.from = user[1]
} else
Qt.openUrlExternally(link)
}
}
}
back: Rectangle {
width: container.ListView.view ? container.ListView.view.width : 0
height: Math.max(72, tweet.y + tweet.height + 10)
color: "#be4a25"
Rectangle { color: "#ff6633"; width: parent.width; height: 1 }
Rectangle { color: "#80341a"; width: parent.width; height: 1; anchors.bottom: parent.bottom }
Image {
id: avatar2
source: model.userImage
anchors.right: parent.right
anchors.rightMargin: 10
y: 9
MouseArea {
anchors.fill: parent
onClicked: {
flipBar.flipDown()
flipBar.flipped = false
}
}
}
Text {
id: username
text: model.twitterName
x: 10; anchors { top: avatar2.top; topMargin: -3 }
font.pixelSize: 12
font.bold: true
color: "black"
linkColor: "blue"
}
Text {
text: model.source + "<br>" + Helper.formatDate(model.published) + "<br>" + model.uri
x: 10; anchors { top: username.bottom; topMargin: 0 }
wrapMode: Text.WordWrap
font.pixelSize: 12
font.bold: false
color: "#ffc2ad"
linkColor: "blue"
onLinkActivated: Qt.openUrlExternally(link);
}
}
}
}

View File

@@ -1,126 +0,0 @@
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** 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 The Qt Company Ltd 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$
**
****************************************************************************/
import QtQuick 2.0
import "tweetsearch.js" as Helper
Item {
id: wrapper
//! [auth tokens]
property string consumerKey : ""
property string consumerSecret : ""
//! [auth tokens]
property string bearerToken : ""
property variant model: tweets
property string from : "CasinocoinNews"
property string phrase : ""
property int status: XMLHttpRequest.UNSENT
property bool isLoading: status === XMLHttpRequest.LOADING
property bool wasLoading: false
signal isLoaded
ListModel { id: tweets }
function encodePhrase(x) { return encodeURIComponent(x); }
function reload() {
tweets.clear()
if (from == "" && phrase == "")
return;
//! [requesting]
var req = new XMLHttpRequest;
req.open("GET", "https://api.twitter.com/1.1/statuses/user_timeline.json?" +
"&count=10&screen_name=" + from);
req.setRequestHeader("Authorization", "Bearer " + bearerToken);
req.onreadystatechange = function() {
status = req.readyState;
if (status === XMLHttpRequest.DONE) {
var objectArray = JSON.parse(req.responseText);
if (objectArray.errors !== undefined)
console.log("Error fetching tweets: " + objectArray.errors[0].message)
else {
for (var key in objectArray) {
var jsonObject = objectArray[key];
tweets.append(jsonObject);
}
}
if (wasLoading == true)
wrapper.isLoaded()
}
wasLoading = (status === XMLHttpRequest.LOADING);
}
req.send();
//! [requesting]
}
onPhraseChanged: reload();
onFromChanged: reload();
Component.onCompleted: {
if (consumerKey === "" || consumerSecret == "") {
bearerToken = encodeURIComponent(Helper.demoToken())
return;
}
var authReq = new XMLHttpRequest;
authReq.open("POST", "https://api.twitter.com/oauth2/token");
authReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
authReq.setRequestHeader("Authorization", "Basic " + Qt.btoa(consumerKey + ":" + consumerSecret));
authReq.onreadystatechange = function() {
if (authReq.readyState === XMLHttpRequest.DONE) {
var jsonResponse = JSON.parse(authReq.responseText);
if (jsonResponse.errors !== undefined)
console.log("Authentication error: " + jsonResponse.errors[0].message)
else
{
bearerToken = jsonResponse.access_token;
reload();
}
}
}
authReq.send("grant_type=client_credentials");
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

View File

@@ -1,62 +0,0 @@
.pragma library
function formatDate(date)
{
var da = new Date(date)
return da.toDateString()
}
function demoToken()
{
var a = new Array(22).join('A')
return a + String.fromCharCode(0x44, 0x69, 0x4a, 0x52, 0x51, 0x41, 0x41, 0x41, 0x41,
0x41, 0x41, 0x74, 0x2b, 0x72, 0x6a, 0x6c, 0x2b, 0x71,
0x6d, 0x7a, 0x30, 0x72, 0x63, 0x79, 0x2b, 0x42, 0x62,
0x75, 0x58, 0x42, 0x42, 0x73, 0x72, 0x55, 0x48, 0x47,
0x45, 0x67, 0x3d, 0x71, 0x30, 0x45, 0x4b, 0x32, 0x61,
0x57, 0x71, 0x51, 0x4d, 0x62, 0x31, 0x35, 0x67, 0x43,
0x5a, 0x4e, 0x77, 0x5a, 0x6f, 0x39, 0x79, 0x71, 0x61,
0x65, 0x30, 0x68, 0x70, 0x65, 0x32, 0x46, 0x44, 0x73,
0x53, 0x39, 0x32, 0x57, 0x41, 0x75, 0x30, 0x67)
}
function linkForEntity(entity)
{
return (entity.url ? entity.url :
(entity.screen_name ? 'https://twitter.com/' + entity.screen_name :
'https://twitter.com/search?q=%23' + entity.text))
}
function textForEntity(entity)
{
return (entity.display_url ? entity.display_url :
(entity.screen_name ? entity.screen_name : entity.text))
}
function insertLinks(text, entities)
{
if (typeof text !== 'string')
return "";
if (!entities)
return text;
// Add all links (urls, usernames and hashtags) to an array and sort them in
// descending order of appearance in text
var links = []
if (entities.urls)
links = entities.urls.concat(entities.hashtags, entities.user_mentions)
else if (entities.url)
links = entities.url.urls
links.sort(function(a, b) { return b.indices[0] - a.indices[0] })
for (var i = 0; i < links.length; i++) {
var offset = links[i].url ? 0 : 1
text = text.substring(0, links[i].indices[0] + offset) +
'<a href=\"' + linkForEntity(links[i]) + '\">' +
textForEntity(links[i]) + '</a>' +
text.substring(links[i].indices[1])
}
return text.replace(/\n/g, '<br>');
}

View File

@@ -1,40 +0,0 @@
#include "twitterwidget.h"
#include <QHBoxLayout>
#include <QCheckBox>
#include <QQuickView>
#include <QQmlContext>
#include "gui20_skin.h"
TwitterWidget::TwitterWidget(QWidget *parent)
: QWidget(parent)
{
}
TwitterWidget::~TwitterWidget()
{
// member objects are moved to qml engine and it manages their instances
}
QWidget* TwitterWidget::dockQmlToWidget()
{
QQuickView* pTwitterWindow = new QQuickView;
QWidget* pPlaceHolder = 0;
if ( pTwitterWindow )
{
QQmlContext* pContext = pTwitterWindow->rootContext();
if ( pContext )
{
pContext->setContextProperty( "GUI20Skin", &GUI20Skin::Instance() );
}
pTwitterWindow->setSource( QUrl( QStringLiteral( "qrc:/qml/twitter/CasinocoinTwitterFeed.qml" ) ) );
pPlaceHolder = QWidget::createWindowContainer( pTwitterWindow, this );
if ( pPlaceHolder )
{
pPlaceHolder->setMinimumSize( 500, 170 );
pPlaceHolder->setSizePolicy( QSizePolicy::Expanding, QSizePolicy::Expanding );
}
}
return pPlaceHolder;
}

View File

@@ -1,25 +0,0 @@
#ifndef TWITTERWIDGET_H
#define TWITTERWIDGET_H
#include <QWidget>
class TwitterWidget : public QWidget
{
Q_OBJECT
public:
TwitterWidget( QWidget *parent = 0) ;
~TwitterWidget();
QWidget* dockQmlToWidget();
public slots:
private:
void registerCustomQmlTypes();
private slots:
};
#endif // TWITTERWIDGET_H

View File

@@ -92,7 +92,7 @@ WalletView::WalletView(QWidget *parent, BitcoinGUI *_gui):
// Clicking on "Export" allows to export the transaction list
connect(exportButton, SIGNAL(clicked()), transactionView, SLOT(exportClicked()));
// subscribe to coin value changes
connect(overviewPage, SIGNAL(coinValueChanged(const QString, const QString, const QString)), infoPage, SLOT(setCoinValues(const QString, const QString, const QString)));
connect(overviewPage, SIGNAL(coinFiatValueChanged(const QString)), infoPage, SLOT(setCoinFiatValue(const QString)));
gotoOverviewPage();
}

View File

@@ -36,7 +36,7 @@ Value importprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 3)
throw runtime_error(
"importprivkey <"+ COIN_NAME + "privkey> [label] [rescan=true]\n"
"importprivkey <casinocoinprivkey> [label] [rescan=true]\n"
"Adds a private key (as returned by dumpprivkey) to your wallet.");
string strSecret = params[0].get_str();
@@ -79,13 +79,13 @@ Value dumpprivkey(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"dumpprivkey <"+ COIN_NAME + "address>\n"
"Reveals the private key corresponding to <"+ COIN_NAME + "address>.");
"dumpprivkey <casinocoinaddress>\n"
"Reveals the private key corresponding to <casinocoinaddress>.");
string strAddress = params[0].get_str();
CBitcoinAddress address;
if (!address.SetString(strAddress))
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid "+ COIN_NAME_DISPLAY + " address");
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CasinoCoin address");
CKeyID keyID;
if (!address.GetKeyID(keyID))
throw JSONRPCError(RPC_TYPE_ERROR, "Address does not refer to a key");

View File

@@ -171,10 +171,10 @@ Value getworkex(const Array& params, bool fHelp)
);
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, ""+ COIN_NAME_DISPLAY + " is not connected!");
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "CasinoCoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, ""+ COIN_NAME_DISPLAY + " is downloading blocks...");
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "CasinoCoin is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
@@ -311,10 +311,10 @@ Value getwork(const Array& params, bool fHelp)
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, ""+ COIN_NAME_DISPLAY + " is not connected!");
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "CasinoCoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, ""+ COIN_NAME_DISPLAY + " is downloading blocks...");
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "CasinoCoin is downloading blocks...");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
@@ -453,10 +453,10 @@ Value getblocktemplate(const Array& params, bool fHelp)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, ""+ COIN_NAME_DISPLAY + " is not connected!");
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "CasinoCoin is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, ""+ COIN_NAME_DISPLAY + " is downloading blocks...");
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "CasinoCoin is downloading blocks...");
// Update block
static unsigned int nTransactionsUpdatedLast;

View File

@@ -48,7 +48,7 @@ Value getpeerinfo(const Array& params, bool fHelp)
Object obj;
obj.push_back(Pair("addr", stats.addrName));
obj.push_back(Pair("services", strprintf("%08" PRI64x, stats.nServices)));
obj.push_back(Pair("services", strprintf("%08"PRI64x, stats.nServices)));
obj.push_back(Pair("lastsend", (boost::int64_t)stats.nLastSend));
obj.push_back(Pair("lastrecv", (boost::int64_t)stats.nLastRecv));
obj.push_back(Pair("bytessent", (boost::int64_t)stats.nSendBytes));

View File

@@ -195,7 +195,7 @@ Value listunspent(const Array& params, bool fHelp)
{
CBitcoinAddress address(input.get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid "+ COIN_NAME_DISPLAY + " address: ")+input.get_str());
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid CasinoCoin address: ")+input.get_str());
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+input.get_str());
setAddress.insert(address);
@@ -294,7 +294,7 @@ Value createrawtransaction(const Array& params, bool fHelp)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid "+ COIN_NAME_DISPLAY + " address: ")+s.name_);
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid CasinoCoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);

View File

@@ -4,12 +4,18 @@
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <boost/assign/list_of.hpp>
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/lexical_cast.hpp>
#include "walletserver.h"
#include "wallet.h"
#include "walletdb.h"
#include "bitcoinrpc.h"
#include "init.h"
#include "base58.h"
#include "ui_interface.h"
using namespace std;
using namespace boost;
@@ -68,7 +74,7 @@ Value getinfo(const Array& params, bool fHelp)
proxyType proxy;
GetProxy(NET_IPV4, proxy);
const Array emptyArray;
Object obj;
obj.push_back(Pair("version", (int)CLIENT_VERSION));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
@@ -77,6 +83,7 @@ Value getinfo(const Array& params, bool fHelp)
obj.push_back(Pair("balance", ValueFromAmount(pwalletMain->GetBalance())));
}
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("coinsupply", ValueFromAmount(GetTotalCoinSupply(nBestHeight,false))));
obj.push_back(Pair("timeoffset", (boost::int64_t)GetTimeOffset()));
obj.push_back(Pair("connections", (int)vNodes.size()));
obj.push_back(Pair("proxy", (proxy.first.IsValid() ? proxy.first.ToStringIPPort() : string())));
@@ -101,7 +108,7 @@ Value getnewaddress(const Array& params, bool fHelp)
if (fHelp || params.size() > 1)
throw runtime_error(
"getnewaddress [account]\n"
"Returns a new " + COIN_NAME_DISPLAY + " address for receiving payments. "
"Returns a new CasinoCoin address for receiving payments. "
"If [account] is specified (recommended), it is added to the address book "
"so payments received with the address will be credited to [account].");
@@ -145,10 +152,8 @@ CBitcoinAddress GetAccountAddress(string strAccount, bool bForceNew=false)
{
const CWalletTx& wtx = (*it).second;
BOOST_FOREACH(const CTxOut& txout, wtx.vout)
{
if (txout.scriptPubKey == scriptPubKey)
bKeyUsed = true;
}
}
}
@@ -170,7 +175,7 @@ Value getaccountaddress(const Array& params, bool fHelp)
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccountaddress <account>\n"
"Returns the current " + COIN_NAME_DISPLAY + " address for receiving payments to this account.");
"Returns the current CasinoCoin address for receiving payments to this account.");
// Parse the account first so we don't generate a key if there's an error
string strAccount = AccountFromValue(params[0]);
@@ -188,12 +193,12 @@ Value setaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"setaccount <" + COIN_NAME + "address> <account>\n"
"setaccount <casinocoinaddress> <account>\n"
"Sets the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid " + COIN_NAME_DISPLAY + " address");
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CasinoCoin address");
string strAccount;
@@ -218,12 +223,12 @@ Value getaccount(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getaccount <" + COIN_NAME + "address>\n"
"getaccount <casinocoinaddress>\n"
"Returns the account associated with the given address.");
CBitcoinAddress address(params[0].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid " + COIN_NAME_DISPLAY + " address");
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CasinoCoin address");
string strAccount;
map<CTxDestination, string>::iterator mi = pwalletMain->mapAddressBook.find(address.Get());
@@ -276,13 +281,13 @@ Value sendtoaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 2 || params.size() > 4)
throw runtime_error(
"sendtoaddress <"+ COIN_NAME + "address> <amount> [comment] [comment-to]\n"
"sendtoaddress <casinocoinaddress> <amount> [comment] [comment-to]\n"
"<amount> 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 "+ COIN_NAME_DISPLAY + " address");
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CasinoCoin address");
// Amount
int64 nAmount = AmountFromValue(params[1]);
@@ -339,7 +344,7 @@ Value signmessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 2)
throw runtime_error(
"signmessage <"+ COIN_NAME + "address> <message>\n"
"signmessage <casinocoinaddress> <message>\n"
"Sign a message with the private key of an address");
EnsureWalletIsUnlocked();
@@ -374,7 +379,7 @@ Value verifymessage(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 3)
throw runtime_error(
"verifymessage <" + COIN_NAME + "address> <signature> <message>\n"
"verifymessage <casinocoinaddress> <signature> <message>\n"
"Verify a signed message");
string strAddress = params[0].get_str();
@@ -411,14 +416,14 @@ Value getreceivedbyaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"getreceivedbyaddress <" + COIN_NAME + "address> [minconf=1]\n"
"Returns the total amount received by <" + COIN_NAME + "address> in transactions with at least [minconf] confirmations.");
"getreceivedbyaddress <casinocoinaddress> [minconf=1]\n"
"Returns the total amount received by <casinocoinaddress> in transactions with at least [minconf] confirmations.");
// Bitcoin address
CBitcoinAddress address = CBitcoinAddress(params[0].get_str());
CScript scriptPubKey;
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid " + COIN_NAME_DISPLAY + " address");
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CasinoCoin address");
scriptPubKey.SetDestination(address.Get());
if (!IsMine(*pwalletMain,scriptPubKey))
return (double)0.0;
@@ -632,14 +637,14 @@ Value sendfrom(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 3 || params.size() > 6)
throw runtime_error(
"sendfrom <fromaccount> <to"+ COIN_NAME + "address> <amount> [minconf=1] [comment] [comment-to]\n"
"sendfrom <fromaccount> <tocasinocoinaddress> <amount> [minconf=1] [comment] [comment-to]\n"
"<amount> is a real and is rounded to the nearest 0.00000001"
+ HelpRequiringPassphrase());
string strAccount = AccountFromValue(params[0]);
CBitcoinAddress address(params[1].get_str());
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid " + COIN_NAME_DISPLAY + " address");
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, "Invalid CasinoCoin address");
int64 nAmount = AmountFromValue(params[2]);
int nMinDepth = 1;
if (params.size() > 3)
@@ -695,7 +700,7 @@ Value sendmany(const Array& params, bool fHelp)
{
CBitcoinAddress address(s.name_);
if (!address.IsValid())
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid " + COIN_NAME_DISPLAY + " address: ")+s.name_);
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, string("Invalid CasinoCoin address: ")+s.name_);
if (setAddress.count(address))
throw JSONRPCError(RPC_INVALID_PARAMETER, string("Invalid parameter, duplicated address: ")+s.name_);
@@ -743,7 +748,7 @@ static CScript _createmultisig(const Array& params)
if ((int)keys.size() < nRequired)
throw runtime_error(
strprintf("not enough keys supplied "
"(got %" PRIszu " keys, but need at least %d to redeem)", keys.size(), nRequired));
"(got %"PRIszu" keys, but need at least %d to redeem)", keys.size(), nRequired));
std::vector<CPubKey> pubkeys;
pubkeys.resize(keys.size());
for (unsigned int i = 0; i < keys.size(); i++)
@@ -791,7 +796,7 @@ Value addmultisigaddress(const Array& params, bool fHelp)
{
string msg = "addmultisigaddress <nrequired> <'[\"key\",\"key\"]'> [account]\n"
"Add a nrequired-to-sign multisignature address to the wallet\"\n"
"each key is a " + COIN_NAME_DISPLAY + " address or hex-encoded public key\n"
"each key is a CasinoCoin address or hex-encoded public key\n"
"If [account] is specified, assign address to [account].";
throw runtime_error(msg);
}
@@ -816,7 +821,7 @@ Value createmultisig(const Array& params, bool fHelp)
string msg = "createmultisig <nrequired> <'[\"key\",\"key\"]'>\n"
"Creates a multi-signature address and returns a json object\n"
"with keys:\n"
"address : " + COIN_NAME + " address\n"
"address : casinocoin address\n"
"redeemScript : hex-encoded redemption script";
throw runtime_error(msg);
}
@@ -1471,7 +1476,7 @@ Value encryptwallet(const Array& params, bool fHelp)
// slack space in .dat files; that is bad if the old data is
// unencrypted private keys. So:
StartShutdown();
return "wallet encrypted; " + COIN_NAME_DISPLAY + " server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
return "wallet encrypted; CasinoCoin server stopping, restart to run with encrypted wallet. The keypool has been flushed, you need to make a new backup.";
}
class DescribeAddressVisitor : public boost::static_visitor<Object>
@@ -1513,8 +1518,8 @@ Value validateaddress(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"validateaddress <"+ COIN_NAME + "address>\n"
"Return information about <"+ COIN_NAME + "address>.");
"validateaddress <casinocoinaddress>\n"
"Return information about <casinocoinaddress>.");
CBitcoinAddress address(params[0].get_str());
bool isValid = address.IsValid();
@@ -1628,3 +1633,209 @@ Value getcoinsupply(const Array& params, bool fHelp)
int64 coinSupply = GetTotalCoinSupply(height,noCheckpoints);
return ValueFromAmount(coinSupply);
}
Value startwalletserversession(const Array &params, bool fHelp)
{
if(!fWalletServer)
throw runtime_error(
"The server is not started in Wallet Server mode so no session can be created");
if (fHelp || params.size() != 1)
throw runtime_error(
"startwalletserversession [accountid]\n"
"Starts a Wallet Server session and returns a session id.\n"
"Pass in the [accountid] which will be used in future wallet server requests for the created session.");
// get the account id
std::string accountId = params[0].get_str();
// check if accountId is not already in a session
if(walletServer.isNewAccountId(accountId))
{
// Create a session id
boost::uuids::uuid uuid = boost::uuids::random_generator()();
std::string sessionId = boost::lexical_cast<std::string>(uuid);
// create session object
Session wsSession = {accountId, sessionId, (int)time(NULL), false, 0};
// Notify the Wallet Server of the newsession
walletServer.NotifyStartNewWalletServerSession(accountId, wsSession);
Object ret;
ret.push_back(Pair("accountid", accountId));
ret.push_back(Pair("sessionid", sessionId));
return ret;
}
else
throw JSONRPCError(RPC_WALLETSERVER_INVALID_ID, "Given identifier is already in an active session");
}
Value listwalletserversessions(const Array &params, bool fHelp)
{
if(!fWalletServer)
throw runtime_error(
"The server is not started in Wallet Server mode so no sessions list available");
if (fHelp || params.size() > 0)
throw runtime_error(
"listwalletserversessions\n"
"Returns a list with current active walletserver sessions.");
// get the sessions
sessionKeyValueType &wsSessions = walletServer.getSessions();
// create the output object
Array ret;
BOOST_FOREACH( sessionKeyValueType::value_type &session, wsSessions )
{
Object o;
o.push_back(Pair("accountid", session.second.email));
o.push_back(Pair("sessionid", session.second.sessionId));
o.push_back(Pair("creationtime", session.second.creationTime));
o.push_back(Pair("walletopen", session.second.walletOpen));
o.push_back(Pair("lastcommandtime", session.second.lastCommandTime));
ret.push_back(o);
}
return ret;
}
Value stopwalletserversession(const Array &params, bool fHelp)
{
if(!fWalletServer)
throw runtime_error(
"The server is not started in Wallet Server mode so no sessions list available");
if (fHelp || params.size() != 1)
throw runtime_error(
"stopwalletserversession [sessionid]\n"
"Removes a Wallet Server session and closes the wallet if open.\n"
"Pass in the [sessionid] of the session that has to be removed.");
// get the session id
std::string sessionId = params[0].get_str();
// remove session and return the result
Object ret;
ret.push_back(Pair("result", walletServer.deleteSession(sessionId)));
return ret;
}
Value listwallets(const Array &params, bool fHelp)
{
if(!fWalletServer)
throw runtime_error(
"The server is not started in Wallet Server mode so no wallet list available");
if (fHelp || params.size() > 0)
throw runtime_error(
"listwallets\n"
"Returns a list with wallets stored by the walletserver.");
// get the wallets
keyValueType wsWallets = walletServer.getWallets();
// create the output object
Array ret;
BOOST_FOREACH( keyValueType::value_type &wallet, wsWallets )
{
Object o;
o.push_back(Pair("walletid", wallet.first));
o.push_back(Pair("accountid", wallet.second));
ret.push_back(o);
}
return ret;
}
Value wsopenwallet(const Array &params, bool fHelp)
{
if(!fWalletServer)
throw runtime_error(
"The server is not started in Wallet Server mode so command is not available");
if (fHelp || params.size() != 3)
throw runtime_error(
"wsopenwallet [sessionid] [accountid] [walletid]\n"
"Open a wallet for a session. account and wallet id combination.");
// get the wallets
keyValueType wsWallets = walletServer.getWallets();
// create the output object
Array ret;
BOOST_FOREACH( keyValueType::value_type &wallet, wsWallets )
{
Object o;
o.push_back(Pair("walletid", wallet.first));
o.push_back(Pair("accountid", wallet.second));
ret.push_back(o);
}
return ret;
}
Value wsclosewallet(const Array &params, bool fHelp)
{
if(!fWalletServer)
throw runtime_error(
"The server is not started in Wallet Server mode so command is not available");
if (fHelp || params.size() != 3)
throw runtime_error(
"wsclosewallet [sessionid] [accountid] [walletid]\n"
"Open a wallet for a session. account and wallet id combination.");
// get the wallets
keyValueType wsWallets = walletServer.getWallets();
// create the output object
Array ret;
BOOST_FOREACH( keyValueType::value_type &wallet, wsWallets )
{
Object o;
o.push_back(Pair("walletid", wallet.first));
o.push_back(Pair("accountid", wallet.second));
ret.push_back(o);
}
return ret;
}
Value wsgetinfo(const Array &params, bool fHelp)
{
if(!fWalletServer)
throw runtime_error(
"The server is not started in Wallet Server mode so command is not available");
if (fHelp || params.size() != 3)
throw runtime_error(
"wsgetinfo [sessionid] [accountid] [walletid]\n"
"Get the Wallet Information for a given session. account and wallet id combination.");
Object obj;
obj.push_back(Pair("version", (int)CLIENT_VERSION));
obj.push_back(Pair("protocolversion",(int)PROTOCOL_VERSION));
return obj;
}
Value wsgetaddresslist(const Array &params, bool fHelp)
{
if(!fWalletServer)
throw runtime_error(
"The server is not started in Wallet Server mode so command is not available");
if (fHelp || params.size() != 3)
throw runtime_error(
"wsgetaddresslist [sessionid] [accountid] [walletid]\n"
"Open a wallet for a session. account and wallet id combination.");
// get the wallets
keyValueType wsWallets = walletServer.getWallets();
// create the output object
Array ret;
BOOST_FOREACH( keyValueType::value_type &wallet, wsWallets )
{
Object o;
o.push_back(Pair("walletid", wallet.first));
o.push_back(Pair("accountid", wallet.second));
ret.push_back(o);
}
return ret;
}
Value wssendtoaddress(const Array &params, bool fHelp)
{
if(!fWalletServer)
throw runtime_error(
"The server is not started in Wallet Server mode so command is not available");
if (fHelp || params.size() != 5)
throw runtime_error(
"wssendtoaddress [sessionid] [accountid] [walletid] [address] [amount]\n"
"Open a wallet for a session. account and wallet id combination.");
// get the wallets
keyValueType wsWallets = walletServer.getWallets();
// create the output object
Array ret;
BOOST_FOREACH( keyValueType::value_type &wallet, wsWallets )
{
Object o;
o.push_back(Pair("walletid", wallet.first));
o.push_back(Pair("accountid", wallet.second));
ret.push_back(o);
}
return ret;
}

601
src/stomp/booststomp.cpp Normal file
View File

@@ -0,0 +1,601 @@
/*
BoostStomp - a STOMP (Simple Text Oriented Messaging Protocol) client
----------------------------------------------------
Copyright (c) 2012 Elias Karakoulakis <elias.karakoulakis@gmail.com>
SOFTWARE NOTICE AND LICENSE
BoostStomp 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 3 of the License,
or (at your option) any later version.
BoostStomp 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 BoostStomp. If not, see <http://www.gnu.org/licenses/>.
for more information on the LGPL, see:
http://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License
*/
// based on the ASIO async TCP client example found on Boost documentation:
// http://www.boost.org/doc/libs/1_46_1/doc/html/boost_asio/example/timeouts/async_tcp_client.cpp
#include <iostream>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/asio/buffer.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/format.hpp>
#include <boost/thread.hpp>
#include "booststomp.h"
#include "main.h"
namespace STOMP {
using namespace std;
using namespace boost;
using namespace boost::asio;
using boost::asio::ip::tcp;
// used by debug_print
boost::mutex global_stream_lock;
// ----------------------------
// constructor
// ----------------------------
BoostStomp::BoostStomp(string& hostname, int& port, AckMode ackmode /*= ACK_AUTO*/):
// ----------------------------
// protected members setup
//m_sendqueue (new std::queue<Frame*>()),
//m_sendqueue_mutex (new boost::mutex()),
m_hostname (hostname),
m_port (port),
m_ackmode (ackmode),
m_stopped (true),
m_connected (false),
m_io_service (new io_service()),
m_io_service_work (new io_service::work(*m_io_service)),
m_strand (new io_service::strand(*m_io_service)),
m_socket (new tcp::socket(*m_io_service)),
// private members
m_protocol_version("1.0"),
m_transaction_id(0)
// ----------------------------
{
// map STOMP server commands to handler methods
cmd_map["CONNECTED"] = &BoostStomp::process_CONNECTED;
cmd_map["MESSAGE"] = &BoostStomp::process_MESSAGE;
cmd_map["RECEIPT"] = &BoostStomp::process_RECEIPT;
cmd_map["ERROR"] = &BoostStomp::process_ERROR;
// set default debug flag
m_showDebug = false;
}
// ----------------------------
// destructor
// ----------------------------
BoostStomp::~BoostStomp()
// ----------------------------
{
// first stop io_service so as to exit the run loop (when idle)
m_io_service->stop();
// then interrupt the worker thread
worker_thread->interrupt();
// delete m_heartbeat_timer; // no need, its a shared_ptr
delete worker_thread;
}
// ----------------------------
// worker thread
// ----------------------------
void BoostStomp::worker( boost::shared_ptr< boost::asio::io_service > _io_service )
{
debug_print("Worker thread: starting...");
while(!m_stopped) {
_io_service->run();
debug_print("Worker thread: io_service is stopped...");
_io_service->reset();
boost::this_thread::sleep_for( boost::chrono::seconds(1));
}
debug_print("Worker thread finished.");
}
// ----------------------------
// ASIO HANDLERS (protected)
// ----------------------------
// Called by the user of the client class to initiate the connection process.
// The endpoint iterator will have been obtained using a tcp::resolver.
void BoostStomp::start(string& login, string& passcode)
{
debug_print("starting...");
m_stopped = false;
tcp::resolver resolver(*m_io_service);
tcp::resolver::iterator endpoint_iter = resolver.resolve(tcp::resolver::query(
m_hostname,
to_string<int>(m_port, std::dec),
boost::asio::ip::resolver_query_base::numeric_service)
);
// Start the connect actor.
start_connect(endpoint_iter, login, passcode);
}
void BoostStomp::start()
{
std::string empty = "";
start(empty, empty);
}
// This function terminates all the actors to shut down the connection. It
// may be called by the user of the client class, or by the class itself in
// response to graceful termination or an unrecoverable error.
void BoostStomp::stop()
{
debug_print("stopping...");
if (m_connected && m_socket->is_open()) {
Frame frame( "DISCONNECT");
frame.encode(stomp_request);
debug_print("Sending DISCONNECT frame...");
boost::asio::write(*m_socket, stomp_request);
}
m_connected = false;
m_stopped = true;
if (m_heartbeat_timer != NULL) {
m_heartbeat_timer->cancel();
}
//
m_socket->close();
//
}
//
// --------------------------------------------------
// ---------- TCP CONNECTION SETUP ------------------
// --------------------------------------------------
// --------------------------------------------------
void BoostStomp::start_connect(tcp::resolver::iterator endpoint_iter, string& login, string& passcode)
// --------------------------------------------------
{
if (endpoint_iter != tcp::resolver::iterator())
{
debug_print(boost::format("STOMP: Connecting to %1%...") % endpoint_iter->endpoint() );
// Try TCP connection synchronously (the first frame to send is the CONNECT frame)
boost::system::error_code ec;
m_socket->connect(endpoint_iter->endpoint(), ec);
if (!ec) {
// now we are connected to STOMP server's TCP port/
debug_print(boost::format("STOMP TCP connection to %1% is active") % endpoint_iter->endpoint() );
// Send the CONNECT request synchronously (immediately).
hdrmap headers;
headers["accept-version"] = "1.1";
headers["host"] = m_hostname;
if (!login.empty()) {
headers["login"] = login;
headers["passcode"] = passcode;
}
Frame frame( "CONNECT", headers );
frame.encode(stomp_request);
debug_print("Sending CONNECT frame...");
boost::asio::write(*m_socket, stomp_request);
// start the read actor so as to receive the CONNECTED frame
start_stomp_read_headers();
// start worker thread (m_io_service.run())
worker_thread = new boost::thread( boost::bind( &BoostStomp::worker, this, m_io_service ) );
} else {
// We need to close the socket used in the previous connection attempt
// before starting a new one.
m_socket->close();
// Try the next available endpoint.
start_connect(++endpoint_iter, login, passcode);
}
}
else
{
// There are no more endpoints to try.
stop();
debug_print("Connection unsuccessful. Sleeping, then retrying...");
boost::this_thread::sleep_for( boost::chrono::seconds(3));
start();
}
}
// -----------------------------------------------
// ---------- INPUT ACTOR SETUP ------------------
// -----------------------------------------------
// -----------------------------------------------
void BoostStomp::start_stomp_read_headers()
// -----------------------------------------------
{
debug_print("start_stomp_read_headers");
// Start an asynchronous operation to read at least the STOMP frame command & headers (till the double newline delimiter)
boost::asio::async_read_until(
*m_socket,
stomp_response,
"\n\n",
boost::bind(&BoostStomp::handle_stomp_read_headers, this, placeholders::error()));
}
// -----------------------------------------------
void BoostStomp::handle_stomp_read_headers(const boost::system::error_code& ec)
// -----------------------------------------------
{
if (m_stopped)
return;
if (!ec)
{
std::size_t bodysize = 0;
try {
debug_print("handle_stomp_read_headers");
m_rcvd_frame = new Frame(stomp_response, cmd_map); // freed by consume_frame
hdrmap& _headers = m_rcvd_frame->headers();
// if the frame headers contain 'content-length', use that to call the proper async_read overload
if (_headers.find("content-length") != _headers.end()) {
string& content_length = _headers["content-length"];
debug_print(boost::format("received response (command+headers: %1% bytes, content-length: %2%)") % stomp_response.size() % content_length );
bodysize = lexical_cast<size_t>(content_length);
}
start_stomp_read_body(bodysize);
} catch(NoMoreFrames&) {
debug_print("No more frames!");
// break;
} catch(std::exception& e) {
debug_print(boost::format("handle_stomp_read in loop: unknown exception in Frame constructor:\n%1%") % e.what());
exit(10);
}
}
else
{
std::cerr << "BoostStomp: Error on receive: " << ec.message() << "\n";
stop();
start();
}
}
// -----------------------------------------------
void BoostStomp::start_stomp_read_body(std::size_t bodysize)
// -----------------------------------------------
{
debug_print("start_stomp_read_body");
// Start an asynchronous operation to read at least the STOMP frame body
if (bodysize == 0) {
boost::asio::async_read_until(
*m_socket, stomp_response,
'\0', // NULL signifies the end of the body
boost::bind(&BoostStomp::handle_stomp_read_body, this, placeholders::error(), placeholders::bytes_transferred()));
} else {
boost::asio::async_read(
*m_socket, stomp_response,
boost::asio::transfer_at_least(bodysize),
boost::bind(&BoostStomp::handle_stomp_read_body, this, placeholders::error(), placeholders::bytes_transferred()));
}
}
// -----------------------------------------------
void BoostStomp::handle_stomp_read_body(const boost::system::error_code& ec, std::size_t bytes_transferred = 0)
// -----------------------------------------------
{
if (m_stopped)
return;
if (!ec)
{
debug_print(boost::format("received response (%1% bytes) (buffer: %2% bytes)") % bytes_transferred % stomp_response.size() );
if (m_rcvd_frame != NULL) {
m_rcvd_frame->parse_body(stomp_response);
consume_received_frame();
}
//
//debug_print("stomp_response contents after Frame scanning:");
//hexdump(stomp_response);
// wait for the next incoming frame from the server...
start_stomp_read_headers();
}
else
{
std::cerr << "BoostStomp: Error on receive: " << ec.message() << "\n";
stop();
start();
}
}
// ------------------------------------------
void BoostStomp::consume_received_frame()
// ------------------------------------------
{
if (m_rcvd_frame != NULL) {
// is there a declared handler for the command in the received STOMP frame?
if (pfnStompCommandHandler_t handler = cmd_map[m_rcvd_frame->command()]) {
debug_print(boost::format("-- consume_frame: calling %1% command handler") % m_rcvd_frame->command());
// call STOMP command handler
(this->*handler)();
}
delete m_rcvd_frame;
}
m_rcvd_frame = NULL;
};
// ------------------------------------------------
// ---------- OUTPUT ACTOR SETUP ------------------
// ------------------------------------------------
// -----------------------------------------------
void BoostStomp::start_stomp_write()
// -----------------------------------------------
{
if ((m_stopped) || (!m_connected))
return;
//debug_print("start_stomp_write");
Frame* frame = NULL;
// send all STOMP frames in queue
while (m_sendqueue.try_pop(frame)) {
debug_print(boost::format("Sending %1% frame...") % frame->command() );
frame->encode(stomp_request);
try {
boost::asio::write(
*m_socket,
stomp_request
);
debug_print("Sent!");
delete frame;
} catch (boost::system::system_error& err){
m_connected = false;
debug_print(boost::format("Error writing to STOMP server: error code:%1%, message:%2%") % err.code() % err.what());
// put! the kot! down! slowly!
if(err.code().value() != 10009)
m_sendqueue.push(frame);
stop();
}
};
}
// -----------------------------------------------
void BoostStomp::start_stomp_heartbeat()
// -----------------------------------------------
{
// Start an asynchronous operation to send a heartbeat message.
//debug_print("Sending heartbeat...");
boost::asio::async_write(
*m_socket,
m_heartbeat,
boost::bind(&BoostStomp::handle_stomp_heartbeat, this, _1)
);
}
// -----------------------------------------------
void BoostStomp::handle_stomp_heartbeat(const boost::system::error_code& ec)
// -----------------------------------------------
{
if (m_stopped)
return;
if (!ec)
{
// Wait 10 seconds before sending the next heartbeat.
m_heartbeat_timer->expires_from_now(boost::posix_time::seconds(10));
m_heartbeat_timer->async_wait(
boost::bind(
&BoostStomp::start_stomp_heartbeat,
this
)
);
}
else
{
std::cout << "Error on sending heartbeat: " << ec.message() << "\n";
stop();
}
}
//-----------------------------------------
void BoostStomp::process_CONNECTED()
//-----------------------------------------
{
m_connected = true;
// try to get supported protocol version from headers
hdrmap _headers = m_rcvd_frame->headers();
if (_headers.find("version") != _headers.end()) {
m_protocol_version = _headers["version"];
debug_print(boost::format("server supports STOMP version %1%") % m_protocol_version);
}
if (m_protocol_version == "1.1") {
// we are connected to a version 1.1 STOMP server, setup heartbeat
m_heartbeat_timer = boost::shared_ptr< deadline_timer> ( new deadline_timer( *m_io_service ));
std::ostream os( &m_heartbeat);
os << "\n";
// we can start the heartbeat actor
start_stomp_heartbeat();
}
// in case of reconnection, we need to re-subscribe to all subscriptions
for (subscription_map::iterator it = m_subscriptions.begin(); it != m_subscriptions.end(); it++) {
//string topic = (*it).first;
do_subscribe((*it).first);
};
}
//-----------------------------------------
void BoostStomp::process_MESSAGE()
//-----------------------------------------
{
bool acked = true;
hdrmap& _headers = m_rcvd_frame->headers();
if (_headers.find("destination") != _headers.end()) {
string& dest = _headers["destination"];
//
if (pfnOnStompMessage_t callback_function = m_subscriptions[dest]) {
//debug_print(boost::format("-- consume_frame: firing callback for %1%") % dest);
//
acked = callback_function(m_rcvd_frame);
};
};
// acknowledge frame, if in "Client" or "Client-Individual" ack mode
if ((m_ackmode == ACK_CLIENT) || (m_ackmode == ACK_CLIENT_INDIVIDUAL)) {
acknowledge(m_rcvd_frame, acked);
}
}
//-----------------------------------------
void BoostStomp::process_RECEIPT()
//-----------------------------------------
{
hdrmap& _headers = m_rcvd_frame->headers();
if (_headers.find("receipt_id") != _headers.end()) {
string& receipt_id = _headers["receipt_id"];
// do something with receipt...
debug_print(boost::format("receipt-id == %1%") % receipt_id);
};
}
//-----------------------------------------
void BoostStomp::process_ERROR()
//-----------------------------------------
{
hdrmap& _headers = m_rcvd_frame->headers();
string errormessage = (_headers.find("message") != _headers.end()) ?
_headers["message"] :
"(unknown error!)";
errormessage += m_rcvd_frame->body().c_str();
//throw(errormessage);
cerr << endl << "============= BoostStomp got an ERROR frame from server: =================" << endl << errormessage << endl;
}
//-----------------------------------------
bool BoostStomp::send_frame( Frame* frame )
//-----------------------------------------
{
// send_frame is called from the application thread. Do not dereference frame here!!! (shared data)
//debug_print(boost::format("send_frame: Adding frame to send queue...") % frame->command() );
//debug_print("send_frame: Adding frame to send queue...");
m_sendqueue.push(frame); // concurrent_queue does all the thread safety stuff
// tell io_service to start the output actor so as the frame get sent from the worker thread
m_strand->post(
boost::bind(&BoostStomp::start_stomp_write, this)
);
return(true);
}
// ---------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------
// ------------------------ PUBLIC INTERFACE ------------------------
// ---------------------------------------------------------------------------------------
// ---------------------------------------------------------------------------------------
// ------------------------------------------
bool BoostStomp::subscribe( string& topic, pfnOnStompMessage_t callback )
// ------------------------------------------
{
debug_print(boost::format("Setting callback function for %1%") % topic);
m_subscriptions[topic] = callback;
return(do_subscribe(topic));
}
// ------------------------------------------
bool BoostStomp::do_subscribe(const string& topic)
// ------------------------------------------
{
hdrmap hm;
hm["id"] = lexical_cast<string>(boost::this_thread::get_id());
hm["destination"] = topic;
return(send_frame(new Frame( "SUBSCRIBE", hm )));
}
// ------------------------------------------
bool BoostStomp::unsubscribe( string& topic )
// ------------------------------------------
{
hdrmap hm;
hm["destination"] = topic;
m_subscriptions.erase(topic);
return(send_frame(new Frame( "UNSUBSCRIBE", hm )));
}
// ------------------------------------------
bool BoostStomp::acknowledge(Frame* frame, bool acked = true)
// ------------------------------------------
{
hdrmap hm = frame->headers();
string _ack_cmd = (acked ? "ACK" : "NACK");
return(send_frame(new Frame( _ack_cmd, hm )));
}
// ------------------------------------------
int BoostStomp::begin()
// ------------------------------------------
// returns a new transaction id
{
hdrmap hm;
// create a new transaction id
hm["transaction"] = lexical_cast<string>(m_transaction_id++);
Frame* frame = new Frame( "BEGIN", hm );
send_frame(frame);
return(m_transaction_id);
};
// ------------------------------------------
bool BoostStomp::commit(int transaction_id)
// ------------------------------------------
{
hdrmap hm;
// add required header
hm["transaction"] = lexical_cast<string>(transaction_id);
return(send_frame(new Frame( "COMMIT", hm )));
};
// ------------------------------------------
bool BoostStomp::abort(int transaction_id)
// ------------------------------------------
{
hdrmap hm;
// add required header
hm["transaction"] = lexical_cast<string>(transaction_id);
return(send_frame(new Frame( "ABORT", hm )));
};
// ------------------------------------------
void BoostStomp::enable_debug_msgs(bool b)
// ------------------------------------------
{
m_showDebug = b;
}
void BoostStomp::debug_print(string& str) {
boost::format fmt = boost::format(str.c_str());
debug_print(fmt);
}
void BoostStomp::debug_print(const char* cstr) {
boost::format fmt = boost::format(cstr);
BoostStomp::debug_print(fmt);
}
void BoostStomp::debug_print(boost::format& fmt) {
using namespace boost::posix_time;
if (m_showDebug) {
ptime now = second_clock::universal_time();
global_stream_lock.lock();
printf("[%s: %s] BoostStomp: %s\n", FormatTime(now).c_str(), boost::lexical_cast<std::string>(boost::this_thread::get_id()).c_str(), fmt.str().c_str());
global_stream_lock.unlock();
}
}
} // end namespace STOMP

181
src/stomp/booststomp.h Normal file
View File

@@ -0,0 +1,181 @@
/*
BoostStomp - a STOMP (Simple Text Oriented Messaging Protocol) client using BOOST (http://www.boost.org)
----------------------------------------------------
Copyright (c) 2012 Elias Karakoulakis <elias.karakoulakis@gmail.com>
SOFTWARE NOTICE AND LICENSE
BoostStomp 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 3 of the License,
or (at your option) any later version.
Thrift4OZW 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 BoostStomp. If not, see <http://www.gnu.org/licenses/>.
for more information on the LGPL, see:
http://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License
*/
// booststomp.h
//
#ifndef __BOOSTSTOMP_H_
#define __BOOSTSTOMP_H_
#include <string>
#include <sstream>
#include <iostream>
//#include <queue>
#include <map>
#include <set>
#include <boost/asio.hpp>
#include <boost/asio/deadline_timer.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include "stompframe.h"
#include "helpers.h"
namespace STOMP {
using namespace boost;
using namespace boost::asio;
using namespace boost::asio::ip;
// ACK mode
typedef enum {
ACK_AUTO=0, // implicit acknowledgment (no ACK is sent)
ACK_CLIENT, // explicit acknowledgment (must ACK)
ACK_CLIENT_INDIVIDUAL //
} AckMode;
// Stomp message callback function prototype
typedef bool (*pfnOnStompMessage_t)( Frame* );
// Stomp subscription map (topic => callback)
typedef std::map<std::string, pfnOnStompMessage_t> subscription_map;
// here we go
// -------------
class BoostStomp
// -------------
{
//----------------
protected:
//----------------
Frame* m_rcvd_frame;
//boost::shared_ptr< std::queue<Frame*> > m_sendqueue;
//boost::shared_ptr< boost::mutex > m_sendqueue_mutex;
concurrent_queue<Frame*> m_sendqueue;
subscription_map m_subscriptions;
//
std::string m_hostname;
int m_port;
AckMode m_ackmode;
//
bool m_stopped;
bool m_connected; // have we completed application-level STOMP connection?
boost::shared_ptr< io_service > m_io_service;
boost::shared_ptr< io_service::work > m_io_service_work;
boost::shared_ptr< io_service::strand> m_strand;
tcp::socket* m_socket;
boost::asio::streambuf stomp_request, stomp_response;
//----------------
private:
//----------------
boost::mutex stream_mutex;
boost::thread* worker_thread;
boost::shared_ptr<deadline_timer> m_heartbeat_timer;
boost::asio::streambuf m_heartbeat;
string m_protocol_version;
int m_transaction_id;
bool m_showDebug;
//
bool send_frame( Frame* _frame );
bool do_subscribe (const string& topic);
//
void consume_received_frame();
void process_CONNECTED();
void process_MESSAGE();
void process_RECEIPT();
void process_ERROR();
void start_connect(tcp::resolver::iterator endpoint_iter, string& login, string& passcode);
void handle_connect(const boost::system::error_code& ec, tcp::resolver::iterator endpoint_iter);
//TODO: void setup_stomp_heartbeat(int cx, int cy);
void start_stomp_heartbeat();
void handle_stomp_heartbeat(const boost::system::error_code& ec);
void start_stomp_read_headers();
void handle_stomp_read_headers(const boost::system::error_code& ec);
void start_stomp_read_body(std::size_t);
void handle_stomp_read_body(const boost::system::error_code& ec, std::size_t bytes_transferred);
void start_stomp_write();
//void handle_stomp_write(const boost::system::error_code& ec);
void worker( boost::shared_ptr< boost::asio::io_service > io_service );
void debug_print(boost::format& fmt);
void debug_print(string& str);
void debug_print(const char* str);
//----------------
public:
//----------------
// constructor
BoostStomp(string& hostname, int& port, AckMode ackmode = ACK_AUTO);
// destructor
~BoostStomp();
stomp_server_command_map_t cmd_map;
void start();
void start(string& login, string& passcode);
void stop();
// Set or clear the debug flag
void enable_debug_msgs(bool b);
// thread-safe methods called from outside the thread loop
template <typename BodyType>
bool send ( std::string& _topic, hdrmap _headers, BodyType& _body, pfnOnStompMessage_t callback = NULL) {
_headers["destination"] = _topic;
Frame* frame = new Frame( "SEND", _headers, _body );
return(send_frame(frame));
}
//bool send ( std::string& topic, hdrmap _headers, std::string& body );
//
bool subscribe ( std::string& topic, pfnOnStompMessage_t callback );
bool unsubscribe ( std::string& topic );
bool acknowledge ( Frame* _frame, bool acked );
// STOMP transactions
int begin(); // returns a new transaction id
bool commit(int transaction_id);
bool abort(int transaction_id);
//
AckMode get_ackmode() { return m_ackmode; };
//
}; //class
}
#endif

45
src/stomp/helpers.cpp Normal file
View File

@@ -0,0 +1,45 @@
/*
* helpers.cpp
*
* Created on: 22 Απρ 2012
* Author: ekarak
*/
#include "helpers.h"
#include <iostream>
void hexdump(const void *ptr, int buflen) {
unsigned char *buf = (unsigned char*)ptr;
int i, j;
for (i=0; i<buflen; i+=16) {
printf("%06x: ", i);
for (j=0; j<16; j++)
if (i+j < buflen)
printf("%02x ", buf[i+j]);
else
printf(" ");
printf(" ");
for (j=0; j<16; j++)
if (i+j < buflen)
printf("%c", isprint(buf[i+j]) ? buf[i+j] : '.');
printf("\n");
}
}
void hexdump(boost::asio::streambuf& sb) {
const char* rawdata = boost::asio::buffer_cast<const char*>(sb.data());
hexdump(rawdata, sb.size());
}
std::string FormatTime(boost::posix_time::ptime& now)
{
using namespace boost::posix_time;
static std::locale loc(std::wcout.getloc(),
new time_facet("%H:%M:%S"));
std::basic_stringstream<char> ss;
ss.imbue(loc);
ss << now;
return ss.str();
}

91
src/stomp/helpers.h Normal file
View File

@@ -0,0 +1,91 @@
/*
* helpers.h
*
* Created on: 22 Απρ 2012
* Author: ekarak
*/
#ifndef HELPERS_H_
#define HELPERS_H_
#include <boost/asio.hpp>
#include <boost/format.hpp>
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <string>
#include <queue>
using namespace std;
// helper function
void hexdump(boost::asio::streambuf&);
void hexdump(const void *ptr, int buflen);
std::string FormatTime(boost::posix_time::ptime&);
// helper template function for pretty-printing just about anything
template <class T>
std::string to_string(T t, std::ios_base & (*f)(std::ios_base&))
{
std::ostringstream oss;
oss.setf (std::ios_base::showbase);
oss << f << t;
return oss.str();
}
// -------------------------------
// Concurrent queue, courtesy of:
// http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html
// -------------------------------
template<typename Data>
class concurrent_queue
{
private:
std::queue<Data> the_queue;
mutable boost::mutex the_mutex;
boost::condition_variable the_condition_variable;
public:
void push(Data const& data)
{
boost::mutex::scoped_lock lock(the_mutex);
the_queue.push(data);
lock.unlock();
the_condition_variable.notify_one();
}
bool empty() const
{
boost::mutex::scoped_lock lock(the_mutex);
return the_queue.empty();
}
bool try_pop(Data& popped_value)
{
boost::mutex::scoped_lock lock(the_mutex);
if(the_queue.empty())
{
return false;
}
popped_value=the_queue.front();
the_queue.pop();
return true;
}
void wait_and_pop(Data& popped_value)
{
boost::mutex::scoped_lock lock(the_mutex);
while(the_queue.empty())
{
the_condition_variable.wait(lock);
}
popped_value=the_queue.front();
the_queue.pop();
}
};
#endif /* HELPERS_H_ */

196
src/stomp/stompframe.cpp Normal file
View File

@@ -0,0 +1,196 @@
/*
BoostStomp - a STOMP (Simple Text Oriented Messaging Protocol) client
----------------------------------------------------
Copyright (c) 2012 Elias Karakoulakis <elias.karakoulakis@gmail.com>
SOFTWARE NOTICE AND LICENSE
BoostStomp 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 3 of the License,
or (at your option) any later version.
BoostStomp 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 BoostStomp. If not, see <http://www.gnu.org/licenses/>.
for more information on the LGPL, see:
http://en.wikipedia.org/wiki/GNU_Lesser_General_Public_License
*/
#include <boost/format.hpp>
#include <boost/lexical_cast.hpp>
#include "booststomp.h"
#include "helpers.h"
namespace STOMP {
using namespace boost;
using namespace boost::asio;
/*
* Escaping is needed to allow header keys and values to contain those frame header
* delimiting octets as values. The CONNECT and CONNECTED frames do not escape the
* colon or newline octets in order to remain backward compatible with STOMP 1.0.
* C style string literal escapes are used to encode any colons and newlines that
* are found within the UTF-8 encoded headers. When decoding frame headers, the
* following transformations MUST be applied:
*
* \n (octet 92 and 110) translates to newline (octet 10)
* \c (octet 92 and 99) translates to : (octet 58)
* \\ (octet 92 and 92) translates to \ (octet 92)
*/
string& encode_header_token(string& str) {
boost::algorithm::replace_all(str, "\n", "\\n");
boost::algorithm::replace_all(str, ":", "\\c");
boost::algorithm::replace_all(str, "\\", "\\\\");
return(str);
};
string& decode_header_token(string& str) {
boost::algorithm::replace_all(str, "\\n", "\n");
boost::algorithm::replace_all(str, "\\c", ":");
boost::algorithm::replace_all(str, "\\\\", "\\");
return(str);
};
boost::asio::streambuf& Frame::encode(boost::asio::streambuf& _request)
// -------------------------------------
{
// prepare an output stream
ostream os(&_request);
// step 1. write the command
if (m_command.length() > 0) {
os << m_command << "\n";
} else {
throw("stomp_write: command not set!!");
}
// step 2. Write the headers (key-value pairs)
if( m_headers.size() > 0 ) {
for ( hdrmap::iterator it = m_headers.begin() ; it != m_headers.end(); it++ ) {
string key = (*it).first;
string val = (*it).second;
os << encode_header_token(key)
<< ":"
<< encode_header_token(val)
<< "\n";
}
}
// special header: content-length
if( m_body.v.size() > 0 ) {
os << "content-length:" << m_body.v.size() << "\n";
}
// write newline signifying end of headers
os << "\n";
// step 3. Write the body
if( m_body.v.size() > 0 ) {
_request.sputn(m_body.v.data(), m_body.v.size());
//_request.commit(m_body.v.size());
}
// write terminating NULL char
_request.sputc('\0');
//_request.commit(1);
return(_request);
};
// my own version of getline for an asio streambuf
inline void mygetline (boost::asio::streambuf& sb, string& _str, char delim = '\n') {
const char* line = boost::asio::buffer_cast<const char*>(sb.data());
char _c;
size_t i;
_str.clear();
for( i = 0;
((i < sb.size()) && ((_c = line[i]) != delim));
i++
) _str += _c;
//debug_print( boost::format("mygetline: i=%1%, sb.size()==%2%") % i % sb.size() );
//hexdump(_str.c_str(), _str.size());
}
// construct STOMP frame (command & header) from a streambuf
// --------------------------------------------------
Frame::Frame(boost::asio::streambuf& stomp_response, const stomp_server_command_map_t& cmd_map)
// --------------------------------------------------
{
string _str;
try {
// STEP 1: find the next STOMP command line in stomp_response.
// Chomp unknown lines till the buffer is empty, in which case an exception is raised
//debug_print(boost::format("Frame parser phase 1, stomp_response.size()==%1%") % stomp_response.size());
//hexdump(boost::asio::buffer_cast<const char*>(stomp_response.data()), stomp_response.size());
while (stomp_response.size() > 0) {
mygetline(stomp_response, _str);
//hexdump(_str.c_str(), _str.length());
stomp_response.consume(_str.size() + 1); // plus one for the newline
if (cmd_map.find(_str) != cmd_map.end()) {
//debug_print(boost::format("phase 1: COMMAND==%1%, sb.size==%2%") % _str % stomp_response.size());
m_command = _str;
break;
}
}
// if after all this trouble m_command is not set, and there's no more data in stomp_response
// (which shouldn't happen since we do async_read_until the double newline), then throw an exception
if (m_command == "") throw(NoMoreFrames());
// STEP 2: parse all headers
//debug_print("Frame parser phase 2");
vector< string > header_parts;
while (stomp_response.size() > 0) {
mygetline(stomp_response, _str);
stomp_response.consume(_str.size()+1);
boost::algorithm::split(header_parts, _str, is_any_of(":"));
if (header_parts.size() > 1) {
string& key = decode_header_token(header_parts[0]);
string& val = decode_header_token(header_parts[1]);
//debug_print(boost::format("phase 2: HEADER[%1%]==%2%") % key % val);
m_headers[key] = val;
//
} else {
// no valid header line detected, on to the body scanner
break;
}
}
//
} catch(NoMoreFrames& e) {
//debug_print("-- Frame parser ended (no more frames)");
throw(e);
}
};
// STEP 3: parse the body
size_t Frame::parse_body(boost::asio::streambuf& _response)
{
std::size_t _content_length = 0, bytecount = 0;
string _str;
//debug_print("Frame parser phase 3");
// special case: content-length
if (m_headers.find("content-length") != m_headers.end()) {
string& val = m_headers["content-length"];
//debug_print(boost::format("phase 3: body content-length==%1%") % val);
_content_length = lexical_cast<size_t>(val);
}
if (_content_length > 0) {
bytecount += _content_length;
// read back the body byte by byte
const char* rawdata = boost::asio::buffer_cast<const char*>(_response.data());
for (size_t i = 0; i < _content_length; i++ ) {
m_body << rawdata[i];
}
} else {
// read all bytes until the first NULL
mygetline(_response, _str, '\0');
bytecount += _str.size();
m_body << _str;
}
bytecount += 1; // for the final frame-terminating NULL
//debug_print(boost::format("phase 3: consumed %1% bytes, BODY(%2% bytes)==%3%") % bytecount % _str.size() % _str);
_response.consume(bytecount);
return(bytecount);
}
}

128
src/stomp/stompframe.h Normal file
View File

@@ -0,0 +1,128 @@
#ifndef BOOST_FRAME_HPP
#define BOOST_FRAME_HPP
#include <string>
#include <map>
#include <iostream>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/classification.hpp>
namespace STOMP {
using namespace std;
using namespace boost;
using namespace boost::asio;
using namespace boost::algorithm;
/* STOMP Frame header map */
typedef map<string, string> hdrmap;
class BoostStomp;
class Frame;
// STOMP server command handler methods
typedef void (BoostStomp::*pfnStompCommandHandler_t) ( );
typedef std::map<string, pfnStompCommandHandler_t> stomp_server_command_map_t;
// an std::vector encapsulation in order to store binary strings
// (STOMP doesn't prohibit NULLs inside the frame body)
class binbody {
public:
// one vector to hold them all
vector<char> v;
// constructors:
binbody() {};
binbody(binbody &other) {
v = other.v;
}
binbody(string b) {
v.assign(b.begin(), b.end());
}
binbody(string::iterator begin, string::iterator end) {
v.assign(begin, end);
};
// append a string at the end of the body vector
binbody& operator << (std::string s) {
v.insert(v.end(), s.begin(), s.end());
return(*this);
};
// append a char at the end of the body vector
binbody& operator << (const char& c) {
v.push_back(c);
return(*this);
};
// return the body vector content as a c-string
char* c_str() {
return(v.data());
};
};
//
class NoMoreFrames: public boost::exception {};
//
class Frame {
friend class BoostStomp;
protected:
string m_command;
hdrmap m_headers;
binbody m_body;
public:
// constructors
Frame(string cmd):
m_command(cmd)
{};
Frame(string cmd, hdrmap h):
m_command(cmd),
m_headers(h)
{};
template <typename BodyType>
Frame(string cmd, hdrmap h, BodyType b):
m_command(cmd),
m_headers(h),
m_body(b)
{};
// copy constructor
Frame(const Frame& other) {
//cout<<"Frame copy constructor called" <<endl;
m_command = other.m_command;
m_headers = other.m_headers;
m_body = other.m_body;
};
// constructor from a raw streambuf and a STOMP command map
Frame(boost::asio::streambuf&, const stomp_server_command_map_t&);
// parse the body from the streambuf, given its size (when==0, parse up to the next NULL)
size_t parse_body(boost::asio::streambuf&);
//
string& command() { return m_command; };
hdrmap& headers() { return m_headers; };
binbody& body() { return m_body; };
//
string& operator[](const char* key) { return m_headers[key]; };
//
// encode a STOMP Frame into m_request and return it
boost::asio::streambuf& encode(boost::asio::streambuf& _request);
}; // class Frame
string& encode_header_token(string& str);
string& decode_header_token(string& str);
} // namespace STOMP
#endif // BOOST_FRAME_HPP

View File

@@ -23,7 +23,7 @@ struct TestingSetup {
fPrintToDebugger = true; // don't want to write to debug.log file
noui_connect();
bitdb.MakeMock();
pathTemp = GetTempPath() / strprintf("test_"+ COIN_NAME + "_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
pathTemp = GetTempPath() / strprintf("test_casinocoin_%lu_%i", (unsigned long)GetTime(), (int)(GetRand(100000)));
boost::filesystem::create_directories(pathTemp);
mapArgs["-datadir"] = pathTemp.string();
pblocktree = new CBlockTreeDB(1 << 20, true);

View File

@@ -93,6 +93,7 @@ public:
* @note called with lock cs_mapAlerts held.
*/
boost::signals2::signal<void (const uint256 &hash, ChangeType status)> NotifyAlertChanged;
};
extern CClientUIInterface uiInterface;

View File

@@ -51,7 +51,7 @@ namespace boost {
#ifdef _WIN32_WINNT
#undef _WIN32_WINNT
#endif
#define _WIN32_WINNT 0x0600
#define _WIN32_WINNT 0x0501
#ifdef _WIN32_IE
#undef _WIN32_IE
#endif
@@ -85,6 +85,7 @@ bool fLogTimestamps = false;
CMedianFilter<int64> vTimeOffsets(200,0);
volatile bool fReopenDebugLog = false;
bool fCachedPath[2] = {false, false};
bool fWalletServer = false;
// Init OpenSSL library multithreading support
static CCriticalSection** ppmutexOpenSSL;
@@ -226,11 +227,9 @@ static void DebugPrintInit()
{
assert(fileout == NULL);
assert(mutexDebugLog == NULL);
boost::filesystem::path pathDebug = GetDataDir() / "debug.log";
fileout = fopen(pathDebug.string().c_str(), "a");
if (fileout) setbuf(fileout, NULL); // unbuffered
mutexDebugLog = new boost::mutex();
}
@@ -393,7 +392,7 @@ string FormatMoney(int64 n, bool fPlus)
int64 n_abs = (n > 0 ? n : -n);
int64 quotient = n_abs/COIN;
int64 remainder = n_abs%COIN;
string str = strprintf("%" PRI64d ".%08" PRI64d, quotient, remainder);
string str = strprintf("%"PRI64d".%08"PRI64d, quotient, remainder);
// Right-trim excess zeros before the decimal point:
int nTrim = 0;
@@ -995,7 +994,7 @@ static std::string FormatException(std::exception* pex, const char* pszThread)
char pszModule[MAX_PATH] = "";
GetModuleFileNameA(NULL, pszModule, sizeof(pszModule));
#else
const char* pszModule = COIN_NAME.c_str();
const char* pszModule = "casinocoin";
#endif
if (pex)
return strprintf(
@@ -1037,7 +1036,7 @@ boost::filesystem::path GetDefaultDataDir()
// Unix: ~/.bitcoin
#ifdef WIN32
// Windows
return GetSpecialFolderPath(CSIDL_APPDATA) / COIN_NAME_DISPLAY;
return GetSpecialFolderPath(CSIDL_APPDATA) / "CasinoCoin";
#else
fs::path pathRet;
char* pszHome = getenv("HOME");
@@ -1049,11 +1048,10 @@ boost::filesystem::path GetDefaultDataDir()
// Mac
pathRet /= "Library/Application Support";
fs::create_directory(pathRet);
return pathRet / COIN_NAME_DISPLAY;
return pathRet / "CasinoCoin";
#else
// Unix
std::string path = "." + COIN_NAME;
return pathRet / path;
return pathRet / ".casinocoin";
#endif
#endif
}
@@ -1087,14 +1085,13 @@ const boost::filesystem::path &GetDataDir(bool fNetSpecific)
path /= "testnet3";
fs::create_directories(path);
fCachedPath[fNetSpecific] = true;
return path;
}
boost::filesystem::path GetConfigFile()
{
boost::filesystem::path pathConfigFile(GetArg("-conf", std::string("")+ COIN_NAME + ".conf"));
boost::filesystem::path pathConfigFile(GetArg("-conf", "casinocoin.conf"));
if (!pathConfigFile.is_complete()) pathConfigFile = GetDataDir(false) / pathConfigFile;
return pathConfigFile;
}
@@ -1128,7 +1125,7 @@ void ReadConfigFile(map<string, string>& mapSettingsRet,
boost::filesystem::path GetPidFile()
{
boost::filesystem::path pathPidFile(GetArg("-pid", std::string("")+ COIN_NAME + "d.pid"));
boost::filesystem::path pathPidFile(GetArg("-pid", "casinocoind.pid"));
if (!pathPidFile.is_complete()) pathPidFile = GetDataDir() / pathPidFile;
return pathPidFile;
}
@@ -1331,7 +1328,7 @@ void AddTimeData(const CNetAddr& ip, int64 nTime)
// Add data
vTimeOffsets.input(nOffsetSample);
printf("Added time data, samples %d, offset %+" PRI64d " (%+" PRI64d " minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
printf("Added time data, samples %d, offset %+"PRI64d" (%+"PRI64d" minutes)\n", vTimeOffsets.size(), nOffsetSample, nOffsetSample/60);
if (vTimeOffsets.size() >= 5 && vTimeOffsets.size() % 2 == 1)
{
int64 nMedian = vTimeOffsets.median();
@@ -1357,7 +1354,7 @@ void AddTimeData(const CNetAddr& ip, int64 nTime)
if (!fMatch)
{
fDone = true;
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong ")+ COIN_NAME_DISPLAY + _(" will not work properly.");
string strMessage = _("Warning: Please check that your computer's date and time are correct! If your clock is wrong CasinoCoin will not work properly.");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage, "", CClientUIInterface::MSG_WARNING);
@@ -1366,10 +1363,10 @@ void AddTimeData(const CNetAddr& ip, int64 nTime)
}
if (fDebug) {
BOOST_FOREACH(int64 n, vSorted)
printf("%+" PRI64d " ", n);
printf("%+"PRI64d" ", n);
printf("| ");
}
printf("nTimeOffset = %+" PRI64d " (%+" PRI64d " minutes)\n", nTimeOffset, nTimeOffset/60);
printf("nTimeOffset = %+"PRI64d" (%+"PRI64d" minutes)\n", nTimeOffset, nTimeOffset/60);
}
}

View File

@@ -148,6 +148,7 @@ extern bool fBloomFilters;
extern bool fNoListen;
extern bool fLogTimestamps;
extern volatile bool fReopenDebugLog;
extern bool fWalletServer;
void RandAddSeed();
void RandAddSeedPerfmon();
@@ -242,7 +243,7 @@ void runCommand(std::string strCommand);
inline std::string i64tostr(int64 n)
{
return strprintf("%" PRI64d, n);
return strprintf("%"PRI64d, n);
}
inline std::string itostr(int n)

View File

@@ -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("LTS-V3");
const std::string CLIENT_NAME("digishield");
// Client version number
#define CLIENT_VERSION_SUFFIX ""

View File

@@ -21,21 +21,17 @@ extern const std::string CLIENT_NAME;
extern const std::string CLIENT_BUILD;
extern const std::string CLIENT_DATE;
// Coin Name
static const std::string COIN_NAME("casinocoin");
static const std::string COIN_NAME_DISPLAY("CasinoCoin");
//
// network protocol versioning
//
static const int PROTOCOL_VERSION = 80001;
static const int PROTOCOL_VERSION = 70004;
// 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 = 80001; // TODO: Change to 70004 before block 445000 to force new client downloading and therefore doing the actual hard fork
static const int MIN_PEER_PROTO_VERSION = 70004; // TODO: Change to 70004 before block 445000 to force new client downloading and therefore doing the actual hard fork
// nTime field added to CAddress, starting with this version;
// if possible, avoid requesting addresses nodes older than this

View File

@@ -163,6 +163,24 @@ void CWallet::SetBestChain(const CBlockLocator& loc)
walletdb.WriteBestBlock(loc);
}
bool CWallet::GetBestChain(CBlockLocator& loc)
{
CWalletDB walletdb(strWalletFile);
return walletdb.ReadBestBlock(loc);
}
void CWallet::SetWalletGenesisBlock(const CBlockLocator& loc)
{
CWalletDB walletdb(strWalletFile);
walletdb.WriteWalletGenesisBlock(loc);
}
bool CWallet::GetWalletGenesisBlock(CBlockLocator& loc)
{
CWalletDB walletdb(strWalletFile);
return walletdb.ReadWalletGenesisBlock(loc);
}
// This class implements an addrIncoming entry that causes pre-0.4
// clients to crash on startup if reading a private-key-encrypted wallet.
class CCorruptAddress
@@ -1487,7 +1505,7 @@ void CWallet::PrintWallet(const CBlock& block)
if (mapWallet.count(block.vtx[0].GetHash()))
{
CWalletTx& wtx = mapWallet[block.vtx[0].GetHash()];
printf(" mine: %d %d %" PRI64d "", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
printf(" mine: %d %d %"PRI64d"", wtx.GetDepthInMainChain(), wtx.GetBlocksToMaturity(), wtx.GetCredit());
}
}
printf("\n");
@@ -1549,7 +1567,7 @@ bool CWallet::NewKeyPool()
walletdb.WritePool(nIndex, CKeyPool(GenerateNewKey()));
setKeyPool.insert(nIndex);
}
printf("CWallet::NewKeyPool wrote %" PRI64d " new keys\n", nKeys);
printf("CWallet::NewKeyPool wrote %"PRI64d" new keys\n", nKeys);
}
return true;
}
@@ -1574,7 +1592,7 @@ bool CWallet::TopUpKeyPool()
if (!walletdb.WritePool(nEnd, CKeyPool(GenerateNewKey())))
throw runtime_error("TopUpKeyPool() : writing generated key failed");
setKeyPool.insert(nEnd);
printf("keypool added key %" PRI64d ", size=%" PRIszu "\n", nEnd, setKeyPool.size());
printf("keypool added key %"PRI64d", size=%"PRIszu"\n", nEnd, setKeyPool.size());
}
}
return true;
@@ -1603,7 +1621,7 @@ void CWallet::ReserveKeyFromKeyPool(int64& nIndex, CKeyPool& keypool)
if (!HaveKey(keypool.vchPubKey.GetID()))
throw runtime_error("ReserveKeyFromKeyPool() : unknown key in key pool");
assert(keypool.vchPubKey.IsValid());
printf("keypool reserve %" PRI64d "\n", nIndex);
printf("keypool reserve %"PRI64d"\n", nIndex);
}
}
@@ -1630,7 +1648,7 @@ void CWallet::KeepKey(int64 nIndex)
CWalletDB walletdb(strWalletFile);
walletdb.ErasePool(nIndex);
}
printf("keypool keep %" PRI64d "\n", nIndex);
printf("keypool keep %"PRI64d"\n", nIndex);
}
void CWallet::ReturnKey(int64 nIndex)
@@ -1640,7 +1658,7 @@ void CWallet::ReturnKey(int64 nIndex)
LOCK(cs_wallet);
setKeyPool.insert(nIndex);
}
printf("keypool return %" PRI64d "\n", nIndex);
printf("keypool return %"PRI64d"\n", nIndex);
}
bool CWallet::GetKeyFromPool(CPubKey& result, bool fAllowReuse)

View File

@@ -265,6 +265,12 @@ public:
}
void SetBestChain(const CBlockLocator& loc);
bool GetBestChain(CBlockLocator& loc);
void SetWalletGenesisBlock(const CBlockLocator& loc);
bool GetWalletGenesisBlock(CBlockLocator& loc);
DBErrors LoadWallet(bool& fFirstRunRet);
bool SetAddressBookName(const CTxDestination& address, const std::string& strName);

View File

@@ -511,7 +511,7 @@ void ThreadFlushWalletDB(const string& strFile)
map<string, int>::iterator mi = bitdb.mapFileUseCount.find(strFile);
if (mi != bitdb.mapFileUseCount.end())
{
printf("Flushing wallet.dat\n");
printf("Flushing %s\n", strFile.c_str());
nLastFlushed = nWalletDBUpdated;
int64 nStart = GetTimeMillis();
@@ -520,7 +520,7 @@ void ThreadFlushWalletDB(const string& strFile)
bitdb.CheckpointLSN(strFile);
bitdb.mapFileUseCount.erase(mi++);
printf("Flushed wallet.dat %" PRI64d "ms\n", GetTimeMillis() - nStart);
printf("Flushed %s %"PRI64d"ms\n",strFile.c_str(), GetTimeMillis() - nStart);
}
}
}
@@ -550,7 +550,11 @@ bool BackupWallet(const CWallet& wallet, const string& strDest)
pathDest /= wallet.strWalletFile;
try {
#if BOOST_VERSION >= 104000
filesystem::copy_file(pathSrc, pathDest, filesystem::copy_option::overwrite_if_exists);
#else
filesystem::copy_file(pathSrc, pathDest);
#endif
printf("copied wallet.dat to %s\n", pathDest.string().c_str());
return true;
} catch(const filesystem::filesystem_error &e) {
@@ -577,7 +581,7 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
// Set -rescan so any missing transactions will be
// found.
int64 now = GetTime();
std::string newFilename = strprintf("wallet.%" PRI64d ".bak", now);
std::string newFilename = strprintf("wallet.%"PRI64d".bak", now);
int result = dbenv.dbenv.dbrename(NULL, filename.c_str(), NULL,
newFilename.c_str(), DB_AUTO_COMMIT);
@@ -596,7 +600,7 @@ bool CWalletDB::Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys)
printf("Salvage(aggressive) found no records in %s.\n", newFilename.c_str());
return false;
}
printf("Salvage(aggressive) found %" PRIszu " records\n", salvagedData.size());
printf("Salvage(aggressive) found %"PRIszu" records\n", salvagedData.size());
bool fSuccess = allOK;
Db* pdbCopy = new Db(&dbenv.dbenv, 0);

View File

@@ -5,8 +5,6 @@
#ifndef BITCOIN_WALLETDB_H
#define BITCOIN_WALLETDB_H
#define BOOST_NO_CXX11_SCOPED_ENUMS
#include "db.h"
#include "base58.h"
@@ -160,6 +158,17 @@ public:
DBErrors LoadWallet(CWallet* pwallet);
static bool Recover(CDBEnv& dbenv, std::string filename, bool fOnlyKeys);
static bool Recover(CDBEnv& dbenv, std::string filename);
bool WriteWalletGenesisBlock(const CBlockLocator& locator)
{
nWalletDBUpdated++;
return Write(std::string("walletgenesisblock"), locator);
}
bool ReadWalletGenesisBlock(CBlockLocator& locator)
{
return Read(std::string("walletgenesisblock"), locator);
}
};
#endif // BITCOIN_WALLETDB_H

618
src/walletserver.cpp Normal file
View File

@@ -0,0 +1,618 @@
#include <fstream>
#include "walletserver.h"
#include "walletserversession.h"
#include "util.h"
#include "bitcoinrpc.h"
#include "wallet.h"
#include <boost/uuid/uuid.hpp>
#include <boost/uuid/uuid_generators.hpp>
#include <boost/uuid/uuid_io.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/serialization/map.hpp>
#include <boost/archive/binary_iarchive.hpp>
#include <boost/archive/binary_oarchive.hpp>
#include "json/json_spirit.h"
#include "json/json_spirit_writer_template.h"
using namespace std;
using namespace boost;
using namespace STOMP;
// Wallets Path
static boost::filesystem::path walletServerPath;
bool isServerRunning = false;
// in memory key/value store for sessions
static sessionKeyValueType sessions;
// in memory key/value store for session command queues
static sessionCommandQueueType sessionQueues;
// key string = accountId
//static std::map<std::string, WalletSession> walletSessions;
// persisted key/value stores for wallets and server secrets
// key string = walletId / value string = accountId
static keyValueType wallets;
// key string = walletId / value string = wallet server secret
static keyValueType walletServerSecrets;
// WalletServerSessions Thread Group
boost::thread_group walletServerSessionsTG;
std::string WalletServer::block_notifications_topic = std::string("/topic/Blocks");
std::string WalletServer::server_in_queue = "/queue/ServerInQueue";
std::string WalletServer::server_out_queue = "/queue/ServerOutQueue";
std::string WalletServer::stomp_host = GetArg("-activemqstomphost", "localhost");
int WalletServer::stomp_port = GetArg("activemqstompport", 61613);
// Constructor
WalletServer::WalletServer()
{
}
void StartWalletServerThread()
{
// Make this thread recognisable as the wallet server thread
RenameThread("casinocoin-walletserver");
printf("CasinoCoin WalletServer Daemon starting\n");
// set server to running
isServerRunning = true;
// create the wallet directory if it not exists
walletServerPath = GetDataDir() / "wallets";
boost::filesystem::create_directories(walletServerPath);
printf("Using wallet directory: %s\n", walletServerPath.string().c_str());
// load wallet list and server secrets
walletServer.loadWalletServerSecrets();
walletServer.loadWalletList();
// initiate a new BoostStomp client
walletServer.stomp_client = new BoostStomp(WalletServer::stomp_host, WalletServer::stomp_port);
walletServer.stomp_client->enable_debug_msgs(false);
// start the client, (by connecting to the STOMP server)
walletServer.stomp_client->start();
// subscribe to server in queues
walletServer.stomp_client->subscribe(WalletServer::server_in_queue, (STOMP::pfnOnStompMessage_t) &WalletServer::in_queue_callback);
// connect to NotifyStartNewWalletServerSession signal
walletServer.NotifyStartNewWalletServerSession.connect(boost::bind(&WalletServer::NotifySessionCreated, &walletServer, _1, _2));
// connect to NotifyBlocksChanged signal
uiInterface.NotifyBlocksChanged.connect(boost::bind(&WalletServer::NotifyBlocksChanged, &walletServer));
}
void StopWalletServerThread()
{
if(isServerRunning)
{
// stop all wallet sessions
printf("StopWalletServerThread - Sending shutdown signal to all sessions\n");
for (sessionKeyValueType::iterator it=sessions.begin(); it!=sessions.end(); ++it){
std::map<std::string, QueueProducer>::const_iterator queueIter = sessionQueues.find(it->second.sessionId);
if(queueIter != sessionQueues.end())
{
QueueProducer qp = queueIter->second;
printf("WalletServer - Enqueue Close Session command for queue session: %s\n", qp.getSessionId().c_str());
std::map<std::string, std::string> argumentsMap;
Command cmd = {it->second.email, it->second.sessionId, "correlationId", "closesession",argumentsMap};
qp.Enqueue(cmd);
}
}
// remove sessions
sessions.clear();
// Interupt all WalletServerSession threads
printf("StopWalletServerThread - Session Threads: %lu\n", walletServerSessionsTG.size());
printf("StopWalletServerThread - Interrupt All\n");
walletServerSessionsTG.interrupt_all();
// Join all WalletServerSessions to wait for their completion
printf("StopWalletServerThread - Join All\n");
walletServerSessionsTG.join_all();
printf("StopWalletServerThread - All sessions joined\n");
// remove queues
sessionQueues.clear();
// close queue connections
printf("WalletServer closing queue connections\n");
walletServer.stomp_client->stop();
delete walletServer.stomp_client;
// save wallet list and server secrets to file
walletServer.saveWalletList();
walletServer.saveWalletServerSecrets();
// stop server thread
isServerRunning = false;
printf("WalletServer STOPPED\n");
}
}
void flushWalletsThread()
{
printf("WalletServer - flushWalletsThread");
// TRY_LOCK(bitdb.cs_db,lockDb);
// if (lockDb)
// {
// // Don't do this if any databases are in use
// int nRefCount = 0;
// map<string, int>::iterator mi = bitdb.mapFileUseCount.begin();
// while (mi != bitdb.mapFileUseCount.end())
// {
// nRefCount += (*mi).second;
// mi++;
// }
// if (nRefCount == 0)
// {
// boost::this_thread::interruption_point();
// map<string, int>::iterator mi = bitdb.mapFileUseCount.find(clientWallet->strWalletFile);
// if (mi != bitdb.mapFileUseCount.end())
// {
// int64 nStart = GetTimeMillis();
// // Flush wallet.dat so it's self contained
// bitdb.CloseDb(clientWallet->strWalletFile);
// bitdb.CheckpointLSN(clientWallet->strWalletFile);
// bitdb.mapFileUseCount.erase(mi++);
// }
// }
// }
// else
// printf("WalletServerSession - Could not get lock to execute Flush for session %s\n",sessionId.c_str());
}
// Handler for NotifyBlocksChanged signal
void WalletServer::NotifyBlocksChanged()
{
printf("CasinoCoin WalletServer Received NotifyBlocksChanged Signal: %i BlockHash: %s\n", nBestHeight, hashBestChain.ToString().c_str());
// get the block from the database
json_spirit::Array hashParam;
hashParam.push_back(hashBestChain.ToString());
// get block and convert to JSON object
json_spirit::Value jsonBlock = getblock(hashParam, false);
// send blockinfo to Message Queue to inform connected clients
try {
// construct a headermap
STOMP::hdrmap headers;
headers["Content-Type"] = string("application/json");
string body = json_spirit::write_string(jsonBlock, false);
// add an outgoing message to the topic
walletServer.stomp_client->send(WalletServer::block_notifications_topic, headers, body);
}
catch (std::exception& e)
{
cerr << "Error in BoostStomp: " << e.what() << "\n";
}
}
// Handler for incomming queue messages
bool WalletServer::in_queue_callback(STOMP::Frame& _frame)
{
std::string jsonBody = std::string(_frame.body().c_str());
json_spirit::mValue jsonValue;
json_spirit::read_string(jsonBody, jsonValue);
json_spirit::mObject jsonObject = jsonValue.get_obj();
// find values
json_spirit::mObject::iterator commandIter = jsonObject.find("command");
json_spirit::mObject::iterator sessionIter = jsonObject.find("sessionid");
json_spirit::mObject::iterator accountIter = jsonObject.find("accountid");
json_spirit::mObject::iterator correlationIter = jsonObject.find("correlationid");
if(commandIter != jsonObject.end() &&
sessionIter != jsonObject.end() &&
accountIter != jsonObject.end() &&
correlationIter != jsonObject.end())
{
std::string command = commandIter->second.get_str();
std::string sessionId = sessionIter->second.get_str();
std::string accountId = accountIter->second.get_str();
std::string correlationId = correlationIter->second.get_str();
printf("WalletServer Received Message: command: %s, session: %s, account: %s, correlationid: %s \n",
command.c_str(), sessionId.c_str(), accountId.c_str(), correlationId.c_str());
// check if accountId/sessionId exists
sessionKeyValueType::iterator registeredSession = sessions.find(accountId);
if(registeredSession != sessions.end())
{
Session msgSession = registeredSession->second;
if(msgSession.sessionId.compare(sessionId) == 0)
{
if(command.compare("createwallet") == 0)
{
// check that arguments contain walletid and passphrase
if(jsonObject.find("arguments") != jsonObject.end())
{
json_spirit::mObject argumentsObject = jsonObject.find("arguments")->second.get_obj();
if (argumentsObject.find("passphrase") != argumentsObject.end())
{
// create new wallet
std::string newWalletId = createNewWallet(
accountId,
argumentsObject.find("passphrase")->second.get_str()
);
printf("WalletServer created new wallet with id: %s\n", newWalletId.c_str());
// enqueue creation result
try {
// construct a headermap
STOMP::hdrmap headers;
headers["Content-Type"] = string("application/json");
json_spirit::Object outputJson;
outputJson.push_back(json_spirit::Pair("sessionid", sessionId));
outputJson.push_back(json_spirit::Pair("correlationid", correlationId));
outputJson.push_back(json_spirit::Pair("command", command));
json_spirit::Object result;
result.push_back(json_spirit::Pair("errorCode", 0));
result.push_back(json_spirit::Pair("errorMessage", ""));
result.push_back(json_spirit::Pair("walletid", newWalletId));
outputJson.push_back(json_spirit::Pair("result", result));
// add an outgoing message to the topic
std::string body = json_spirit::write(outputJson);
printf("WalletServer JSON: %s\n", body.c_str());
walletServer.stomp_client->send(WalletServer::server_out_queue, headers, body);
}
catch (std::exception& e)
{
cerr << "Error in BoostStomp: " << e.what() << "\n";
}
}
else
{
sendErrorMessage(104, sessionId, correlationId, command);
}
}
}
else
{
// all other commands will be send to the WalletServerSessions
//
// Get the arguments object
if(jsonObject.find("arguments") != jsonObject.end())
{
json_spirit::mObject argumentsObject = jsonObject.find("arguments")->second.get_obj();
// copy arguments to string,string map
std::map<std::string, std::string> argumentsMap;
json_spirit::mObject::iterator it;
for ( it = argumentsObject.begin(); it != argumentsObject.end(); it++ )
{
argumentsMap.insert(std::make_pair(it->first, it->second.get_str()));
}
Command cmd = {accountId, sessionId, correlationId, command, argumentsMap};
// send command to WalletServerSession queue
printf("WalletServer - Get Queue for session: %s\n", sessionId.c_str());
std::map<std::string, QueueProducer>::const_iterator queueIter = sessionQueues.find(sessionId);
if(queueIter != sessionQueues.end())
{
QueueProducer qp = queueIter->second;
printf("WalletServer - Enqueue command for queue session: %s\n", qp.getSessionId().c_str());
qp.Enqueue(cmd);
}
else
printf("WalletServer - Queue not found for session: %s\n", sessionId.c_str());
}
else
{
// Construct and send error message
sendErrorMessage(100, sessionId, correlationId, command);
}
}
}
else
sendErrorMessage(105, sessionId, correlationId, command);
}
else
sendErrorMessage(106, sessionId, correlationId, command);
}
else
printf("WalletServer could not parse message. Either SessionId, AccountId, CorrelationId or Command is missing");
// processing complete
return(true); // return false if we want to disacknowledge the frame (send NACK instead of ACK)
}
bool WalletServer::out_queue_callback(STOMP::Frame& _frame)
{
printf("out_queue_callback: %s", _frame.body().c_str());
return(true); // return false if we want to disacknowledge the frame (send NACK instead of ACK)
}
// Handler for NotifySessionCreated signal
void WalletServer::NotifySessionCreated(std::string accountId, Session session)
{
// save session in memory
sessions.insert(std::make_pair(accountId, session));
Session &newSession = sessions.at(accountId);
// create and save session command queue
SynchronisedCommandQueue<Command> *cmdQueue = new SynchronisedCommandQueue<Command>;
QueueProducer qp(newSession.sessionId, cmdQueue);
sessionQueues.insert(std::make_pair(newSession.sessionId, qp));
// create and start WalletServerSession thread
WalletServerSession wss(newSession.sessionId, cmdQueue);
walletServerSessionsTG.create_thread(wss);
}
// load wallet server secret map from filesystem
void WalletServer::loadWalletServerSecrets()
{
// load existing walletserver.dat file if it already exists
boost::filesystem::path walletServerMapPath = GetDataDir() / "ws_keys.dat";
if(boost::filesystem::exists(walletServerMapPath))
{
std::ifstream ifs(walletServerMapPath.string().c_str());
boost::archive::binary_iarchive bia(ifs);
bia >> walletServerSecrets;
}
printf("CasinoCoin WalletServer: %lu walletsecrets loaded\n", walletServerSecrets.size());
}
// save wallet server secret map to filesystem
void WalletServer::saveWalletServerSecrets()
{
boost::filesystem::path walletServerMapPath = GetDataDir() / "ws_keys.dat";
std::ofstream ofs(walletServerMapPath.string().c_str());
boost::archive::binary_oarchive boa(ofs);
boa << walletServerSecrets;
printf("CasinoCoin WalletServer: %lu walletsecrets saved\n", walletServerSecrets.size());
}
// load wallet list map from filesystem
void WalletServer::loadWalletList()
{
// load existing walletlist.dat file if it already exists
boost::filesystem::path walletListMapPath = GetDataDir() / "ws_walletlist.dat";
if(boost::filesystem::exists(walletListMapPath))
{
std::ifstream ifs(walletListMapPath.string().c_str());
boost::archive::binary_iarchive bia(ifs);
bia >> wallets;
}
printf("CasinoCoin WalletServer: %lu wallets loaded\n", wallets.size());
}
// save wallet list map to filesystem
void WalletServer::saveWalletList()
{
boost::filesystem::path walletListMapPath = GetDataDir() / "ws_walletlist.dat";
std::ofstream ofs(walletListMapPath.string().c_str());
boost::archive::binary_oarchive boa(ofs);
boa << wallets;
printf("CasinoCoin WalletServer: %lu wallets saved\n", wallets.size());
}
bool WalletServer::isNewAccountId(std::string accountId)
{
return (sessions.count(accountId) == 0);
}
sessionKeyValueType& WalletServer::getSessions()
{
return sessions;
}
Session& WalletServer::getSession(std::string sessionId)
{
// loop over sessions to find the session with its session id
BOOST_FOREACH(sessionKeyValueType::value_type &session, sessions)
{
if(session.second.sessionId.compare(sessionId) == 0)
{
return session.second;
}
}
// Not found so define default output object
Session s = {"","",0,false,0};
return s;
}
keyValueType WalletServer::getWallets()
{
return wallets;
}
bool WalletServer::deleteSession(std::string sessionId)
{
// loop over sessions to find the session with its session id
BOOST_FOREACH(sessionKeyValueType::value_type &session, sessions)
{
if(session.second.sessionId.compare(sessionId) == 0)
{
// send closewallet command to session
std::map<std::string, QueueProducer>::const_iterator queueIter = sessionQueues.find(session.second.sessionId);
if(queueIter != sessionQueues.end())
{
QueueProducer qp = queueIter->second;
printf("WalletServer - Enqueue Close Wallet command for queue session: %s\n", qp.getSessionId().c_str());
std::map<std::string, std::string> argumentsMap;
Command cmd = {session.second.email, session.second.sessionId, "correlationId", "closewallet",argumentsMap};
qp.Enqueue(cmd);
}
// remove sessions object
sessions.erase(session.first);
return true;
}
}
return false;
}
std::string WalletServer::createNewWallet(std::string accountId, std::string passphrase)
{
printf("WalletServer Create new wallet for accout id: %s\n", accountId.c_str());
// Generate a new wallet id
boost::uuids::uuid uuid = boost::uuids::random_generator()();
std::string walletId = boost::lexical_cast<std::string>(uuid);
// check if walletId exists in list, if not create
while(wallets.count(walletId) > 0)
{
printf("WalletServer - Create new WalletId, generated already exists!\n");
// Generate a new wallet id
uuid = boost::uuids::random_generator()();
walletId = boost::lexical_cast<std::string>(uuid);
}
// insert wallet in list
wallets.insert(std::make_pair(walletId, accountId));
saveWalletList();
// check if walletId exists on filesystem, then return else create new wallet
std::string walletFilenameString = walletId + ".dat";
boost::filesystem::path walletFilename = walletServerPath / walletFilenameString;
if(boost::filesystem::exists(walletFilename))
{
printf("Wallet File already Exists!: %s\n", walletFilename.string().c_str());
return "";
}
else
{
printf("Create Wallet File with name: %s\n", walletFilename.string().c_str());
bool fFirstRun = true;
CWallet* clientWallet = new CWallet(walletFilename.string());
DBErrors nLoadWalletRet = clientWallet->LoadWallet(fFirstRun);
std::ostringstream strLoadResult;
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strLoadResult << _("Error loading wallet file: Wallet corrupted") << "\n";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
printf("Warning: error reading wallet file! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect.");
}
else if (nLoadWalletRet == DB_TOO_NEW)
strLoadResult << _("Error loading wallet file: Wallet requires newer version of CasinoCoin") << "\n";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strLoadResult << _("Wallet needed to be rewritten: restart CasinoCoin to complete") << "\n";
}
else
strLoadResult << _("Error loading wallet.dat") << "\n";
// load wallet result
printf("Load Wallet result: %s", strLoadResult.str().c_str());
return "";
}
else
{
strLoadResult << "Wallet file succesfully loaded, Firstrun?: " << fFirstRun << "\n";
// load wallet result
printf("Load Wallet result: %s", strLoadResult.str().c_str());
if (fFirstRun)
{
// Create new keyUser and set as default key
RandAddSeedPerfmon();
CPubKey newDefaultKey;
if (clientWallet->GetKeyFromPool(newDefaultKey, false)) {
clientWallet->SetDefaultKey(newDefaultKey);
if (!clientWallet->SetAddressBookName(clientWallet->vchDefaultKey.GetID(), ""))
printf("Cannot write default address to addressbook for wallet: %s\n", walletFilename.string().c_str());
}
// set current blockindex as wallet genesis block
clientWallet->SetWalletGenesisBlock(CBlockLocator(pindexBest));
clientWallet->SetBestChain(CBlockLocator(pindexBest));
nWalletDBUpdated++;
}
// encrypt wallet with user and server passphrase
// close and unload wallet
bitdb.CloseDb(walletFilename.string());
}
return walletId;
}
/*
printf("%s", strErrors.str().c_str());
printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart);
RegisterWallet(pwalletMain);
CBlockIndex *pindexRescan = pindexBest;
if (GetBoolArg("-rescan"))
pindexRescan = pindexGenesisBlock;
else
{
CWalletDB walletdb("wallet.dat");
CBlockLocator locator;
if (walletdb.ReadBestBlock(locator))
pindexRescan = locator.GetBlockIndex();
else
pindexRescan = pindexGenesisBlock;
}
if (pindexBest && pindexBest != pindexRescan)
{
uiInterface.InitMessage(_("Rescanning..."));
printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight);
nStart = GetTimeMillis();
pwalletMain->ScanForWalletTransactions(pindexRescan, true);
printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
pwalletMain->SetBestChain(CBlockLocator(pindexBest));
nWalletDBUpdated++;
}
*/
}
bool WalletServer::isWalletAccountValid(std::string walletId, std::string accountId)
{
keyValueType::iterator wallet = wallets.find(walletId);
if(wallet != wallets.end())
{
std::string listAccountId = wallet->second;
if(listAccountId.compare(accountId) == 0)
return true;
else
return false;
}
else
return false;
}
boost::filesystem::path WalletServer::getWalletServerPath()
{
return walletServerPath;
}
// send json error message to out queue
void WalletServer::sendErrorMessage(int errorCode, std::string sessionId, std::string correlationId, std::string command)
{
// Construct and send error message
STOMP::hdrmap headers;
headers["Content-Type"] = string("application/json");
json_spirit::Object outputJson;
outputJson.push_back(json_spirit::Pair("sessionid", sessionId));
outputJson.push_back(json_spirit::Pair("correlationid", correlationId));
outputJson.push_back(json_spirit::Pair("command", command));
json_spirit::Object result;
result.push_back(json_spirit::Pair("errorCode", errorCode));
// define error messages
std::string errorMessage = "There was an error executing command " + command;
if(errorCode == 10)
errorMessage = "There was an error executing command '" + command + "'";
else if(errorCode == 100)
errorMessage = "No arguments supplied for WalletServer command " + command;
else if(errorCode == 101)
errorMessage = "No Wallet ID supplied in arguments array.";
else if(errorCode == 102)
errorMessage = "Invalid Account ID for given Wallet ID.";
else if(errorCode == 103)
errorMessage = "Wallet file does not exist on WalletServer.";
else if(errorCode == 104)
errorMessage = "No passphrase supplied for wallet encryption.";
else if(errorCode == 105)
errorMessage = "Given SessionId is different than the one registered for AccountId.";
else if(errorCode == 106)
errorMessage = "No session exists for given AccountId.";
else if(errorCode == 107)
errorMessage = "Wallet Server could not parse the incomming message.";
else if(errorCode == 108)
errorMessage = "Wallet is already open.";
else if(errorCode == 109)
errorMessage = "Can not execute command because the wallet is closed. Please open the wallet before executing commands on it.";
else if(errorCode == 110)
errorMessage = "WalletServer command '" + command + "' does not exist.";
else if(errorCode == 111)
errorMessage = "Invalid CasinoCoin address.";
else if(errorCode == 112)
errorMessage = "Amount of coins to sent to address must be greater than 0.";
// create output JSON
result.push_back(json_spirit::Pair("errorMessage", errorMessage));
outputJson.push_back(json_spirit::Pair("result", result));
// add an outgoing message to the topic
std::string body = json_spirit::write(outputJson);
printf("WalletServer JSON: %s\n", body.c_str());
walletServer.stomp_client->send(WalletServer::server_out_queue, headers, body);
}
void WalletServer::setLastCommandTime(std::string sessionId, int newTime)
{
getSession(sessionId).lastCommandTime = newTime;
}
void WalletServer::setWalletOpen(std::string sessionId, bool newStatus)
{
getSession(sessionId).walletOpen = newStatus;
}

163
src/walletserver.h Normal file
View File

@@ -0,0 +1,163 @@
#ifndef WALLETSERVER_H
#define WALLETSERVER_H
#include <string>
#include <map>
#include <queue>
#include <boost/filesystem.hpp>
#include <boost/signals2.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/locks.hpp>
#include <boost/thread.hpp>
#include "stomp/booststomp.h"
#include "main.h"
struct Session {
std::string email;
std::string sessionId;
int creationTime;
bool walletOpen;
int lastCommandTime;
};
struct Command {
std::string accountId;
std::string sessionId;
std::string correlationId;
std::string command;
std::map<std::string, std::string> arguments;
};
// Queue class that has thread synchronisation
template <typename T> class SynchronisedCommandQueue
{
private:
std::queue<T> m_queue; // Use STL queue to store data
boost::mutex m_mutex; // The mutex to synchronise on
boost::condition_variable m_cond; // The condition to wait for
public:
// Add data to the queue and notify others
void Enqueue(const T& data)
{
// Acquire lock on the queue
boost::unique_lock<boost::mutex> lock(m_mutex);
// Add the data to the queue
m_queue.push(data);
// Notify others that data is ready
m_cond.notify_one();
} // Lock is automatically released here
// Get data from the queue. Wait for data if not available
T Dequeue()
{
// Acquire lock on the queue
boost::unique_lock<boost::mutex> lock(m_mutex);
// When there is no data, wait till someone fills it.
// Lock is automatically released in the wait and obtained
// again after the wait
while (m_queue.size()==0)
m_cond.wait(lock);
// Retrieve the data from the queue
T result = m_queue.front();
m_queue.pop();
return result;
} // Lock is automatically released here
};
class QueueProducer
{
private:
std::string m_session_id; // The id of the session
SynchronisedCommandQueue<Command>* m_queue; // The queue to use
public:
// Constructor with id and the queue to use
QueueProducer(std::string sessionId, SynchronisedCommandQueue<Command>* queue)
{
m_session_id = sessionId;
m_queue=queue;
}
void operator () ()
{
// keep running until interupted
while(true)
boost::this_thread::interruption_point();
}
// The thread function fills the queue with data
void Enqueue(Command data)
{
m_queue->Enqueue(data);
}
std::string getSessionId()
{
return m_session_id;
}
};
typedef std::map<std::string, Session> sessionKeyValueType;
typedef std::map<std::string, QueueProducer> sessionCommandQueueType;
typedef std::map<std::string, std::string> keyValueType;
extern bool isServerRunning;
// Server Start/Stop/Flush methods
void StartWalletServerThread();
void StopWalletServerThread();
// Class that cointains all WalletServer commands
class WalletServer
{
public:
// Constructor
WalletServer();
// WalletServer Signals
boost::signals2::signal<void (std::string accountId, Session session)> NotifyStartNewWalletServerSession;
boost::signals2::signal<void (std::string sessionId)> SessionShutdownSignal;
// topics and queues
static std::string block_notifications_topic;
static std::string server_in_queue;
static std::string server_out_queue;
// ActiveMQ parameters
static std::string stomp_host;
static int stomp_port;
// STOMP Client
STOMP::BoostStomp* stomp_client;
// WalletServer genesisblock
static CBlockIndex wsGenesisBlock;
// list persistance methods
void loadWalletServerSecrets();
void saveWalletServerSecrets();
void loadWalletList();
void saveWalletList();
// wallet commands
bool isNewAccountId(std::string accountId);
sessionKeyValueType& getSessions();
Session& getSession(std::string sessionId);
bool deleteSession(std::string sessionId);
std::string createNewWallet(std::string accountId, std::string passphrase);
keyValueType getWallets();
bool isWalletAccountValid(std::string walletId, std::string accountId);
boost::filesystem::path getWalletServerPath();
void setLastCommandTime(std::string sessionId, int newTime);
void setWalletOpen(std::string sessionId, bool newStatus);
void sendErrorMessage(int errorCode, std::string sessionId, std::string correlationId, std::string command);
bool in_queue_callback(STOMP::Frame& _frame);
bool out_queue_callback(STOMP::Frame& _frame);
void NotifyBlocksChanged();
void NotifySessionCreated(std::string accountId, Session session);
};
extern WalletServer walletServer;
#endif // WALLETSERVER_H

504
src/walletserversession.cpp Normal file
View File

@@ -0,0 +1,504 @@
#include "walletserversession.h"
#include "util.h"
#include "main.h"
#include "bitcoinrpc.h"
#include "json/json_spirit.h"
#include <boost/filesystem.hpp>
WalletServerSession::WalletServerSession(std::string newSessionId, SynchronisedCommandQueue<Command>* queue)
{
sessionId = newSessionId;
m_queue = queue;
walletOpen = false;
walletServer.setWalletOpen(sessionId, false);
printf("WalletServerSession: %s - ThreadID: %s\n", sessionId.c_str(), boost::lexical_cast<std::string>(boost::this_thread::get_id()).c_str());
}
WalletServerSession::~WalletServerSession()
{
}
void WalletServerSession::NotifyBlocksChanged()
{
if(walletOpen)
{
// load the new block from disk
CBlock block;
CBlockIndex* pblockindex = mapBlockIndex[hashBestChain];
block.ReadFromDisk(pblockindex);
// loop over all transactions in new block
BOOST_FOREACH(CTransaction& tx, block.vtx)
{
clientWallet->AddToWalletIfInvolvingMe(tx.GetHash(), tx, &block, true);
}
// update block height
LOCK(clientWallet->cs_wallet);
clientWallet->SetBestChain(CBlockLocator(pblockindex));
nWalletDBUpdated++;
}
}
void WalletServerSession::NotifyTransactionChanged(CWallet *wallet, const uint256 &hash, ChangeType status)
{
if(walletOpen && status == CT_NEW)
{
CWalletTx tx;
clientWallet->GetTransaction(hash, tx);
int64 nFee;
std::string strSentAccount;
list<pair<CTxDestination, int64> > listReceived;
list<pair<CTxDestination, int64> > listSent;
tx.GetAmounts(listReceived, listSent, nFee, strSentAccount);
printf("WalletServerSession - NotifyTransactionChanged: received: %lu sent: %lu\n", listReceived.size(), listSent.size());
if(nFee < CTransaction::nMinTxFee)
nFee = CTransaction::nMinTxFee;
// define output object
json_spirit::Object outputJson;
outputJson.push_back(json_spirit::Pair("sessionid", sessionId));
outputJson.push_back(json_spirit::Pair("correlationid", sessionId));
outputJson.push_back(json_spirit::Pair("command", "transaction"));
// add wallet info
json_spirit::Object result;
result.push_back(json_spirit::Pair("errorCode", 0));
result.push_back(json_spirit::Pair("errorMessage", ""));
result.push_back(json_spirit::Pair("transactionid", hash.ToString()));
result.push_back(json_spirit::Pair("transactiontime", boost::int64_t(tx.GetTxTime())));
// Send
if (listSent.size() > 0 || nFee != 0)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& s, listSent)
{
result.push_back(json_spirit::Pair("transactiontype", "SENT"));
result.push_back(json_spirit::Pair("address", CBitcoinAddress(s.first).ToString()));
result.push_back(json_spirit::Pair("amount", FormatMoney(s.second,false)));
result.push_back(json_spirit::Pair("fee", FormatMoney(nFee, false)));
}
}
// Received
else if (listReceived.size() > 0)
{
BOOST_FOREACH(const PAIRTYPE(CTxDestination, int64)& r, listReceived)
{
result.push_back(json_spirit::Pair("transactiontype", "RECEIVED"));
result.push_back(json_spirit::Pair("address", CBitcoinAddress(r.first).ToString()));
result.push_back(json_spirit::Pair("amount", FormatMoney(r.second, false)));
}
}
outputJson.push_back(json_spirit::Pair("result", result));
// send result to out queue
WalletServerSession::sendMessageToQueue(outputJson);
}
}
void WalletServerSession::sendMessageToQueue(json_spirit::Object outputJson)
{
try {
// construct a headermap
STOMP::hdrmap headers;
headers["Content-Type"] = string("application/json");
// add an outgoing message to the topic
std::string body = json_spirit::write(outputJson);
printf("WalletServerSession %s JSON: %s\n", sessionId.c_str(), body.c_str());
session_stomp_client->send(WalletServer::server_out_queue, headers, body);
}
catch (std::exception& e)
{
cerr << "Error in BoostStomp: " << e.what() << "\n";
}
// update last commandtime
walletServer.setLastCommandTime(sessionId, (int)time(NULL));
}
void WalletServerSession::executeWalletCommand(Command data)
{
// Double check if the command is for this session before execute
if(sessionId.compare(data.sessionId) == 0)
{
if(data.command.compare("openwallet") == 0)
{
if(!walletOpen)
WalletServerSession::openWallet(data);
else
walletServer.sendErrorMessage(108, sessionId, data.correlationId, data.command);
}
else if(data.command.compare("closewallet") == 0)
{
WalletServerSession::closeWallet(data);
}
else if(data.command.compare("getinfo") == 0)
{
if(walletOpen)
WalletServerSession::getWalletInfo(data);
else
walletServer.sendErrorMessage(109, sessionId, data.correlationId, data.command);
}
else if(data.command.compare("getaddresslist") == 0)
{
if(walletOpen)
WalletServerSession::getAddressBook(data);
else
walletServer.sendErrorMessage(109, sessionId, data.correlationId, data.command);
}
else if(data.command.compare("sendtoaddress") == 0)
{
if(walletOpen)
WalletServerSession::sendCoinsToAddress(data);
else
walletServer.sendErrorMessage(109, sessionId, data.correlationId, data.command);
}
else if(data.command.compare("closesession") == 0)
{
WalletServerSession::closeSession();
}
else
{
printf("WalletServerSession command not found: %s\n", data.command.c_str());
walletServer.sendErrorMessage(110, sessionId, data.correlationId, data.command);
}
}
}
void WalletServerSession::closeWalletIfOpen()
{
printf("Close WalletServerSession sessionId: %s - Current WalletId: %s - Current Thread ID: %s\n",
sessionId.c_str(), walletId.c_str(), boost::lexical_cast<std::string>(boost::this_thread::get_id()).c_str());
if(walletOpen)
{
// detach and close wallet file
printf("%s detach\n", clientWallet->strWalletFile.c_str());
bitdb.dbenv.lsn_reset(clientWallet->strWalletFile.c_str(), 0);
printf("%s closed\n", clientWallet->strWalletFile.c_str());
// Create close wallet result message
json_spirit::Object outputJson;
outputJson.push_back(json_spirit::Pair("sessionid", sessionId));
outputJson.push_back(json_spirit::Pair("command", "closewallet"));
json_spirit::Object result;
result.push_back(json_spirit::Pair("errorCode", 0));
result.push_back(json_spirit::Pair("errorMessage", ""));
outputJson.push_back(json_spirit::Pair("result", result));
// send result to out queue
WalletServerSession::sendMessageToQueue(outputJson);
// Close Queue connection
printf("WalletServerSession sessionId: %s stop stomp client.\n", this->sessionId.c_str());
this->session_stomp_client->stop();
printf("WalletServerSession sessionId: %s delete stomp client.\n", this->sessionId.c_str());
delete this->session_stomp_client;
printf("WalletServerSession sessionId: %s wallet close finished.\n", sessionId.c_str());
walletOpen = false;
walletServer.setWalletOpen(sessionId, false);
}
}
void WalletServerSession::openWallet(Command data)
{
printf("WalletServerSession sessionId: %s Execute %s\n", this->sessionId.c_str(), data.command.c_str());
// define output object
json_spirit::Object outputJson;
outputJson.push_back(json_spirit::Pair("sessionid", sessionId));
outputJson.push_back(json_spirit::Pair("correlationid", data.correlationId));
outputJson.push_back(json_spirit::Pair("command", "openWallet"));
// get WalletId from command arguments
std::string openWalletId = "";
std::map<std::string, std::string>::iterator it;
it = data.arguments.find("walletid");
if(it != data.arguments.end())
{
openWalletId = it->second;
}
if(openWalletId.length() == 0)
{
// send error message
json_spirit::Object result;
result.push_back(json_spirit::Pair("errorCode", 101));
result.push_back(json_spirit::Pair("errorMessage", "No Wallet ID supplied in arguments array."));
outputJson.push_back(json_spirit::Pair("result", result));
}
else
{
// verify walletId/accountId combination is valid
bool commandValid = walletServer.isWalletAccountValid(openWalletId, data.accountId);
if(commandValid)
{
// check wallet file is available on filesystem
std::string walletFilenameString = openWalletId + ".dat";
this->walletFilename = walletServer.getWalletServerPath() / walletFilenameString;
if(boost::filesystem::exists(this->walletFilename))
{
printf("Wallet File Exists so open the wallet: %s\n", this->walletFilename.string().c_str());
// open wallet
int64 nStart = GetTimeMillis();
bool fFirstRun = true;
clientWallet = new CWallet(this->walletFilename.string());
DBErrors nLoadWalletRet = clientWallet->LoadWallet(fFirstRun);
std::ostringstream strLoadResult;
if (nLoadWalletRet != DB_LOAD_OK)
{
if (nLoadWalletRet == DB_CORRUPT)
strLoadResult << "Error loading wallet file: Wallet corrupted";
else if (nLoadWalletRet == DB_NONCRITICAL_ERROR)
{
strLoadResult << "Warning: error reading wallet file! All keys read correctly, but transaction data"
" or address book entries might be missing or incorrect.";
}
else if (nLoadWalletRet == DB_TOO_NEW)
strLoadResult << "Error loading wallet file: Wallet requires newer version of CasinoCoin";
else if (nLoadWalletRet == DB_NEED_REWRITE)
{
strLoadResult << "Wallet needed to be rewritten: restart CasinoCoin to complete";
}
else
strLoadResult << "Error loading " << walletFilenameString.c_str();
// load wallet result
printf("WalletServerSession - Load Wallet result: %s\n", strLoadResult.str().c_str());
// send error message
json_spirit::Object result;
result.push_back(json_spirit::Pair("errorCode", 103));
std::string openWalletError = std::string("Open Wallet Error: ");
openWalletError.append(strLoadResult.str());
result.push_back(json_spirit::Pair("errorMessage", openWalletError));
outputJson.push_back(json_spirit::Pair("result", result));
}
else
{
// connect to new Transaction Notifications
printf("WalletServerSession - Connect to new Transaction Notification\n");
clientWallet->NotifyTransactionChanged.connect(boost::bind(&WalletServerSession::NotifyTransactionChanged, this, _1, _2, _3));
// set wallet open in session
walletOpen = true;
walletServer.setWalletOpen(sessionId, true);
walletServer.setLastCommandTime(sessionId, (int)time(NULL));
// get blockchain best block
CBlockIndex *pindexBlockchain = pindexBest;
// get wallet genesis block
CBlockIndex *pindexWalletGenesisBlock;
CBlockLocator genesisLocator;
if(clientWallet->GetWalletGenesisBlock(genesisLocator))
pindexWalletGenesisBlock = genesisLocator.GetBlockIndex();
else
pindexWalletGenesisBlock = pindexGenesisBlock;
// get wallet best block
CBlockLocator walletLocator;
CBlockIndex *pindexWallet;
if (clientWallet->GetBestChain(walletLocator))
pindexWallet = walletLocator.GetBlockIndex();
else
pindexWallet = pindexWalletGenesisBlock;
printf("WalletServerSession - pindexBlockchain: %i pindexWallet: %i pindexWalletGenesisBlock: %i\n", pindexBlockchain->nHeight, pindexWallet->nHeight, pindexWalletGenesisBlock->nHeight);
if(pindexBlockchain->nHeight > pindexWallet->nHeight)
{
CBlockIndex *pindexRescan = pindexWallet;
if(pindexWalletGenesisBlock->nHeight > pindexRescan->nHeight)
pindexRescan = pindexWalletGenesisBlock;
printf("WalletServerSession - Rescanning last %i blocks (from block %i) for wallet %s\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight, walletFilenameString.c_str());
nStart = GetTimeMillis();
clientWallet->ScanForWalletTransactions(pindexRescan);
printf("WalletServerSession - rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart);
clientWallet->SetBestChain(CBlockLocator(pindexBest));
nWalletDBUpdated++;
}
// Add wallet transactions that aren't already in a block to mapTransactions
clientWallet->ReacceptWalletTransactions();
// set walletId in session
walletId = openWalletId;
// send result message to out queue
json_spirit::Object result;
result.push_back(json_spirit::Pair("errorCode", 0));
result.push_back(json_spirit::Pair("errorMessage", ""));
outputJson.push_back(json_spirit::Pair("result", result));
}
}
else
{
// send error message
json_spirit::Object result;
result.push_back(json_spirit::Pair("errorCode", 103));
std::string openWalletFileError = "Wallet file " + this->walletFilename.string() + " does not exist on WalletServer.";
result.push_back(json_spirit::Pair("errorMessage", openWalletFileError));
outputJson.push_back(json_spirit::Pair("result", result));
}
}
else
{
// send error message
json_spirit::Object result;
result.push_back(json_spirit::Pair("errorCode", 102));
result.push_back(json_spirit::Pair("errorMessage", "Invalid Account ID for given Wallet ID."));
outputJson.push_back(json_spirit::Pair("result", result));
}
}
// send result to out queue
WalletServerSession::sendMessageToQueue(outputJson);
}
void WalletServerSession::closeWallet(Command data)
{
printf("WalletServerSession sessionId: %s Execute closeWallet\n", sessionId.c_str());
closeWalletIfOpen();
}
json_spirit::Value WalletServerSession::getWalletInfo(Command data)
{
printf("WalletServerSession sessionId: %s Execute getWalletInfo\n", this->sessionId.c_str());
// define output object
json_spirit::Object outputJson;
outputJson.push_back(json_spirit::Pair("sessionid", sessionId));
outputJson.push_back(json_spirit::Pair("correlationid", data.correlationId));
outputJson.push_back(json_spirit::Pair("command", "getinfo"));
// add wallet info
json_spirit::Object result;
result.push_back(json_spirit::Pair("errorCode", 0));
result.push_back(json_spirit::Pair("errorMessage", ""));
result.push_back(json_spirit::Pair("version",(int)CLIENT_VERSION));
result.push_back(json_spirit::Pair("protocolversion",(int)PROTOCOL_VERSION));
result.push_back(json_spirit::Pair("blocks", (int)nBestHeight));
result.push_back(json_spirit::Pair("coinsupply", FormatMoney(GetTotalCoinSupply(nBestHeight,false),false)));
result.push_back(json_spirit::Pair("timeoffset", (boost::int64_t)GetTimeOffset()));
result.push_back(json_spirit::Pair("connections",(int)vNodes.size()));
result.push_back(json_spirit::Pair("difficulty", (double)GetDifficulty()));
if (clientWallet) {
result.push_back(json_spirit::Pair("walletversion", clientWallet->GetVersion()));
result.push_back(json_spirit::Pair("defaultaddress", CBitcoinAddress(clientWallet->vchDefaultKey.GetID()).ToString()));
result.push_back(json_spirit::Pair("balance", FormatMoney(clientWallet->GetBalance(),false)));
result.push_back(json_spirit::Pair("unconfirmedbalance", FormatMoney(clientWallet->GetUnconfirmedBalance(),false)));
balancesMapType balances = clientWallet->GetAddressBalances();
json_spirit::Array addressBalanceArray;
BOOST_FOREACH(balancesMapType::value_type balance, balances)
{
json_spirit::Object addressInfo;
addressInfo.push_back(json_spirit::Pair("address",CBitcoinAddress(balance.first).ToString()));
addressInfo.push_back(json_spirit::Pair("balance", ValueFromAmount(balance.second)));
addressBalanceArray.push_back(addressInfo);
}
result.push_back(json_spirit::Pair("addresses", addressBalanceArray));
result.push_back(json_spirit::Pair("keypoololdest",(boost::int64_t)clientWallet->GetOldestKeyPoolTime()));
result.push_back(json_spirit::Pair("keypoolsize", (int)clientWallet->GetKeyPoolSize()));
}
result.push_back(json_spirit::Pair("paytxfee", FormatMoney(CTransaction::nMinTxFee, false)));
result.push_back(json_spirit::Pair("mininput", FormatMoney(nMinimumInputValue, false)));
if (clientWallet && clientWallet->IsCrypted())
result.push_back(json_spirit::Pair("unlocked_until", (boost::int64_t)nWalletUnlockTime));
outputJson.push_back(json_spirit::Pair("result", result));
// send result to out queue
WalletServerSession::sendMessageToQueue(outputJson);
return outputJson;
}
json_spirit::Value WalletServerSession::getAddressBook(Command data)
{
printf("WalletServerSession sessionId: %s Execute getAddressBook\n", sessionId.c_str());
balancesMapType balances = clientWallet->GetAddressBalances();
// define output object
json_spirit::Object outputJson;
outputJson.push_back(json_spirit::Pair("sessionid", sessionId));
outputJson.push_back(json_spirit::Pair("correlationid", data.correlationId));
outputJson.push_back(json_spirit::Pair("command", data.command));
// add wallet info
json_spirit::Object result;
result.push_back(json_spirit::Pair("errorCode", 0));
result.push_back(json_spirit::Pair("errorMessage", ""));
json_spirit::Array addressBalanceArray;
BOOST_FOREACH(balancesMapType::value_type balance, balances)
{
json_spirit::Object addressInfo;
addressInfo.push_back(json_spirit::Pair("address",CBitcoinAddress(balance.first).ToString()));
addressInfo.push_back(json_spirit::Pair("balance", ValueFromAmount(balance.second)));
addressBalanceArray.push_back(addressInfo);
}
result.push_back(json_spirit::Pair("addresses", addressBalanceArray));
outputJson.push_back(json_spirit::Pair("result", result));
// send result to out queue
WalletServerSession::sendMessageToQueue(outputJson);
return outputJson;
}
json_spirit::Value WalletServerSession::sendCoinsToAddress(Command data)
{
std::string strAddress = "";
std::string strAmount = "";
std::string strComment = "";
// loop over arguments and get the values
std::map<std::string, std::string>::iterator argit;
for(argit = data.arguments.begin(); argit != data.arguments.end(); argit++) {
if(argit->first.compare("address")==0)
strAddress = argit->second;
else if(argit->first.compare("amount")==0)
strAmount = argit->second;
else if(argit->first.compare("comment")==0)
strComment = argit->second;
}
printf("WalletServerSession: %s sendCoinsToAddress: %s Amount: %s\n", sessionId.c_str(), strAddress.c_str(), strAmount.c_str());
// define output object
json_spirit::Object outputJson;
outputJson.push_back(json_spirit::Pair("sessionid", sessionId));
outputJson.push_back(json_spirit::Pair("correlationid", data.correlationId));
outputJson.push_back(json_spirit::Pair("command", data.command));
// create coin address
CBitcoinAddress address(strAddress);
if (!address.IsValid())
{
// send error message
json_spirit::Object result;
result.push_back(json_spirit::Pair("errorCode", 111));
result.push_back(json_spirit::Pair("errorMessage", "Invalid CasinoCoin address."));
outputJson.push_back(json_spirit::Pair("result", result));
// send result to out queue
WalletServerSession::sendMessageToQueue(outputJson);
return outputJson;
}
// Amount
int64 nAmount;
ParseMoney(strAmount, nAmount);
if (nAmount <= 0)
{
// send error message
json_spirit::Object result;
result.push_back(json_spirit::Pair("errorCode", 112));
result.push_back(json_spirit::Pair("errorMessage", "Amount of coins to sent to address must be greater than 0."));
outputJson.push_back(json_spirit::Pair("result", result));
// send result to out queue
WalletServerSession::sendMessageToQueue(outputJson);
return outputJson;
}
// Wallet comments
CWalletTx wtx;
if(!strComment.empty())
wtx.mapValue["comment"] = strComment;
// check if wallet is locked
// if (pwalletMain->IsLocked())
// throw JSONRPCError(RPC_WALLET_UNLOCK_NEEDED, "Error: Please enter the wallet passphrase with walletpassphrase first.");
// execute send
string strError = clientWallet->SendMoneyToDestination(address.Get(), nAmount, wtx);
if (strError != "")
{
// send error message
json_spirit::Object result;
result.push_back(json_spirit::Pair("errorCode", 10));
result.push_back(json_spirit::Pair("errorMessage", "Error sending coins: " + strError));
outputJson.push_back(json_spirit::Pair("result", result));
}
else
{
json_spirit::Object result;
result.push_back(json_spirit::Pair("errorCode", 0));
result.push_back(json_spirit::Pair("errorMessage", ""));
result.push_back(json_spirit::Pair("txid", wtx.GetHash().GetHex()));
outputJson.push_back(json_spirit::Pair("result", result));
}
// send result to out queue
WalletServerSession::sendMessageToQueue(outputJson);
return outputJson;
}
void WalletServerSession::closeSession()
{
printf("WalletServerSession sessionId: %s Execute closeSession\n", sessionId.c_str());
closeWalletIfOpen();
// remove wallet object
if(clientWallet != NULL)
delete clientWallet;
// set shutdownComplete
shutdownComplete = true;
printf("WalletServerSession sessionId: %s Session Close Finished!\n", sessionId.c_str());
}

95
src/walletserversession.h Normal file
View File

@@ -0,0 +1,95 @@
#ifndef WALLETSERVERSESSION_H
#define WALLETSERVERSESSION_H
#include <string>
#include "walletserver.h"
#include "wallet.h"
#include "json/json_spirit.h"
#include "stomp/booststomp.h"
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/mutex.hpp>
typedef std::map<CTxDestination, int64> balancesMapType;
// Class that consumes objects from a queue
class WalletServerSession
{
private:
SynchronisedCommandQueue<Command>* m_queue; // The queue to use
std::string sessionId; // The id of the wallet session
std::string walletId; // The wallet id of the session
boost::filesystem::path walletFilename;
// ActiveMQ Connection
STOMP::BoostStomp* session_stomp_client;
// Wallet
CWallet* clientWallet;
bool walletOpen;
// Handle new block signal
void NotifyBlocksChanged();
// Handle new transaction signal
void NotifyTransactionChanged(CWallet *wallet, const uint256 &hash, ChangeType status);
// shutdown condition
bool shutdownComplete;
// wallet commands
void openWallet(Command data);
void closeWallet(Command data);
json_spirit::Value getWalletInfo(Command data);
json_spirit::Value getAddressBook(Command data);
json_spirit::Value sendCoinsToAddress(Command data);
public:
// Constructor with id and the queue to use.
WalletServerSession(std::string newSessionId, SynchronisedCommandQueue<Command>* queue);
// Destructor
~WalletServerSession();
// Default operator that starts the ActiveMQ connection and reads data from the WalletServer queue
void operator () ()
{
printf("WalletServerSession - ActiveMQ connection for session: %s\n", sessionId.c_str());
// initialize wallet pointer to NULL
clientWallet = NULL;
shutdownComplete = false;
// initiate a new BoostStomp client
session_stomp_client = new STOMP::BoostStomp(WalletServer::stomp_host, WalletServer::stomp_port);
session_stomp_client->enable_debug_msgs(false);
// start the client, (by connecting to the STOMP server)
session_stomp_client->start();
// connect to Signals
uiInterface.NotifyBlocksChanged.connect(boost::bind(&WalletServerSession::NotifyBlocksChanged, this));
printf("WalletServerSession - Start Dequeue for session: %s\n", sessionId.c_str());
while (true)
{
// Get the data from the queue and print it
Command data = m_queue->Dequeue();
printf("Consumer Session: %s consumed: %s for session: %s ThreadID: %s\n",
sessionId.c_str(), data.command.c_str(), data.sessionId.c_str(),
boost::lexical_cast<std::string>(boost::this_thread::get_id()).c_str());
executeWalletCommand(data);
// if closesesion command then wait for shutdown complete
if(data.command.compare("closesession") == 0)
{
while(!shutdownComplete)
{
printf("Wait until closesession shutdownComplete");
MilliSleep(100);
}
}
// Make sure we can be interrupted
boost::this_thread::interruption_point();
}
}
// public methods
void sendMessageToQueue(json_spirit::Object outputJson);
void executeWalletCommand(Command data);
void closeWalletIfOpen();
void setWalletOpen();
bool isWalletOpen();
void closeSession();
};
#endif // WALLETSERVERSESSION_H

View File

@@ -1,45 +0,0 @@
; Script generated by the Inno Setup Script Wizard.
; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!
#define MyAppName "Casinocoin"
#define MySetupAppName "casinocoin"
#define MyAppVersion "3.0.0.0"
#define MyAppPublisher "Casinocoin Foundation"
#define MyAppURL "http://www.casinocoin.org"
#define MyAppExeName "casinocoin-qt.exe"
[Setup]
; NOTE: The value of AppId uniquely identifies this application.
; Do not use the same AppId value in installers for other applications.
; (To generate a new GUID, click Tools | Generate GUID inside the IDE.)
AppId={{1698FEC3-9D7C-43F3-B379-9028E51F8B56}
AppName={#MyAppName}
AppVersion={#MyAppVersion}
;AppVerName={#MyAppName} {#MyAppVersion}
AppPublisher={#MyAppPublisher}
AppPublisherURL={#MyAppURL}
AppSupportURL={#MyAppURL}
AppUpdatesURL={#MyAppURL}
DefaultDirName={pf}\{#MyAppName}
DisableProgramGroupPage=yes
OutputBaseFilename={#MySetupAppName}-{#MyAppVersion}-setup
Compression=lzma
SolidCompression=yes
[Languages]
Name: "english"; MessagesFile: "compiler:Default.isl"
[Tasks]
Name: "desktopicon"; Description: "{cm:CreateDesktopIcon}"; GroupDescription: "{cm:AdditionalIcons}"; Flags: unchecked
[Files]
Source: "C:\Users\a.jochems\Documents\GitHub\casinocoin-development\release\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
; NOTE: Don't use "Flags: ignoreversion" on any shared system files
[Icons]
Name: "{commonprograms}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"
Name: "{commondesktop}\{#MyAppName}"; Filename: "{app}\{#MyAppExeName}"; Tasks: desktopicon
[Run]
Filename: "{app}\{#MyAppExeName}"; Description: "{cm:LaunchProgram,{#StringChange(MyAppName, '&', '&&')}}"; Flags: nowait postinstall skipifsilent